提交 9d99b46d 编写于 作者: J jrose

7013417: JSR 292 needs to support variadic method handle calls

Summary: Implement MH.asVarargsCollector, etc., and remove withTypeHandler.
Reviewed-by: twisti
上级 7440a203
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -135,7 +135,10 @@ public class MethodHandles {
* <p>
* In general, the conditions under which a method handle may be
* created for a method {@code M} are exactly as restrictive as the conditions
* under which the lookup class could have compiled a call to {@code M}.
* under which the lookup class could have compiled a call to {@code M},
* or could have compiled an {@code ldc} instruction loading a
* {@code CONSTANT_MethodHandle} of M.
* The same point is true of fields and constructors.
* <p>
* In some cases, this access is obtained by the Java compiler by creating
* an wrapper method to access a private method of another class
......@@ -379,6 +382,10 @@ public class MethodHandles {
* The method and all its argument types must be accessible to the lookup class.
* If the method's class has not yet been initialized, that is done
* immediately, before the method handle is returned.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set.
* @param refc the class from which the method is accessed
* @param name the name of the method
* @param type the type of the method
......@@ -403,6 +410,10 @@ public class MethodHandles {
* implementation to enter.
* (The dispatching action is identical with that performed by an
* {@code invokevirtual} or {@code invokeinterface} instruction.)
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set.
* @param refc the class or interface from which the method is accessed
* @param name the name of the method
* @param type the type of the method, with the receiver argument omitted
......@@ -427,6 +438,10 @@ public class MethodHandles {
* <p>
* Note: The requested type must have a return type of {@code void}.
* This is consistent with the JVM's treatment of constructor signatures.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the constructor's variable arity modifier bit ({@code 0x0080}) is set.
* @param refc the class or interface from which the method is accessed
* @param type the type of the method, with the receiver argument omitted, and a void return type
* @return the desired method handle
......@@ -438,7 +453,23 @@ public class MethodHandles {
assert(ctor.isConstructor());
checkAccess(refc, ctor);
MethodHandle rawMH = MethodHandleImpl.findMethod(IMPL_TOKEN, ctor, false, lookupClassOrNull());
return MethodHandleImpl.makeAllocator(IMPL_TOKEN, rawMH);
MethodHandle allocMH = MethodHandleImpl.makeAllocator(IMPL_TOKEN, rawMH);
return fixVarargs(allocMH, rawMH);
}
/** Return a version of MH which matches matchMH w.r.t. isVarargsCollector. */
private static MethodHandle fixVarargs(MethodHandle mh, MethodHandle matchMH) {
boolean va1 = mh.isVarargsCollector();
boolean va2 = matchMH.isVarargsCollector();
if (va1 == va2) {
return mh;
} else if (va2) {
MethodType type = mh.type();
int arity = type.parameterCount();
return mh.asVarargsCollector(type.parameterType(arity-1));
} else {
throw new InternalError("already varargs, but template is not: "+mh);
}
}
/**
......@@ -458,6 +489,10 @@ public class MethodHandles {
* If the explicitly specified caller class is not identical with the
* lookup class, or if this lookup object does not have private access
* privileges, the access fails.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set.
* @param refc the class or interface from which the method is accessed
* @param name the name of the method (which must not be "&lt;init&gt;")
* @param type the type of the method, with the receiver argument omitted
......@@ -547,13 +582,26 @@ public class MethodHandles {
* so that every call to the method handle will invoke the
* requested method on the given receiver.
* <p>
* This is equivalent to the following expression:
* <code>
* {@link #insertArguments insertArguments}({@link #findVirtual findVirtual}(defc, name, type), receiver)
* </code>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set
* <em>and</em> the trailing array argument is not the only argument.
* (If the trailing array argument is the only argument,
* the given receiver value will be bound to it.)
* <p>
* This is equivalent to the following code:
* <blockquote><pre>
MethodHandle mh0 = {@link #findVirtual findVirtual}(defc, name, type);
MethodHandle mh1 = mh0.{@link MethodHandle#bindTo bindTo}(receiver);
MethodType mt1 = mh1.type();
if (mh0.isVarargsCollector() && mt1.parameterCount() > 0) {
mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
return mh1;
* </pre></blockquote>
* where {@code defc} is either {@code receiver.getClass()} or a super
* type of that class, in which the requested method is accessible
* to the lookup class.
* (Note that {@code bindTo} does not preserve variable arity.)
* @param receiver the object from which the method is accessed
* @param name the name of the method
* @param type the type of the method, with the receiver argument omitted
......@@ -568,7 +616,9 @@ public class MethodHandles {
MethodHandle bmh = MethodHandleImpl.bindReceiver(IMPL_TOKEN, dmh, receiver);
if (bmh == null)
throw newNoAccessException(method, lookupClass());
return bmh;
if (dmh.type().parameterCount() == 0)
return dmh; // bound the trailing parameter; no varargs possible
return fixVarargs(bmh, dmh);
}
/**
......@@ -581,6 +631,10 @@ public class MethodHandles {
* If the method's {@code accessible} flag is not set,
* access checking is performed immediately on behalf of the lookup class.
* If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set.
* @param m the reflected method
* @return a method handle which can invoke the reflected method
* @exception NoAccessException if access checking fails
......@@ -603,6 +657,10 @@ public class MethodHandles {
* If the method's {@code accessible} flag is not set,
* access checking is performed immediately on behalf of the lookup class,
* as if {@code invokespecial} instruction were being linked.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the method's variable arity modifier bit ({@code 0x0080}) is set.
* @param m the reflected method
* @param specialCaller the class nominally calling the method
* @return a method handle which can invoke the reflected method
......@@ -628,6 +686,10 @@ public class MethodHandles {
* <p>
* If the constructor's {@code accessible} flag is not set,
* access checking is performed immediately on behalf of the lookup class.
* <p>
* The returned method handle will have
* {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
* the constructor's variable arity modifier bit ({@code 0x0080}) is set.
* @param c the reflected constructor
* @return a method handle which can invoke the reflected constructor
* @exception NoAccessException if access checking fails
......@@ -637,7 +699,8 @@ public class MethodHandles {
assert(ctor.isConstructor());
if (!c.isAccessible()) checkAccess(c.getDeclaringClass(), ctor);
MethodHandle rawCtor = MethodHandleImpl.findMethod(IMPL_TOKEN, ctor, false, lookupClassOrNull());
return MethodHandleImpl.makeAllocator(IMPL_TOKEN, rawCtor);
MethodHandle allocator = MethodHandleImpl.makeAllocator(IMPL_TOKEN, rawCtor);
return fixVarargs(allocator, rawCtor);
}
/**
......@@ -785,7 +848,8 @@ public class MethodHandles {
MethodType rawType = mh.type();
if (rawType.parameterType(0) == caller) return mh;
MethodType narrowType = rawType.changeParameterType(0, caller);
return MethodHandleImpl.convertArguments(IMPL_TOKEN, mh, narrowType, rawType, null);
MethodHandle narrowMH = MethodHandleImpl.convertArguments(IMPL_TOKEN, mh, narrowType, rawType, null);
return fixVarargs(narrowMH, mh);
}
MethodHandle makeAccessor(Class<?> refc, String name, Class<?> type,
......@@ -909,22 +973,21 @@ public class MethodHandles {
* <p>
* This method is equivalent to the following code (though it may be more efficient):
* <p><blockquote><pre>
* MethodHandle invoker = lookup().findVirtual(MethodHandle.class, "invokeGeneric", type);
* MethodType vaType = MethodType.genericMethodType(objectArgCount, true);
* vaType = vaType.insertParameterType(0, MethodHandle.class);
* int spreadArgCount = type.parameterCount - objectArgCount;
* invoker = invoker.asSpreader(Object.class, spreadArgCount);
* return invoker.asType(vaType);
MethodHandle invoker = publicLookup()
.findVirtual(MethodHandle.class, "invokeGeneric", type)
int spreadArgCount = type.parameterCount - objectArgCount;
invoker = invoker.asSpreader(Object[].class, spreadArgCount);
return invoker;
* </pre></blockquote>
* @param type the desired target type
* @param objectArgCount number of fixed (non-varargs) {@code Object} arguments
* @return a method handle suitable for invoking any method handle of the given type
*/
static public
MethodHandle varargsInvoker(MethodType type, int objectArgCount) {
MethodHandle spreadInvoker(MethodType type, int objectArgCount) {
if (objectArgCount < 0 || objectArgCount > type.parameterCount())
throw new IllegalArgumentException("bad argument count "+objectArgCount);
return invokers(type).varargsInvoker(objectArgCount);
return invokers(type).spreadInvoker(objectArgCount);
}
/**
......@@ -1826,7 +1889,10 @@ System.out.println((int) f0.invokeExact("x", "y")); // 2
* the given {@code target} on the incoming arguments,
* and returning or throwing whatever the {@code target}
* returns or throws. The invocation will be as if by
* {@code target.invokeExact}.
* {@code target.invokeGeneric}.
* The target's type will be checked before the SAM
* instance is created, as if by a call to {@code asType},
* which may result in a {@code WrongMethodTypeException}.
* <p>
* The method handle may throw an <em>undeclared exception</em>,
* which means any checked exception (or other checked throwable)
......@@ -1874,15 +1940,17 @@ System.out.println((int) f0.invokeExact("x", "y")); // 2
* {@link java.dyn.MethodHandles.AsInstanceObject AsInstanceObject}
* in the adapters, so that generic code can extract the underlying
* method handle without knowing where the SAM adapter came from.
* <p>
* Future versions of this API may accept additional types,
* such as abstract classes with single abstract methods.
* @param target the method handle to invoke from the wrapper
* @param samType the desired type of the wrapper, a SAM type
* @return a correctly-typed wrapper for the given {@code target}
* @throws IllegalArgumentException if the {@code target} throws
* an undeclared exception
* @throws IllegalArgumentException if the {@code samType} is not a
* valid argument to this method
* @throws WrongMethodTypeException if the {@code target} cannot
* be converted to the type required by the SAM type
*/
// ISSUE: Should we delegate equals/hashCode to the targets?
// Not useful unless there is a stable equals/hashCode behavior
// for MethodHandle, but there isn't.
public static
<T> T asInstance(final MethodHandle target, final Class<T> samType) {
// POC implementation only; violates the above contract several ways
......@@ -1890,8 +1958,9 @@ System.out.println((int) f0.invokeExact("x", "y")); // 2
if (sam == null)
throw new IllegalArgumentException("not a SAM type: "+samType.getName());
MethodType samMT = MethodType.methodType(sam.getReturnType(), sam.getParameterTypes());
if (!samMT.equals(target.type()))
throw new IllegalArgumentException("wrong method type: "+target+" should match "+sam);
MethodHandle checkTarget = target.asType(samMT); // make throw WMT
checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
final MethodHandle vaTarget = checkTarget.asSpreader(Object[].class, samMT.parameterCount());
return samType.cast(Proxy.newProxyInstance(
samType.getClassLoader(),
new Class[]{ samType, AsInstanceObject.class },
......@@ -1905,7 +1974,7 @@ System.out.println((int) f0.invokeExact("x", "y")); // 2
if (method.getDeclaringClass() == AsInstanceObject.class)
return getArg(method.getName());
if (method.equals(sam))
return target.invokeVarargs(args);
return vaTarget.invokeExact(args);
if (isObjectMethod(method))
return callObjectMethod(this, method, args);
throw new InternalError();
......@@ -1991,7 +2060,7 @@ System.out.println((int) f0.invokeExact("x", "y")); // 2
}
/*non-public*/
static MethodHandle withTypeHandler(MethodHandle target, MethodHandle typeHandler) {
return MethodHandleImpl.withTypeHandler(IMPL_TOKEN, target, typeHandler);
static MethodHandle asVarargsCollector(MethodHandle target, Class<?> arrayType) {
return MethodHandleImpl.asVarargsCollector(IMPL_TOKEN, target, arrayType);
}
}
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -166,13 +166,13 @@
* normal accesses are legal.
* <p>
* A constant may refer to a method or constructor with the {@code varargs}
* bit (hexadecimal {@code 80}) set in its modifier bitmask.
* The method handle constant produced for such a method behaves the same
* bit (hexadecimal {@code 0x0080}) set in its modifier bitmask.
* The method handle constant produced for such a method behaves as if
* it were created by {@link java.dyn.MethodHandle#asVarargsCollector asVarargsCollector}.
* In other words, the constant method handle will exhibit variable arity,
* when invoked via {@code invokeGeneric}.
* On the other hand, its behavior with respect to {@code invokeExact} will be the same
* as if the {@code varargs} bit were not set.
* The argument-collecting behavior of {@code varargs} can be emulated by
* adapting the method handle constant with
* {@link java.dyn.MethodHandle#asCollector asCollector}.
* There is no provision for doing this automatically.
* <p>
* Although the {@code CONSTANT_MethodHandle} and {@code CONSTANT_MethodType} constant types
* resolve class names, they do not force class initialization.
......@@ -369,21 +369,40 @@
* the instruction's bootstrap method will be invoked on three arguments,
* conveying the instruction's caller class, name, and method type.
* If the {@code invokedynamic} instruction specifies one or more static arguments,
* a fourth argument will be passed to the bootstrap argument,
* either an {@code Object} reference to the sole extra argument (if there is one)
* or an {@code Object} array of references to all the arguments (if there are two or more),
* as if the bootstrap method is a variable-arity method.
* those values will be passed as additional arguments to the method handle.
* (Note that because there is a limit of 255 arguments to any method,
* at most 252 extra arguments can be supplied.)
* The bootstrap method will be invoked as if by either {@code invokeGeneric}
* or {@code invokeWithArguments}. (There is no way to tell the difference.)
* If the bootstrap method is a variable arity method (its modifier bit {@code 0x0080} is set),
* then some or all of the arguments specified here may be collected into a trailing array parameter.
* (This is not a special rule, but rather a useful consequence of the interaction
* between {@code CONSTANT_MethodHandle} constants, the modifier bit for variable arity methods,
* and the {@code java.dyn.MethodHandle#asVarargsCollector asVarargsCollector} transformation.)
* <p>
* Given these rules, here are examples of legal bootstrap method declarations,
* given various numbers {@code N} of extra arguments.
* The first rows (marked {@code *}) will work for any number of extra arguments.
* <code>
* <table border=1 cellpadding=5 summary="Static argument types">
* <tr><th>N</th><th>sample bootstrap method</th></tr>
* <tr><td>*</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)</code></td></tr>
* <tr><td>*</td><td><code>CallSite bootstrap(Object... args)</code></td></tr>
* <tr><td>*</td><td><code>CallSite bootstrap(Object caller, Object... nameAndTypeWithArgs)</code></td></tr>
* <tr><td>0</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type)</code></td></tr>
* <tr><td>0</td><td><code>CallSite bootstrap(Lookup caller, Object... nameAndType)</code></td></tr>
* <tr><td>1</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type, Object arg)</code></td></tr>
* <tr><td>2</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)</code></td></tr>
* <tr><td>2</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type, String... args)</code></td></tr>
* <tr><td>2</td><td><code>CallSite bootstrap(Lookup caller, String name, MethodType type, String x, int y)</code></td></tr>
* </table>
* </code>
* The last example assumes that the extra arguments are of type
* {@code CONSTANT_String} and {@code CONSTANT_Integer}, respectively.
* The second-to-last example assumes that all extra arguments are of type
* {@code CONSTANT_String}.
* The other examples work with all types of extra arguments.
* <p>
* The argument and return types listed here are used by the {@code invokeGeneric}
* call to the bootstrap method.
* As noted above, the actual method type of the bootstrap method can vary.
* For example, the fourth argument could be {@code MethodHandle},
* if that is the type of the corresponding constant in
......@@ -391,14 +410,8 @@
* In that case, the {@code invokeGeneric} call will pass the extra method handle
* constant as an {@code Object}, but the type matching machinery of {@code invokeGeneric}
* will cast the reference back to {@code MethodHandle} before invoking the bootstrap method.
* (If a string constant were passed instead, by badly generated code, that cast would then fail.)
* <p>
* If the fourth argument is an array, the array element type must be {@code Object},
* since object arrays (as produced by the JVM at this point) cannot be converted
* to other array types.
* <p>
* If an array is provided, it will appear to be freshly allocated.
* That is, the same array will not appear to two bootstrap method calls.
* (If a string constant were passed instead, by badly generated code, that cast would then fail,
* resulting in an {@code InvokeDynamicBootstrapError}.)
* <p>
* Extra bootstrap method arguments are intended to allow language implementors
* to safely and compactly encode metadata.
......@@ -406,24 +419,6 @@
* since each call site could be given its own unique bootstrap method.
* Such a practice is likely to produce large class files and constant pools.
*
* <p style="font-size:smaller;">
* <em>PROVISIONAL API, WORK IN PROGRESS:</em>
* (Usage Note: There is no mechanism for specifying five or more positional arguments to the bootstrap method.
* If there are two or more arguments, the Java code of the bootstrap method is required to extract them from
* a varargs-style object array.
* This design uses varargs because it anticipates some use cases where bootstrap arguments
* contribute components of variable-length structures, such as virtual function tables
* or interpreter token streams.
* Such parameters would be awkward or impossible to manage if represented
* as normal positional method arguments,
* since there would need to be one Java method per length.
* On balance, leaving out the varargs feature would cause more trouble to users than keeping it.
* Also, this design allows bootstrap methods to be called in a limited JVM stack depth.
* At both the user and JVM level, the difference between varargs and non-varargs
* calling sequences can easily be bridged via the
* {@link java.dyn.MethodHandle#asSpreader asSpreader}
* and {@link java.dyn.MethodHandle#asSpreader asCollector} methods.)
*
* <h2><a name="structs"></a>Structure Summary</h2>
* <blockquote><pre>// summary of constant and attribute structures
struct CONSTANT_MethodHandle_info {
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -478,37 +478,60 @@ public class AdapterMethodHandle extends BoundMethodHandle {
return new AdapterMethodHandle(target, newType, makeConv(raw ? OP_RETYPE_RAW : OP_RETYPE_ONLY));
}
static MethodHandle makeTypeHandler(Access token,
MethodHandle target, MethodHandle typeHandler) {
static MethodHandle makeVarargsCollector(Access token,
MethodHandle target, Class<?> arrayType) {
Access.check(token);
return new WithTypeHandler(target, typeHandler);
return new AsVarargsCollector(target, arrayType);
}
static class WithTypeHandler extends AdapterMethodHandle {
final MethodHandle target, typeHandler;
WithTypeHandler(MethodHandle target, MethodHandle typeHandler) {
static class AsVarargsCollector extends AdapterMethodHandle {
final MethodHandle target;
final Class<?> arrayType;
MethodHandle cache;
AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
super(target, target.type(), makeConv(OP_RETYPE_ONLY));
this.target = target;
this.typeHandler = typeHandler.asType(TYPE_HANDLER_TYPE);
this.arrayType = arrayType;
this.cache = target.asCollector(arrayType, 0);
}
@Override
public boolean isVarargsCollector() {
return true;
}
@Override
public MethodHandle asType(MethodType newType) {
if (this.type() == newType)
return this;
MethodType type = this.type();
int collectArg = type.parameterCount() - 1;
int newArity = newType.parameterCount();
if (newArity == collectArg+1 &&
type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
// if arity and trailing parameter are compatible, do normal thing
return super.asType(newType);
}
// check cache
if (cache.type().parameterCount() == newArity)
return cache.asType(newType);
// build and cache a collector
int arrayLength = newArity - collectArg;
MethodHandle collector;
try {
MethodHandle retyped = (MethodHandle) typeHandler.invokeExact(target, newType);
// Contract: Must return the desired type, or throw WMT
if (retyped.type() != newType)
throw new WrongMethodTypeException(retyped.toString());
return retyped;
} catch (Throwable ex) {
if (ex instanceof Error) throw (Error)ex;
if (ex instanceof RuntimeException) throw (RuntimeException)ex;
throw new RuntimeException(ex);
collector = target.asCollector(arrayType, arrayLength);
} catch (IllegalArgumentException ex) {
throw new WrongMethodTypeException("cannot build collector");
}
cache = collector;
return collector.asType(newType);
}
public MethodHandle asVarargsCollector(Class<?> arrayType) {
MethodType type = this.type();
if (type.parameterType(type.parameterCount()-1) == arrayType)
return this;
return super.asVarargsCollector(arrayType);
}
private static final MethodType TYPE_HANDLER_TYPE
= MethodType.methodType(MethodHandle.class, MethodHandle.class, MethodType.class);
}
/** Can a checkcast adapter validly convert the target to newType?
......
......@@ -37,17 +37,17 @@ public class CallSiteImpl {
static CallSite makeSite(MethodHandle bootstrapMethod,
// Callee information:
String name, MethodType type,
// Call-site attributes, if any:
// Extra arguments for BSM, if any:
Object info,
// Caller information:
MemberName callerMethod, int callerBCI) {
Class<?> callerClass = callerMethod.getDeclaringClass();
Object caller;
if (bootstrapMethod.type().parameterType(0) == Class.class)
if (bootstrapMethod.type().parameterType(0) == Class.class && TRANSITIONAL_BEFORE_PFD)
caller = callerClass; // remove for PFD
else
caller = MethodHandleImpl.IMPL_LOOKUP.in(callerClass);
if (bootstrapMethod == null) {
if (bootstrapMethod == null && TRANSITIONAL_BEFORE_PFD) {
// If there is no bootstrap method, throw IncompatibleClassChangeError.
// This is a valid generic error type for resolution (JLS 12.3.3).
throw new IncompatibleClassChangeError
......@@ -56,30 +56,35 @@ public class CallSiteImpl {
CallSite site;
try {
Object binding;
info = maybeReBox(info);
if (info == null) {
if (false) // switch when invokeGeneric works
binding = bootstrapMethod.invokeGeneric(caller, name, type);
else
binding = bootstrapMethod.invokeVarargs(new Object[]{ caller, name, type });
binding = bootstrapMethod.invokeGeneric(caller, name, type);
} else if (!info.getClass().isArray()) {
binding = bootstrapMethod.invokeGeneric(caller, name, type, info);
} else {
info = maybeReBox(info);
if (false) // switch when invokeGeneric works
binding = bootstrapMethod.invokeGeneric(caller, name, type, info);
Object[] argv = (Object[]) info;
if (3 + argv.length > 255)
new InvokeDynamicBootstrapError("too many bootstrap method arguments");
MethodType bsmType = bootstrapMethod.type();
if (bsmType.parameterCount() == 4 && bsmType.parameterType(3) == Object[].class)
binding = bootstrapMethod.invokeGeneric(caller, name, type, argv);
else
binding = bootstrapMethod.invokeVarargs(new Object[]{ caller, name, type, info });
binding = MethodHandles.spreadInvoker(bsmType, 3)
.invokeGeneric(bootstrapMethod, caller, name, type, argv);
}
//System.out.println("BSM for "+name+type+" => "+binding);
if (binding instanceof CallSite) {
site = (CallSite) binding;
} else if (binding instanceof MethodHandle) {
} else if (binding instanceof MethodHandle && TRANSITIONAL_BEFORE_PFD) {
// Transitional!
MethodHandle target = (MethodHandle) binding;
site = new ConstantCallSite(target);
} else {
throw new ClassCastException("bootstrap method failed to produce a MethodHandle or CallSite");
throw new ClassCastException("bootstrap method failed to produce a CallSite");
}
PRIVATE_INITIALIZE_CALL_SITE.invokeExact(site, name, type,
callerMethod, callerBCI);
if (TRANSITIONAL_BEFORE_PFD)
PRIVATE_INITIALIZE_CALL_SITE.invokeExact(site, name, type,
callerMethod, callerBCI);
assert(site.getTarget() != null);
assert(site.getTarget().type().equals(type));
} catch (Throwable ex) {
......@@ -93,6 +98,8 @@ public class CallSiteImpl {
return site;
}
private static boolean TRANSITIONAL_BEFORE_PFD = true; // FIXME: remove for PFD
private static Object maybeReBox(Object x) {
if (x instanceof Integer) {
int xi = (int) x;
......@@ -117,6 +124,7 @@ public class CallSiteImpl {
static {
try {
PRIVATE_INITIALIZE_CALL_SITE =
!TRANSITIONAL_BEFORE_PFD ? null :
MethodHandleImpl.IMPL_LOOKUP.findVirtual(CallSite.class, "initializeFromJVM",
MethodType.methodType(void.class,
String.class, MethodType.class,
......
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2011, 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
......@@ -108,7 +108,7 @@ class InvokeGeneric {
*/
private MethodHandle dispatch(MethodType callerType, MethodHandle target) {
MethodType targetType = target.type();
if (USE_AS_TYPE_PATH || target instanceof AdapterMethodHandle.WithTypeHandler) {
if (USE_AS_TYPE_PATH || target.isVarargsCollector()) {
MethodHandle newTarget = target.asType(callerType);
targetType = callerType;
Invokers invokers = MethodTypeImpl.invokers(Access.TOKEN, targetType);
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -47,7 +47,7 @@ public class Invokers {
private /*lazy*/ MethodHandle genericInvoker;
// generic (untyped) invoker for the outgoing call; accepts a single Object[]
private final /*lazy*/ MethodHandle[] varargsInvokers;
private final /*lazy*/ MethodHandle[] spreadInvokers;
// invoker for an unbound callsite
private /*lazy*/ MethodHandle uninitializedCallSite;
......@@ -55,10 +55,9 @@ public class Invokers {
/** Compute and cache information common to all collecting adapters
* that implement members of the erasure-family of the given erased type.
*/
public Invokers(Access token, MethodType targetType) {
Access.check(token);
/*non-public*/ Invokers(MethodType targetType) {
this.targetType = targetType;
this.varargsInvokers = new MethodHandle[targetType.parameterCount()+1];
this.spreadInvokers = new MethodHandle[targetType.parameterCount()+1];
}
public static MethodType invokerType(MethodType targetType) {
......@@ -69,7 +68,7 @@ public class Invokers {
MethodHandle invoker = exactInvoker;
if (invoker != null) return invoker;
try {
invoker = MethodHandleImpl.IMPL_LOOKUP.findVirtual(MethodHandle.class, "invoke", targetType);
invoker = MethodHandleImpl.IMPL_LOOKUP.findVirtual(MethodHandle.class, "invokeExact", targetType);
} catch (NoAccessException ex) {
throw new InternalError("JVM cannot find invoker for "+targetType);
}
......@@ -101,13 +100,13 @@ public class Invokers {
return invoker;
}
public MethodHandle varargsInvoker(int objectArgCount) {
MethodHandle vaInvoker = varargsInvokers[objectArgCount];
public MethodHandle spreadInvoker(int objectArgCount) {
MethodHandle vaInvoker = spreadInvokers[objectArgCount];
if (vaInvoker != null) return vaInvoker;
MethodHandle gInvoker = genericInvoker();
MethodType vaType = MethodType.genericMethodType(objectArgCount, true);
vaInvoker = MethodHandles.spreadArguments(gInvoker, invokerType(vaType));
varargsInvokers[objectArgCount] = vaInvoker;
spreadInvokers[objectArgCount] = vaInvoker;
return vaInvoker;
}
......@@ -118,7 +117,7 @@ public class Invokers {
if (invoker != null) return invoker;
if (targetType.parameterCount() > 0) {
MethodType type0 = targetType.dropParameterTypes(0, targetType.parameterCount());
Invokers invokers0 = MethodTypeImpl.invokers(Access.TOKEN, type0);
Invokers invokers0 = MethodTypeImpl.invokers(type0);
invoker = MethodHandles.dropArguments(invokers0.uninitializedCallSite(),
0, targetType.parameterList());
assert(invoker.type().equals(targetType));
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -184,7 +184,10 @@ public abstract class MethodHandleImpl {
if (!mh.isValid())
throw newNoAccessException(method, lookupClass);
assert(mh.type() == mtype);
return mh;
if (!method.isVarargs())
return mh;
else
return mh.asVarargsCollector(mtype.parameterType(mtype.parameterCount()-1));
}
public static
......@@ -1263,8 +1266,8 @@ public abstract class MethodHandleImpl {
return MethodHandleNatives.getBootstrap(callerClass);
}
public static MethodHandle withTypeHandler(Access token, MethodHandle target, MethodHandle typeHandler) {
public static MethodHandle asVarargsCollector(Access token, MethodHandle target, Class<?> arrayType) {
Access.check(token);
return AdapterMethodHandle.makeTypeHandler(token, target, typeHandler);
return AdapterMethodHandle.makeVarargsCollector(token, target, arrayType);
}
}
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, 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
......@@ -498,9 +498,12 @@ public class MethodTypeImpl {
public static Invokers invokers(Access token, MethodType type) {
Access.check(token);
return invokers(type);
}
/*non-public*/ static Invokers invokers(MethodType type) {
Invokers inv = METHOD_TYPE_FRIEND.getInvokers(type);
if (inv != null) return inv;
inv = new Invokers(token, type);
inv = new Invokers(type);
METHOD_TYPE_FRIEND.setInvokers(type, inv);
return inv;
}
......
......@@ -23,15 +23,19 @@
/* @test
* @summary smoke test for invokedynamic instructions
* @library indify
* @build indify.Indify
* @compile InvokeDynamicPrintArgs.java
* @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic
* indify.Indify
* --verify-specifier-count=3 --transitionalJSR292=false
* --expand-properties --classpath ${test.classes}
* --java InvokeDynamicPrintArgs --check-output
* --java test.java.dyn.InvokeDynamicPrintArgs --check-output
*/
package test.java.dyn;
import org.junit.Test;
import java.util.*;
import java.io.*;
......@@ -53,6 +57,20 @@ public class InvokeDynamicPrintArgs {
closeBuf();
}
@Test
public void testInvokeDynamicPrintArgs() throws IOException {
System.err.println(System.getProperties());
String testClassPath = System.getProperty("build.test.classes.dir");
if (testClassPath == null) throw new RuntimeException();
String[] args = new String[]{
"--verify-specifier-count=3", "--transitionalJSR292=false",
"--expand-properties", "--classpath", testClassPath,
"--java", "test.java.dyn.InvokeDynamicPrintArgs", "--check-output"
};
System.err.println("Indify: "+Arrays.toString(args));
indify.Indify.main(args);
}
private static PrintStream oldOut;
private static ByteArrayOutputStream buf;
private static void openBuf() {
......@@ -79,11 +97,11 @@ public class InvokeDynamicPrintArgs {
}
private static final String[] EXPECT_OUTPUT = {
"Printing some argument lists, starting with a empty one:",
"[InvokeDynamicPrintArgs, nothing, ()void][]",
"[InvokeDynamicPrintArgs, bar, (java.lang.String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar arg, 1]",
"[InvokeDynamicPrintArgs, bar2, (java.lang.String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar2 arg, 222]",
"[InvokeDynamicPrintArgs, baz, (java.lang.String,int,double)void, 1234.5][baz arg, 2, 3.14]",
"[InvokeDynamicPrintArgs, foo, (java.lang.String)void][foo arg]",
"[test.java.dyn.InvokeDynamicPrintArgs, nothing, ()void][]",
"[test.java.dyn.InvokeDynamicPrintArgs, bar, (String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar arg, 1]",
"[test.java.dyn.InvokeDynamicPrintArgs, bar2, (String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar2 arg, 222]",
"[test.java.dyn.InvokeDynamicPrintArgs, baz, (String,int,double)void, 1234.5][baz arg, 2, 3.14]",
"[test.java.dyn.InvokeDynamicPrintArgs, foo, (String)void][foo arg]",
"Done printing argument lists."
};
......@@ -110,18 +128,15 @@ public class InvokeDynamicPrintArgs {
return lookup().findStatic(lookup().lookupClass(), "bsm", MT_bsm());
}
private static CallSite bsm2(Lookup caller, String name, MethodType type, Object arg) throws ReflectiveOperationException {
private static CallSite bsm2(Lookup caller, String name, MethodType type, Object... arg) throws ReflectiveOperationException {
// ignore caller and name, but match the type:
List<Object> bsmInfo = new ArrayList<>(Arrays.asList(caller, name, type));
if (arg instanceof Object[])
bsmInfo.addAll(Arrays.asList((Object[])arg));
else
bsmInfo.add(arg);
bsmInfo.addAll(Arrays.asList((Object[])arg));
return new ConstantCallSite(MH_printArgs().bindTo(bsmInfo).asCollector(Object[].class, type.parameterCount()).asType(type));
}
private static MethodType MT_bsm2() {
shouldNotCallThis();
return methodType(CallSite.class, Lookup.class, String.class, MethodType.class, Object.class);
return methodType(CallSite.class, Lookup.class, String.class, MethodType.class, Object[].class);
}
private static MethodHandle MH_bsm2() throws ReflectiveOperationException {
shouldNotCallThis();
......
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2011, 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
......@@ -142,37 +142,80 @@ assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
Assert.assertEquals(exp, act);
}
static MethodHandle asList;
@Test public void testWithTypeHandler() throws Throwable {
@Test public void testMethodHandlesSummary() throws Throwable {
{{
{} /// JAVADOC
MethodHandle makeEmptyList = MethodHandles.constant(List.class, Arrays.asList());
MethodHandle asList = lookup()
.findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
JavaDocExamplesTest.asList = asList;
/*
static MethodHandle collectingTypeHandler(MethodHandle base, MethodType newType) {
return asList.asCollector(Object[].class, newType.parameterCount()).asType(newType);
}
*/
MethodHandle collectingTypeHandler = lookup()
.findStatic(lookup().lookupClass(), "collectingTypeHandler",
methodType(MethodHandle.class, MethodHandle.class, MethodType.class));
MethodHandle makeAnyList = makeEmptyList.withTypeHandler(collectingTypeHandler);
assertEquals("[]", makeAnyList.invokeGeneric().toString());
assertEquals("[1]", makeAnyList.invokeGeneric(1).toString());
assertEquals("[two, too]", makeAnyList.invokeGeneric("two", "too").toString());
Object x, y; String s; int i;
MethodType mt; MethodHandle mh;
MethodHandles.Lookup lookup = MethodHandles.lookup();
// mt is (char,char)String
mt = MethodType.methodType(String.class, char.class, char.class);
mh = lookup.findVirtual(String.class, "replace", mt);
// (Ljava/lang/String;CC)Ljava/lang/String;
s = (String) mh.invokeExact("daddy",'d','n');
assert(s.equals("nanny"));
// weakly typed invocation (using MHs.invoke)
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
assert(s.equals("savvy"));
// mt is (Object[])List
mt = MethodType.methodType(java.util.List.class, Object[].class);
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
assert(mh.isVarargsCollector());
x = mh.invokeGeneric("one", "two");
assert(x.equals(java.util.Arrays.asList("one","two")));
// mt is (Object,Object,Object)Object
mt = MethodType.genericMethodType(3);
mh = MethodHandles.collectArguments(mh, mt);
// mt is (Object,Object,Object)Object
// (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
assert(x.equals(java.util.Arrays.asList(1,2,3)));
// mt is { =&gt; int}
mt = MethodType.methodType(int.class);
mh = lookup.findVirtual(java.util.List.class, "size", mt);
// (Ljava/util/List;)I
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
assert(i == 3);
mt = MethodType.methodType(void.class, String.class);
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
mh.invokeExact(System.out, "Hello, world.");
{}
}}
}
static MethodHandle collectingTypeHandler(MethodHandle base, MethodType newType) {
//System.out.println("Converting "+asList+" to "+newType);
MethodHandle conv = asList.asCollector(Object[].class, newType.parameterCount()).asType(newType);
//System.out.println(" =>"+conv);
return conv;
}
@Test public void testAsVarargsCollector() throws Throwable {
{{
{} /// JAVADOC
MethodHandle asList = publicLookup()
.findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
.asVarargsCollector(Object[].class);
assertEquals("[]", asList.invokeGeneric().toString());
assertEquals("[1]", asList.invokeGeneric(1).toString());
assertEquals("[two, too]", asList.invokeGeneric("two", "too").toString());
Object[] argv = { "three", "thee", "tee" };
assertEquals("[three, thee, tee]", asList.invokeGeneric(argv).toString());
List ls = (List) asList.invokeGeneric((Object)argv);
assertEquals(1, ls.size());
assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
}}
}
@Test public void testVarargsCollectorSuppression() throws Throwable {
{{
{} /// JAVADOC
MethodHandle vamh = publicLookup()
.findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
.asVarargsCollector(Object[].class);
MethodHandle invokeExact = publicLookup()
.findVirtual(MethodHandle.class, "invokeExact", vamh.type());
MethodHandle mh = invokeExact.bindTo(vamh);
assert(vamh.type().equals(mh.type()));
assertEquals("[1, 2, 3]", vamh.invokeGeneric(1,2,3).toString());
boolean failed = false;
try { mh.invokeGeneric(1,2,3); }
catch (WrongMethodTypeException ex) { failed = true; }
assert(failed);
{}
}}
}
}
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2011, 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
......@@ -1108,18 +1108,6 @@ public class MethodHandlesTest {
}
}
static MethodHandle typeHandler2(MethodHandle target, MethodType newType) {
MethodType oldType = target.type();
int oldArity = oldType.parameterCount();
int newArity = newType.parameterCount();
if (newArity < oldArity)
return MethodHandles.insertArguments(target, oldArity, "OPTIONAL");
else if (newArity > oldArity)
return MethodHandles.dropArguments(target, oldArity-1, newType.parameterType(oldArity-1));
else
return target; // attempt no further conversions
}
@Test
public void testConvertArguments() throws Throwable {
if (CAN_SKIP_WORKING) return;
......@@ -1137,23 +1125,6 @@ public class MethodHandlesTest {
testConvert(true, true, id, rtype, name, params);
}
@Test
public void testTypeHandler() throws Throwable {
MethodHandle id = Callee.ofType(1);
MethodHandle th2 = PRIVATE.findStatic(MethodHandlesTest.class, "typeHandler2",
MethodType.methodType(MethodHandle.class, MethodHandle.class, MethodType.class));
MethodHandle id2 = id.withTypeHandler(th2);
testConvert(true, false, id2, null, "id", Object.class);
testConvert(true, true, id2, null, "id", Object.class);
if (true) return; //FIXME
testConvert(true, false, id2, null, "id", String.class); // FIXME: throws WMT
testConvert(false, true, id2, null, "id", String.class); // FIXME: should not succeed
testConvert(false, false, id2, null, "id", Object.class, String.class); //FIXME: array[1] line 1164
testConvert(true, true, id2, null, "id", Object.class, String.class);
testConvert(false, false, id2, null, "id");
testConvert(true, true, id2, null, "id");
}
void testConvert(boolean positive, boolean useAsType,
MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
countTest(positive);
......@@ -1183,9 +1154,9 @@ public class MethodHandlesTest {
RuntimeException error = null;
try {
if (useAsType)
target = MethodHandles.convertArguments(id, newType);
else
target = id.asType(newType);
else
target = MethodHandles.convertArguments(id, newType);
} catch (RuntimeException ex) {
error = ex;
}
......@@ -1204,6 +1175,20 @@ public class MethodHandlesTest {
System.out.print(':');
}
@Test
public void testVarargsCollector() throws Throwable {
MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
MethodType.methodType(Object.class, String.class, Object[].class));
vac0 = vac0.bindTo("vac");
MethodHandle vac = vac0.asVarargsCollector(Object[].class);
testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
for (Class<?> at : new Class[] { Object.class, String.class, Integer.class }) {
testConvert(true, true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
testConvert(true, true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
}
}
@Test
public void testPermuteArguments() throws Throwable {
if (CAN_SKIP_WORKING) return;
......@@ -1644,14 +1629,14 @@ public class MethodHandlesTest {
assertCalled("invokee", args);
// varargs invoker #0
calledLog.clear();
inv = MethodHandles.varargsInvoker(type, 0);
inv = MethodHandles.spreadInvoker(type, 0);
result = inv.invokeExact(target, args);
if (testRetCode) assertEquals(code, result);
assertCalled("invokee", args);
if (nargs >= 1) {
// varargs invoker #1
calledLog.clear();
inv = MethodHandles.varargsInvoker(type, 1);
inv = MethodHandles.spreadInvoker(type, 1);
result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
if (testRetCode) assertEquals(code, result);
assertCalled("invokee", args);
......@@ -1659,7 +1644,7 @@ public class MethodHandlesTest {
if (nargs >= 2) {
// varargs invoker #2
calledLog.clear();
inv = MethodHandles.varargsInvoker(type, 2);
inv = MethodHandles.spreadInvoker(type, 2);
result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
if (testRetCode) assertEquals(code, result);
assertCalled("invokee", args);
......@@ -1667,7 +1652,7 @@ public class MethodHandlesTest {
if (nargs >= 3) {
// varargs invoker #3
calledLog.clear();
inv = MethodHandles.varargsInvoker(type, 3);
inv = MethodHandles.spreadInvoker(type, 3);
result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
if (testRetCode) assertEquals(code, result);
assertCalled("invokee", args);
......@@ -1676,7 +1661,7 @@ public class MethodHandlesTest {
// varargs invoker #0..N
countTest();
calledLog.clear();
inv = MethodHandles.varargsInvoker(type, k);
inv = MethodHandles.spreadInvoker(type, k);
List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
Object[] tail = tailList.toArray();
......@@ -2089,19 +2074,6 @@ public class MethodHandlesTest {
}
}
// Test error checking:
MethodHandle genericMH = ValueConversions.varargsArray(0);
genericMH = MethodHandles.convertArguments(genericMH, genericMH.type().generic());
for (Class<?> sam : new Class[] { Runnable.class,
Fooable.class,
Iterable.class }) {
try {
// Must throw, because none of these guys has generic type.
MethodHandles.asInstance(genericMH, sam);
System.out.println("Failed to throw");
assertTrue(false);
} catch (IllegalArgumentException ex) {
}
}
for (Class<?> nonSAM : new Class[] { Object.class,
String.class,
CharSequence.class,
......
......@@ -98,8 +98,9 @@ $ $JAVA_HOME/bin/java -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic
(same output as above)
* </pre></blockquote>
* <p>
* Until the format of {@code CONSTANT_InvokeDynamic} entries is finalized,
* the {@code --transitionalJSR292} switch is recommended (and turned on by default).
* Before OpenJDK build b123, the format of {@code CONSTANT_InvokeDynamic} is in transition,
* and the switch {@code --transitionalJSR292=yes} is recommended.
* It is turned <em>off</em> by default, but users of earlier builds may need to turn it on.
* <p>
* A version of this transformation built on top of <a href="http://asm.ow2.org/">http://asm.ow2.org/</a> would be welcome.
* @author John Rose
......@@ -116,7 +117,7 @@ public class Indify {
public boolean overwrite = false;
public boolean quiet = false;
public boolean verbose = false;
public boolean transitionalJSR292 = true; // default to false later
public boolean transitionalJSR292 = false; // final version is distributed
public boolean all = false;
public int verifySpecifierCount = -1;
......@@ -158,6 +159,7 @@ public class Indify {
av = avl.toArray(new String[0]);
Class<?> mainClass = Class.forName(mainClassName, true, makeClassLoader());
java.lang.reflect.Method main = mainClass.getMethod("main", String[].class);
try { main.setAccessible(true); } catch (SecurityException ex) { }
main.invoke(null, (Object) av);
}
......@@ -223,8 +225,8 @@ public class Indify {
private boolean booleanOption(String s) {
if (s == null) return true;
switch (s) {
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": return false;
case "true": case "yes": case "on": case "1": return true;
case "false": case "no": case "off": case "0": return false;
}
throw new IllegalArgumentException("unrecognized boolean flag="+s);
}
......@@ -284,7 +286,7 @@ public class Indify {
}
File classPathFile(File pathDir, String className) {
String qualname = className+".class";
String qualname = className.replace('.','/')+".class";
qualname = qualname.replace('/', File.separatorChar);
return new File(pathDir, qualname);
}
......@@ -339,6 +341,7 @@ public class Indify {
private File findClassInPath(String name) {
for (String s : classpath) {
File f = classPathFile(new File(s), name);
//System.out.println("Checking for "+f);
if (f.exists() && f.canRead()) {
return f;
}
......@@ -353,11 +356,11 @@ public class Indify {
}
}
private Class<?> transformAndLoadClass(File f) throws ClassNotFoundException, IOException {
if (verbose) System.out.println("Loading class from "+f);
if (verbose) System.err.println("Loading class from "+f);
ClassFile cf = new ClassFile(f);
Logic logic = new Logic(cf);
boolean changed = logic.transform();
if (verbose && !changed) System.out.println("(no change)");
if (verbose && !changed) System.err.println("(no change)");
logic.reportPatternMethods(!verbose, keepgoing);
byte[] bytes = cf.toByteArray();
return defineClass(null, bytes, 0, bytes.length);
......@@ -525,6 +528,7 @@ public class Indify {
throw new IllegalArgumentException("BootstrapMethods length is "+specsLen+" but should be "+verifySpecifierCount);
}
}
if (!quiet) System.err.flush();
}
// mark constant pool entries according to participation in patterns
......@@ -696,6 +700,18 @@ public class Indify {
args.clear();
break;
case opc_new:
{
String type = pool.getString(CONSTANT_Class, (short)i.u2At(1));
//System.out.println("new "+type);
switch (type) {
case "java/lang/StringBuilder":
jvm.push("StringBuilder");
continue decode; // go to next instruction
}
break decode; // bail out
}
case opc_getstatic:
{
// int.class compiles to getstatic Integer.TYPE
......@@ -732,8 +748,9 @@ public class Indify {
case opc_invokestatic:
case opc_invokevirtual:
case opc_invokespecial:
{
boolean hasRecv = (bc == opc_invokevirtual);
boolean hasRecv = (bc != opc_invokestatic);
int methi = i.u2At(1);
char mark = poolMarks[methi];
Short[] ref = pool.getMemberRef((short)methi);
......@@ -770,6 +787,7 @@ public class Indify {
if (mark == 'T' || mark == 'H' || mark == 'I') {
ownMethod = findMember(cf.methods, ref[1], ref[2]);
}
//if (intrinsic != null) System.out.println("intrinsic = "+intrinsic);
switch (intrinsic == null ? "" : intrinsic) {
case "fromMethodDescriptorString":
con = makeMethodTypeCon(args.get(0));
......@@ -860,6 +878,15 @@ public class Indify {
}
}
break decode;
case "StringBuilder.append":
// allow calls like ("value = "+x)
removeEmptyJVMSlots(args);
args.subList(1, args.size()).clear();
continue;
case "StringBuilder.toString":
args.clear();
args.add(intrinsic);
continue;
}
if (!hasRecv && ownMethod != null && patternMark != 0) {
con = constants.get(ownMethod);
......@@ -1506,6 +1533,7 @@ public class Indify {
out.write(bytes);
} else {
trueSize = flatten(out);
//if (!(item instanceof Code)) System.err.println("wrote complex attr name="+(int)(char)name+" size="+trueSize+" data="+Arrays.toString(flatten()));
}
if (trueSize != size && size >= 0)
System.err.println("warning: attribute size changed "+size+" to "+trueSize);
......@@ -1525,7 +1553,7 @@ public class Indify {
}
public List<Attr> attrs() { return null; } // Code overrides this
public byte[] flatten() {
ByteArrayOutputStream buf = new ByteArrayOutputStream(size);
ByteArrayOutputStream buf = new ByteArrayOutputStream(Math.max(20, size));
flatten(buf);
return buf.toByteArray();
}
......@@ -1642,6 +1670,7 @@ public class Indify {
opc_invokestatic = 184,
opc_invokeinterface = 185,
opc_invokedynamic = 186,
opc_new = 187,
opc_anewarray = 189,
opc_checkcast = 192,
opc_ifnull = 198,
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册