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