ScriptFunctionData.java revision 1583:1b47169055e2
1/* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.runtime; 27 28import static jdk.nashorn.internal.lookup.Lookup.MH; 29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 31 32import java.io.IOException; 33import java.io.ObjectInputStream; 34import java.io.Serializable; 35import java.lang.invoke.MethodHandle; 36import java.lang.invoke.MethodHandles; 37import java.lang.invoke.MethodType; 38import java.util.Collection; 39import java.util.LinkedList; 40import java.util.List; 41import jdk.nashorn.internal.runtime.linker.LinkerCallSite; 42 43 44/** 45 * A container for data needed to instantiate a specific {@link ScriptFunction} at runtime. 46 * Instances of this class are created during codegen and stored in script classes' 47 * constants array to reduce function instantiation overhead during runtime. 48 */ 49public abstract class ScriptFunctionData implements Serializable { 50 static final int MAX_ARITY = LinkerCallSite.ARGLIMIT; 51 static { 52 // Assert it fits in a byte, as that's what we store it in. It's just a size optimization though, so if needed 53 // "byte arity" field can be widened. 54 assert MAX_ARITY < 256; 55 } 56 57 /** Name of the function or "" for anonymous functions */ 58 protected final String name; 59 60 /** 61 * A list of code versions of a function sorted in ascending order of generic descriptors. 62 */ 63 protected transient LinkedList<CompiledFunction> code = new LinkedList<>(); 64 65 /** Function flags */ 66 protected int flags; 67 68 // Parameter arity of the function, corresponding to "f.length". E.g. "function f(a, b, c) { ... }" arity is 3, and 69 // some built-in ECMAScript functions have their arity declared by the specification. Note that regardless of this 70 // value, the function might still be capable of receiving variable number of arguments, see isVariableArity. 71 private int arity; 72 73 /** 74 * A pair of method handles used for generic invoker and constructor. Field is volatile as it can be initialized by 75 * multiple threads concurrently, but we still tolerate a race condition in it as all values stored into it are 76 * idempotent. 77 */ 78 private volatile transient GenericInvokers genericInvokers; 79 80 private static final MethodHandle BIND_VAR_ARGS = findOwnMH("bindVarArgs", Object[].class, Object[].class, Object[].class); 81 82 /** Is this a strict mode function? */ 83 public static final int IS_STRICT = 1 << 0; 84 /** Is this a built-in function? */ 85 public static final int IS_BUILTIN = 1 << 1; 86 /** Is this a constructor function? */ 87 public static final int IS_CONSTRUCTOR = 1 << 2; 88 /** Does this function expect a callee argument? */ 89 public static final int NEEDS_CALLEE = 1 << 3; 90 /** Does this function make use of the this-object argument? */ 91 public static final int USES_THIS = 1 << 4; 92 /** Is this a variable arity function? */ 93 public static final int IS_VARIABLE_ARITY = 1 << 5; 94 /** Is this a object literal property getter or setter? */ 95 public static final int IS_PROPERTY_ACCESSOR = 1 << 6; 96 97 /** Flag for strict or built-in functions */ 98 public static final int IS_STRICT_OR_BUILTIN = IS_STRICT | IS_BUILTIN; 99 /** Flag for built-in constructors */ 100 public static final int IS_BUILTIN_CONSTRUCTOR = IS_BUILTIN | IS_CONSTRUCTOR; 101 102 private static final long serialVersionUID = 4252901245508769114L; 103 104 /** 105 * Constructor 106 * 107 * @param name script function name 108 * @param arity arity 109 * @param flags the function flags 110 */ 111 ScriptFunctionData(final String name, final int arity, final int flags) { 112 this.name = name; 113 this.flags = flags; 114 setArity(arity); 115 } 116 117 final int getArity() { 118 return arity; 119 } 120 121 String getDocumentation() { 122 return toSource(); 123 } 124 125 String getDocumentationKey() { 126 return null; 127 } 128 129 final boolean isVariableArity() { 130 return (flags & IS_VARIABLE_ARITY) != 0; 131 } 132 133 final boolean isPropertyAccessor() { 134 return (flags & IS_PROPERTY_ACCESSOR) != 0; 135 } 136 137 /** 138 * Used from e.g. Native*$Constructors as an explicit call. TODO - make arity immutable and final 139 * @param arity new arity 140 */ 141 void setArity(final int arity) { 142 if(arity < 0 || arity > MAX_ARITY) { 143 throw new IllegalArgumentException(String.valueOf(arity)); 144 } 145 this.arity = arity; 146 } 147 148 /** 149 * Used from nasgen generated code. 150 * 151 * @param doc documentation for this function 152 */ 153 void setDocumentationKey(final String docKey) { 154 } 155 156 157 CompiledFunction bind(final CompiledFunction originalInv, final ScriptFunction fn, final Object self, final Object[] args) { 158 final MethodHandle boundInvoker = bindInvokeHandle(originalInv.createComposableInvoker(), fn, self, args); 159 160 if (isConstructor()) { 161 return new CompiledFunction(boundInvoker, bindConstructHandle(originalInv.createComposableConstructor(), fn, args), null); 162 } 163 164 return new CompiledFunction(boundInvoker); 165 } 166 167 /** 168 * Is this a ScriptFunction generated with strict semantics? 169 * @return true if strict, false otherwise 170 */ 171 public final boolean isStrict() { 172 return (flags & IS_STRICT) != 0; 173 } 174 175 /** 176 * Return the complete internal function name for this 177 * data, not anonymous or similar. May be identical 178 * @return internal function name 179 */ 180 protected String getFunctionName() { 181 return getName(); 182 } 183 184 final boolean isBuiltin() { 185 return (flags & IS_BUILTIN) != 0; 186 } 187 188 final boolean isConstructor() { 189 return (flags & IS_CONSTRUCTOR) != 0; 190 } 191 192 abstract boolean needsCallee(); 193 194 /** 195 * Returns true if this is a non-strict, non-built-in function that requires non-primitive this argument 196 * according to ECMA 10.4.3. 197 * @return true if this argument must be an object 198 */ 199 final boolean needsWrappedThis() { 200 return (flags & USES_THIS) != 0 && (flags & IS_STRICT_OR_BUILTIN) == 0; 201 } 202 203 String toSource() { 204 return "function " + (name == null ? "" : name) + "() { [native code] }"; 205 } 206 207 String getName() { 208 return name; 209 } 210 211 /** 212 * Get this function as a String containing its source code. If no source code 213 * exists in this ScriptFunction, its contents will be displayed as {@code [native code]} 214 * 215 * @return string representation of this function 216 */ 217 @Override 218 public String toString() { 219 return name.isEmpty() ? "<anonymous>" : name; 220 } 221 222 /** 223 * Verbose description of data 224 * @return verbose description 225 */ 226 public String toStringVerbose() { 227 final StringBuilder sb = new StringBuilder(); 228 229 sb.append("name='"). 230 append(name.isEmpty() ? "<anonymous>" : name). 231 append("' "). 232 append(code.size()). 233 append(" invokers="). 234 append(code); 235 236 return sb.toString(); 237 } 238 239 /** 240 * Pick the best invoker, i.e. the one version of this method with as narrow and specific 241 * types as possible. If the call site arguments are objects, but boxed primitives we can 242 * also try to get a primitive version of the method and do an unboxing filter, but then 243 * we need to insert a guard that checks the argument is really always a boxed primitive 244 * and not suddenly a "real" object 245 * 246 * @param callSiteType callsite type 247 * @return compiled function object representing the best invoker. 248 */ 249 final CompiledFunction getBestInvoker(final MethodType callSiteType, final ScriptObject runtimeScope) { 250 return getBestInvoker(callSiteType, runtimeScope, CompiledFunction.NO_FUNCTIONS); 251 } 252 253 final CompiledFunction getBestInvoker(final MethodType callSiteType, final ScriptObject runtimeScope, final Collection<CompiledFunction> forbidden) { 254 final CompiledFunction cf = getBest(callSiteType, runtimeScope, forbidden); 255 assert cf != null; 256 return cf; 257 } 258 259 final CompiledFunction getBestConstructor(final MethodType callSiteType, final ScriptObject runtimeScope, final Collection<CompiledFunction> forbidden) { 260 if (!isConstructor()) { 261 throw typeError("not.a.constructor", toSource()); 262 } 263 // Constructor call sites don't have a "this", but getBest is meant to operate on "callee, this, ..." style 264 final CompiledFunction cf = getBest(callSiteType.insertParameterTypes(1, Object.class), runtimeScope, forbidden); 265 return cf; 266 } 267 268 /** 269 * If we can have lazy code generation, this is a hook to ensure that the code has been compiled. 270 * This does not guarantee the code been installed in this {@code ScriptFunctionData} instance 271 */ 272 protected void ensureCompiled() { 273 //empty 274 } 275 276 /** 277 * Return a generic Object/Object invoker for this method. It will ensure code 278 * is generated, get the most generic of all versions of this function and adapt it 279 * to Objects. 280 * 281 * @param runtimeScope the runtime scope. It can be used to evaluate types of scoped variables to guide the 282 * optimistic compilation, should the call to this method trigger code compilation. Can be null if current runtime 283 * scope is not known, but that might cause compilation of code that will need more deoptimization passes. 284 * @return generic invoker of this script function 285 */ 286 final MethodHandle getGenericInvoker(final ScriptObject runtimeScope) { 287 // This method has race conditions both on genericsInvoker and genericsInvoker.invoker, but even if invoked 288 // concurrently, they'll create idempotent results, so it doesn't matter. We could alternatively implement this 289 // using java.util.concurrent.AtomicReferenceFieldUpdater, but it's hardly worth it. 290 final GenericInvokers lgenericInvokers = ensureGenericInvokers(); 291 MethodHandle invoker = lgenericInvokers.invoker; 292 if(invoker == null) { 293 lgenericInvokers.invoker = invoker = createGenericInvoker(runtimeScope); 294 } 295 return invoker; 296 } 297 298 private MethodHandle createGenericInvoker(final ScriptObject runtimeScope) { 299 return makeGenericMethod(getGeneric(runtimeScope).createComposableInvoker()); 300 } 301 302 final MethodHandle getGenericConstructor(final ScriptObject runtimeScope) { 303 // This method has race conditions both on genericsInvoker and genericsInvoker.constructor, but even if invoked 304 // concurrently, they'll create idempotent results, so it doesn't matter. We could alternatively implement this 305 // using java.util.concurrent.AtomicReferenceFieldUpdater, but it's hardly worth it. 306 final GenericInvokers lgenericInvokers = ensureGenericInvokers(); 307 MethodHandle constructor = lgenericInvokers.constructor; 308 if(constructor == null) { 309 lgenericInvokers.constructor = constructor = createGenericConstructor(runtimeScope); 310 } 311 return constructor; 312 } 313 314 private MethodHandle createGenericConstructor(final ScriptObject runtimeScope) { 315 return makeGenericMethod(getGeneric(runtimeScope).createComposableConstructor()); 316 } 317 318 private GenericInvokers ensureGenericInvokers() { 319 GenericInvokers lgenericInvokers = genericInvokers; 320 if(lgenericInvokers == null) { 321 genericInvokers = lgenericInvokers = new GenericInvokers(); 322 } 323 return lgenericInvokers; 324 } 325 326 private static MethodType widen(final MethodType cftype) { 327 final Class<?>[] paramTypes = new Class<?>[cftype.parameterCount()]; 328 for (int i = 0; i < cftype.parameterCount(); i++) { 329 paramTypes[i] = cftype.parameterType(i).isPrimitive() ? cftype.parameterType(i) : Object.class; 330 } 331 return MH.type(cftype.returnType(), paramTypes); 332 } 333 334 /** 335 * Used to find an apply to call version that fits this callsite. 336 * We cannot just, as in the normal matcher case, return e.g. (Object, Object, int) 337 * for (Object, Object, int, int, int) or we will destroy the semantics and get 338 * a function that, when padded with undefined values, behaves differently 339 * @param type actual call site type 340 * @return apply to call that perfectly fits this callsite or null if none found 341 */ 342 CompiledFunction lookupExactApplyToCall(final MethodType type) { 343 for (final CompiledFunction cf : code) { 344 if (!cf.isApplyToCall()) { 345 continue; 346 } 347 348 final MethodType cftype = cf.type(); 349 if (cftype.parameterCount() != type.parameterCount()) { 350 continue; 351 } 352 353 if (widen(cftype).equals(widen(type))) { 354 return cf; 355 } 356 } 357 358 return null; 359 } 360 361 CompiledFunction pickFunction(final MethodType callSiteType, final boolean canPickVarArg) { 362 for (final CompiledFunction candidate : code) { 363 if (candidate.matchesCallSite(callSiteType, canPickVarArg)) { 364 return candidate; 365 } 366 } 367 return null; 368 } 369 370 /** 371 * Returns the best function for the specified call site type. 372 * @param callSiteType The call site type. Call site types are expected to have the form 373 * {@code (callee, this[, args...])}. 374 * @param runtimeScope the runtime scope. It can be used to evaluate types of scoped variables to guide the 375 * optimistic compilation, should the call to this method trigger code compilation. Can be null if current runtime 376 * scope is not known, but that might cause compilation of code that will need more deoptimization passes. 377 * @param linkLogicOkay is a CompiledFunction with a LinkLogic acceptable? 378 * @return the best function for the specified call site type. 379 */ 380 abstract CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope, final Collection<CompiledFunction> forbidden, final boolean linkLogicOkay); 381 382 /** 383 * Returns the best function for the specified call site type. 384 * @param callSiteType The call site type. Call site types are expected to have the form 385 * {@code (callee, this[, args...])}. 386 * @param runtimeScope the runtime scope. It can be used to evaluate types of scoped variables to guide the 387 * optimistic compilation, should the call to this method trigger code compilation. Can be null if current runtime 388 * scope is not known, but that might cause compilation of code that will need more deoptimization passes. 389 * @return the best function for the specified call site type. 390 */ 391 final CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope, final Collection<CompiledFunction> forbidden) { 392 return getBest(callSiteType, runtimeScope, forbidden, true); 393 } 394 395 boolean isValidCallSite(final MethodType callSiteType) { 396 return callSiteType.parameterCount() >= 2 && // Must have at least (callee, this) 397 callSiteType.parameterType(0).isAssignableFrom(ScriptFunction.class); // Callee must be assignable from script function 398 } 399 400 CompiledFunction getGeneric(final ScriptObject runtimeScope) { 401 return getBest(getGenericType(), runtimeScope, CompiledFunction.NO_FUNCTIONS, false); 402 } 403 404 /** 405 * Get a method type for a generic invoker. 406 * @return the method type for the generic invoker 407 */ 408 abstract MethodType getGenericType(); 409 410 /** 411 * Allocates an object using this function's allocator. 412 * 413 * @param map the property map for the allocated object. 414 * @return the object allocated using this function's allocator, or null if the function doesn't have an allocator. 415 */ 416 ScriptObject allocate(final PropertyMap map) { 417 return null; 418 } 419 420 /** 421 * Get the property map to use for objects allocated by this function. 422 * 423 * @param prototype the prototype of the allocated object 424 * @return the property map for allocated objects. 425 */ 426 PropertyMap getAllocatorMap(final ScriptObject prototype) { 427 return null; 428 } 429 430 /** 431 * This method is used to create the immutable portion of a bound function. 432 * See {@link ScriptFunction#createBound(Object, Object[])} 433 * 434 * @param fn the original function being bound 435 * @param self this reference to bind. Can be null. 436 * @param args additional arguments to bind. Can be null. 437 */ 438 ScriptFunctionData makeBoundFunctionData(final ScriptFunction fn, final Object self, final Object[] args) { 439 final Object[] allArgs = args == null ? ScriptRuntime.EMPTY_ARRAY : args; 440 final int length = args == null ? 0 : args.length; 441 // Clear the callee and this flags 442 final int boundFlags = flags & ~NEEDS_CALLEE & ~USES_THIS; 443 444 final List<CompiledFunction> boundList = new LinkedList<>(); 445 final ScriptObject runtimeScope = fn.getScope(); 446 final CompiledFunction bindTarget = new CompiledFunction(getGenericInvoker(runtimeScope), getGenericConstructor(runtimeScope), null); 447 boundList.add(bind(bindTarget, fn, self, allArgs)); 448 449 return new FinalScriptFunctionData(name, Math.max(0, getArity() - length), boundList, boundFlags); 450 } 451 452 /** 453 * Convert this argument for non-strict functions according to ES 10.4.3 454 * 455 * @param thiz the this argument 456 * 457 * @return the converted this object 458 */ 459 private Object convertThisObject(final Object thiz) { 460 return needsWrappedThis() ? wrapThis(thiz) : thiz; 461 } 462 463 static Object wrapThis(final Object thiz) { 464 if (!(thiz instanceof ScriptObject)) { 465 if (JSType.nullOrUndefined(thiz)) { 466 return Context.getGlobal(); 467 } 468 469 if (isPrimitiveThis(thiz)) { 470 return Context.getGlobal().wrapAsObject(thiz); 471 } 472 } 473 474 return thiz; 475 } 476 477 static boolean isPrimitiveThis(final Object obj) { 478 return JSType.isString(obj) || obj instanceof Number || obj instanceof Boolean; 479 } 480 481 /** 482 * Creates an invoker method handle for a bound function. 483 * 484 * @param targetFn the function being bound 485 * @param originalInvoker an original invoker method handle for the function. This can be its generic invoker or 486 * any of its specializations. 487 * @param self the "this" value being bound 488 * @param args additional arguments being bound 489 * 490 * @return a bound invoker method handle that will bind the self value and the specified arguments. The resulting 491 * invoker never needs a callee; if the original invoker needed it, it will be bound to {@code fn}. The resulting 492 * invoker still takes an initial {@code this} parameter, but it is always dropped and the bound {@code self} passed 493 * to the original invoker on invocation. 494 */ 495 private MethodHandle bindInvokeHandle(final MethodHandle originalInvoker, final ScriptFunction targetFn, final Object self, final Object[] args) { 496 // Is the target already bound? If it is, we won't bother binding either callee or self as they're already bound 497 // in the target and will be ignored anyway. 498 final boolean isTargetBound = targetFn.isBoundFunction(); 499 500 final boolean needsCallee = needsCallee(originalInvoker); 501 assert needsCallee == needsCallee() : "callee contract violation 2"; 502 assert !(isTargetBound && needsCallee); // already bound functions don't need a callee 503 504 final Object boundSelf = isTargetBound ? null : convertThisObject(self); 505 final MethodHandle boundInvoker; 506 507 if (isVarArg(originalInvoker)) { 508 // First, bind callee and this without arguments 509 final MethodHandle noArgBoundInvoker; 510 511 if (isTargetBound) { 512 // Don't bind either callee or this 513 noArgBoundInvoker = originalInvoker; 514 } else if (needsCallee) { 515 // Bind callee and this 516 noArgBoundInvoker = MH.insertArguments(originalInvoker, 0, targetFn, boundSelf); 517 } else { 518 // Only bind this 519 noArgBoundInvoker = MH.bindTo(originalInvoker, boundSelf); 520 } 521 // Now bind arguments 522 if (args.length > 0) { 523 boundInvoker = varArgBinder(noArgBoundInvoker, args); 524 } else { 525 boundInvoker = noArgBoundInvoker; 526 } 527 } else { 528 // If target is already bound, insert additional bound arguments after "this" argument, at position 1. 529 final int argInsertPos = isTargetBound ? 1 : 0; 530 final Object[] boundArgs = new Object[Math.min(originalInvoker.type().parameterCount() - argInsertPos, args.length + (isTargetBound ? 0 : needsCallee ? 2 : 1))]; 531 int next = 0; 532 if (!isTargetBound) { 533 if (needsCallee) { 534 boundArgs[next++] = targetFn; 535 } 536 boundArgs[next++] = boundSelf; 537 } 538 // If more bound args were specified than the function can take, we'll just drop those. 539 System.arraycopy(args, 0, boundArgs, next, boundArgs.length - next); 540 // If target is already bound, insert additional bound arguments after "this" argument, at position 1; 541 // "this" will get dropped anyway by the target invoker. We previously asserted that already bound functions 542 // don't take a callee parameter, so we can know that the signature is (this[, args...]) therefore args 543 // start at position 1. If the function is not bound, we start inserting arguments at position 0. 544 boundInvoker = MH.insertArguments(originalInvoker, argInsertPos, boundArgs); 545 } 546 547 if (isTargetBound) { 548 return boundInvoker; 549 } 550 551 // If the target is not already bound, add a dropArguments that'll throw away the passed this 552 return MH.dropArguments(boundInvoker, 0, Object.class); 553 } 554 555 /** 556 * Creates a constructor method handle for a bound function using the passed constructor handle. 557 * 558 * @param originalConstructor the constructor handle to bind. It must be a composed constructor. 559 * @param fn the function being bound 560 * @param args arguments being bound 561 * 562 * @return a bound constructor method handle that will bind the specified arguments. The resulting constructor never 563 * needs a callee; if the original constructor needed it, it will be bound to {@code fn}. The resulting constructor 564 * still takes an initial {@code this} parameter and passes it to the underlying original constructor. Finally, if 565 * this script function data object has no constructor handle, null is returned. 566 */ 567 private static MethodHandle bindConstructHandle(final MethodHandle originalConstructor, final ScriptFunction fn, final Object[] args) { 568 assert originalConstructor != null; 569 570 // If target function is already bound, don't bother binding the callee. 571 final MethodHandle calleeBoundConstructor = fn.isBoundFunction() ? originalConstructor : 572 MH.dropArguments(MH.bindTo(originalConstructor, fn), 0, ScriptFunction.class); 573 574 if (args.length == 0) { 575 return calleeBoundConstructor; 576 } 577 578 if (isVarArg(calleeBoundConstructor)) { 579 return varArgBinder(calleeBoundConstructor, args); 580 } 581 582 final Object[] boundArgs; 583 584 final int maxArgCount = calleeBoundConstructor.type().parameterCount() - 1; 585 if (args.length <= maxArgCount) { 586 boundArgs = args; 587 } else { 588 boundArgs = new Object[maxArgCount]; 589 System.arraycopy(args, 0, boundArgs, 0, maxArgCount); 590 } 591 592 return MH.insertArguments(calleeBoundConstructor, 1, boundArgs); 593 } 594 595 /** 596 * Takes a method handle, and returns a potentially different method handle that can be used in 597 * {@code ScriptFunction#invoke(Object, Object...)} or {code ScriptFunction#construct(Object, Object...)}. 598 * The returned method handle will be sure to return {@code Object}, and will have all its parameters turned into 599 * {@code Object} as well, except for the following ones: 600 * <ul> 601 * <li>a last parameter of type {@code Object[]} which is used for vararg functions,</li> 602 * <li>the first argument, which is forced to be {@link ScriptFunction}, in case the function receives itself 603 * (callee) as an argument.</li> 604 * </ul> 605 * 606 * @param mh the original method handle 607 * 608 * @return the new handle, conforming to the rules above. 609 */ 610 private static MethodHandle makeGenericMethod(final MethodHandle mh) { 611 final MethodType type = mh.type(); 612 final MethodType newType = makeGenericType(type); 613 return type.equals(newType) ? mh : mh.asType(newType); 614 } 615 616 private static MethodType makeGenericType(final MethodType type) { 617 MethodType newType = type.generic(); 618 if (isVarArg(type)) { 619 newType = newType.changeParameterType(type.parameterCount() - 1, Object[].class); 620 } 621 if (needsCallee(type)) { 622 newType = newType.changeParameterType(0, ScriptFunction.class); 623 } 624 return newType; 625 } 626 627 /** 628 * Execute this script function. 629 * 630 * @param self Target object. 631 * @param arguments Call arguments. 632 * @return ScriptFunction result. 633 * 634 * @throws Throwable if there is an exception/error with the invocation or thrown from it 635 */ 636 Object invoke(final ScriptFunction fn, final Object self, final Object... arguments) throws Throwable { 637 final MethodHandle mh = getGenericInvoker(fn.getScope()); 638 final Object selfObj = convertThisObject(self); 639 final Object[] args = arguments == null ? ScriptRuntime.EMPTY_ARRAY : arguments; 640 641 DebuggerSupport.notifyInvoke(mh); 642 643 if (isVarArg(mh)) { 644 if (needsCallee(mh)) { 645 return mh.invokeExact(fn, selfObj, args); 646 } 647 return mh.invokeExact(selfObj, args); 648 } 649 650 final int paramCount = mh.type().parameterCount(); 651 if (needsCallee(mh)) { 652 switch (paramCount) { 653 case 2: 654 return mh.invokeExact(fn, selfObj); 655 case 3: 656 return mh.invokeExact(fn, selfObj, getArg(args, 0)); 657 case 4: 658 return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1)); 659 case 5: 660 return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2)); 661 case 6: 662 return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3)); 663 case 7: 664 return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4)); 665 case 8: 666 return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5)); 667 default: 668 return mh.invokeWithArguments(withArguments(fn, selfObj, paramCount, args)); 669 } 670 } 671 672 switch (paramCount) { 673 case 1: 674 return mh.invokeExact(selfObj); 675 case 2: 676 return mh.invokeExact(selfObj, getArg(args, 0)); 677 case 3: 678 return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1)); 679 case 4: 680 return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2)); 681 case 5: 682 return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3)); 683 case 6: 684 return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4)); 685 case 7: 686 return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5)); 687 default: 688 return mh.invokeWithArguments(withArguments(null, selfObj, paramCount, args)); 689 } 690 } 691 692 Object construct(final ScriptFunction fn, final Object... arguments) throws Throwable { 693 final MethodHandle mh = getGenericConstructor(fn.getScope()); 694 final Object[] args = arguments == null ? ScriptRuntime.EMPTY_ARRAY : arguments; 695 696 DebuggerSupport.notifyInvoke(mh); 697 698 if (isVarArg(mh)) { 699 if (needsCallee(mh)) { 700 return mh.invokeExact(fn, args); 701 } 702 return mh.invokeExact(args); 703 } 704 705 final int paramCount = mh.type().parameterCount(); 706 if (needsCallee(mh)) { 707 switch (paramCount) { 708 case 1: 709 return mh.invokeExact(fn); 710 case 2: 711 return mh.invokeExact(fn, getArg(args, 0)); 712 case 3: 713 return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1)); 714 case 4: 715 return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2)); 716 case 5: 717 return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3)); 718 case 6: 719 return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4)); 720 case 7: 721 return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5)); 722 default: 723 return mh.invokeWithArguments(withArguments(fn, paramCount, args)); 724 } 725 } 726 727 switch (paramCount) { 728 case 0: 729 return mh.invokeExact(); 730 case 1: 731 return mh.invokeExact(getArg(args, 0)); 732 case 2: 733 return mh.invokeExact(getArg(args, 0), getArg(args, 1)); 734 case 3: 735 return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2)); 736 case 4: 737 return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3)); 738 case 5: 739 return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4)); 740 case 6: 741 return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5)); 742 default: 743 return mh.invokeWithArguments(withArguments(null, paramCount, args)); 744 } 745 } 746 747 private static Object getArg(final Object[] args, final int i) { 748 return i < args.length ? args[i] : UNDEFINED; 749 } 750 751 private static Object[] withArguments(final ScriptFunction fn, final int argCount, final Object[] args) { 752 final Object[] finalArgs = new Object[argCount]; 753 754 int nextArg = 0; 755 if (fn != null) { 756 //needs callee 757 finalArgs[nextArg++] = fn; 758 } 759 760 // Don't add more args that there is argCount in the handle (including self and callee). 761 for (int i = 0; i < args.length && nextArg < argCount;) { 762 finalArgs[nextArg++] = args[i++]; 763 } 764 765 // If we have fewer args than argCount, pad with undefined. 766 while (nextArg < argCount) { 767 finalArgs[nextArg++] = UNDEFINED; 768 } 769 770 return finalArgs; 771 } 772 773 private static Object[] withArguments(final ScriptFunction fn, final Object self, final int argCount, final Object[] args) { 774 final Object[] finalArgs = new Object[argCount]; 775 776 int nextArg = 0; 777 if (fn != null) { 778 //needs callee 779 finalArgs[nextArg++] = fn; 780 } 781 finalArgs[nextArg++] = self; 782 783 // Don't add more args that there is argCount in the handle (including self and callee). 784 for (int i = 0; i < args.length && nextArg < argCount;) { 785 finalArgs[nextArg++] = args[i++]; 786 } 787 788 // If we have fewer args than argCount, pad with undefined. 789 while (nextArg < argCount) { 790 finalArgs[nextArg++] = UNDEFINED; 791 } 792 793 return finalArgs; 794 } 795 /** 796 * Takes a variable-arity method and binds a variable number of arguments in it. The returned method will filter the 797 * vararg array and pass a different array that prepends the bound arguments in front of the arguments passed on 798 * invocation 799 * 800 * @param mh the handle 801 * @param args the bound arguments 802 * 803 * @return the bound method handle 804 */ 805 private static MethodHandle varArgBinder(final MethodHandle mh, final Object[] args) { 806 assert args != null; 807 assert args.length > 0; 808 return MH.filterArguments(mh, mh.type().parameterCount() - 1, MH.bindTo(BIND_VAR_ARGS, args)); 809 } 810 811 /** 812 * Heuristic to figure out if the method handle has a callee argument. If it's type is 813 * {@code (ScriptFunction, ...)}, then we'll assume it has a callee argument. We need this as 814 * the constructor above is not passed this information, and can't just blindly assume it's false 815 * (notably, it's being invoked for creation of new scripts, and scripts have scopes, therefore 816 * they also always receive a callee). 817 * 818 * @param mh the examined method handle 819 * 820 * @return true if the method handle expects a callee, false otherwise 821 */ 822 protected static boolean needsCallee(final MethodHandle mh) { 823 return needsCallee(mh.type()); 824 } 825 826 static boolean needsCallee(final MethodType type) { 827 final int length = type.parameterCount(); 828 829 if (length == 0) { 830 return false; 831 } 832 833 final Class<?> param0 = type.parameterType(0); 834 return param0 == ScriptFunction.class || param0 == boolean.class && length > 1 && type.parameterType(1) == ScriptFunction.class; 835 } 836 837 /** 838 * Check if a javascript function methodhandle is a vararg handle 839 * 840 * @param mh method handle to check 841 * 842 * @return true if vararg 843 */ 844 protected static boolean isVarArg(final MethodHandle mh) { 845 return isVarArg(mh.type()); 846 } 847 848 static boolean isVarArg(final MethodType type) { 849 return type.parameterType(type.parameterCount() - 1).isArray(); 850 } 851 852 /** 853 * Is this ScriptFunction declared in a dynamic context 854 * @return true if in dynamic context, false if not or irrelevant 855 */ 856 public boolean inDynamicContext() { 857 return false; 858 } 859 860 @SuppressWarnings("unused") 861 private static Object[] bindVarArgs(final Object[] array1, final Object[] array2) { 862 if (array2 == null) { 863 // Must clone it, as we can't allow the receiving method to alter the array 864 return array1.clone(); 865 } 866 867 final int l2 = array2.length; 868 if (l2 == 0) { 869 return array1.clone(); 870 } 871 872 final int l1 = array1.length; 873 final Object[] concat = new Object[l1 + l2]; 874 System.arraycopy(array1, 0, concat, 0, l1); 875 System.arraycopy(array2, 0, concat, l1, l2); 876 877 return concat; 878 } 879 880 private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) { 881 return MH.findStatic(MethodHandles.lookup(), ScriptFunctionData.class, name, MH.type(rtype, types)); 882 } 883 884 /** 885 * This class is used to hold the generic invoker and generic constructor pair. It is structured in this way since 886 * most functions will never use them, so this way ScriptFunctionData only pays storage cost for one null reference 887 * to the GenericInvokers object, instead of two null references for the two method handles. 888 */ 889 private static final class GenericInvokers { 890 volatile MethodHandle invoker; 891 volatile MethodHandle constructor; 892 } 893 894 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { 895 in.defaultReadObject(); 896 code = new LinkedList<>(); 897 } 898} 899