ScriptFunction.java revision 953:221a84ef44c0
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.codegen.CompilerConstants.virtualCallNoLookup;
29import static jdk.nashorn.internal.lookup.Lookup.MH;
30import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
31import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
32import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
33
34import java.lang.invoke.MethodHandle;
35import java.lang.invoke.MethodHandles;
36import java.lang.invoke.MethodType;
37import java.lang.invoke.SwitchPoint;
38import java.util.Collections;
39import jdk.internal.dynalink.CallSiteDescriptor;
40import jdk.internal.dynalink.linker.GuardedInvocation;
41import jdk.internal.dynalink.linker.LinkRequest;
42import jdk.internal.dynalink.support.Guards;
43import jdk.nashorn.internal.codegen.ApplySpecialization;
44import jdk.nashorn.internal.codegen.CompilerConstants.Call;
45import jdk.nashorn.internal.objects.Global;
46import jdk.nashorn.internal.objects.NativeFunction;
47import jdk.nashorn.internal.runtime.linker.Bootstrap;
48import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
49
50/**
51 * Runtime representation of a JavaScript function.
52 */
53public abstract class ScriptFunction extends ScriptObject {
54
55    /** Method handle for prototype getter for this ScriptFunction */
56    public static final MethodHandle G$PROTOTYPE = findOwnMH_S("G$prototype", Object.class, Object.class);
57
58    /** Method handle for prototype setter for this ScriptFunction */
59    public static final MethodHandle S$PROTOTYPE = findOwnMH_S("S$prototype", void.class, Object.class, Object.class);
60
61    /** Method handle for length getter for this ScriptFunction */
62    public static final MethodHandle G$LENGTH = findOwnMH_S("G$length", int.class, Object.class);
63
64    /** Method handle for name getter for this ScriptFunction */
65    public static final MethodHandle G$NAME = findOwnMH_S("G$name", Object.class, Object.class);
66
67    /** Method handle used for implementing sync() in mozilla_compat */
68    public static final MethodHandle INVOKE_SYNC = findOwnMH_S("invokeSync", Object.class, ScriptFunction.class, Object.class, Object.class, Object[].class);
69
70    /** Method handle for allocate function for this ScriptFunction */
71    static final MethodHandle ALLOCATE = findOwnMH_V("allocate", Object.class);
72
73    private static final MethodHandle WRAPFILTER = findOwnMH_S("wrapFilter", Object.class, Object.class);
74
75    private static final MethodHandle SCRIPTFUNCTION_GLOBALFILTER = findOwnMH_S("globalFilter", Object.class, Object.class);
76
77    /** method handle to scope getter for this ScriptFunction */
78    public static final Call GET_SCOPE = virtualCallNoLookup(ScriptFunction.class, "getScope", ScriptObject.class);
79
80    private static final MethodHandle IS_FUNCTION_MH  = findOwnMH_S("isFunctionMH", boolean.class, Object.class, ScriptFunctionData.class);
81
82    private static final MethodHandle IS_APPLY_FUNCTION  = findOwnMH_S("isApplyFunction", boolean.class, boolean.class, Object.class, Object.class);
83
84    private static final MethodHandle IS_NONSTRICT_FUNCTION = findOwnMH_S("isNonStrictFunction", boolean.class, Object.class, Object.class, ScriptFunctionData.class);
85
86    private static final MethodHandle ADD_ZEROTH_ELEMENT = findOwnMH_S("addZerothElement", Object[].class, Object[].class, Object.class);
87
88    private static final MethodHandle WRAP_THIS = MH.findStatic(MethodHandles.lookup(), ScriptFunctionData.class, "wrapThis", MH.type(Object.class, Object.class));
89
90    /** The parent scope. */
91    private final ScriptObject scope;
92
93    private final ScriptFunctionData data;
94
95    /** The property map used for newly allocated object when function is used as constructor. */
96    protected PropertyMap allocatorMap;
97
98    /**
99     * Constructor
100     *
101     * @param name          function name
102     * @param methodHandle  method handle to function (if specializations are present, assumed to be most generic)
103     * @param map           property map
104     * @param scope         scope
105     * @param specs         specialized version of this function - other method handles
106     * @param flags         {@link ScriptFunctionData} flags
107     */
108    protected ScriptFunction(
109            final String name,
110            final MethodHandle methodHandle,
111            final PropertyMap map,
112            final ScriptObject scope,
113            final MethodHandle[] specs,
114            final int flags) {
115
116        this(new FinalScriptFunctionData(name, methodHandle, specs, flags), map, scope);
117    }
118
119    /**
120     * Constructor
121     *
122     * @param data          static function data
123     * @param map           property map
124     * @param scope         scope
125     */
126    protected ScriptFunction(
127            final ScriptFunctionData data,
128            final PropertyMap map,
129            final ScriptObject scope) {
130
131        super(map);
132
133        if (Context.DEBUG) {
134            constructorCount++;
135        }
136
137        this.data  = data;
138        this.scope = scope;
139        this.allocatorMap = data.getAllocatorMap();
140    }
141
142    @Override
143    public String getClassName() {
144        return "Function";
145    }
146
147    /**
148     * ECMA 15.3.5.3 [[HasInstance]] (V)
149     * Step 3 if "prototype" value is not an Object, throw TypeError
150     */
151    @Override
152    public boolean isInstance(final ScriptObject instance) {
153        final Object basePrototype = getTargetFunction().getPrototype();
154        if (!(basePrototype instanceof ScriptObject)) {
155            throw typeError("prototype.not.an.object", ScriptRuntime.safeToString(getTargetFunction()), ScriptRuntime.safeToString(basePrototype));
156        }
157
158        for (ScriptObject proto = instance.getProto(); proto != null; proto = proto.getProto()) {
159            if (proto == basePrototype) {
160                return true;
161            }
162        }
163
164        return false;
165    }
166
167    /**
168     * Returns the target function for this function. If the function was not created using
169     * {@link #makeBoundFunction(Object, Object[])}, its target function is itself. If it is bound, its target function
170     * is the target function of the function it was made from (therefore, the target function is always the final,
171     * unbound recipient of the calls).
172     * @return the target function for this function.
173     */
174    protected ScriptFunction getTargetFunction() {
175        return this;
176    }
177
178    boolean isBoundFunction() {
179        return getTargetFunction() != this;
180    }
181
182    /**
183     * Set the arity of this ScriptFunction
184     * @param arity arity
185     */
186    public final void setArity(final int arity) {
187        data.setArity(arity);
188    }
189
190    /**
191     * Is this a ECMAScript 'use strict' function?
192     * @return true if function is in strict mode
193     */
194    public boolean isStrict() {
195        return data.isStrict();
196    }
197
198    /**
199     * Returns true if this is a non-strict, non-built-in function that requires non-primitive this argument
200     * according to ECMA 10.4.3.
201     * @return true if this argument must be an object
202     */
203    public boolean needsWrappedThis() {
204        return data.needsWrappedThis();
205    }
206
207    private static boolean needsWrappedThis(final Object fn) {
208        return fn instanceof ScriptFunction ? ((ScriptFunction)fn).needsWrappedThis() : false;
209    }
210
211    /**
212     * Execute this script function.
213     * @param self  Target object.
214     * @param arguments  Call arguments.
215     * @return ScriptFunction result.
216     * @throws Throwable if there is an exception/error with the invocation or thrown from it
217     */
218    Object invoke(final Object self, final Object... arguments) throws Throwable {
219        if (Context.DEBUG) {
220            invokes++;
221        }
222        return data.invoke(this, self, arguments);
223    }
224
225    /**
226     * Execute this script function as a constructor.
227     * @param arguments  Call arguments.
228     * @return Newly constructed result.
229     * @throws Throwable if there is an exception/error with the invocation or thrown from it
230     */
231    Object construct(final Object... arguments) throws Throwable {
232        return data.construct(this, arguments);
233    }
234
235    /**
236     * Allocate function. Called from generated {@link ScriptObject} code
237     * for allocation as a factory method
238     *
239     * @return a new instance of the {@link ScriptObject} whose allocator this is
240     */
241    @SuppressWarnings("unused")
242    private Object allocate() {
243        if (Context.DEBUG) {
244            allocations++;
245        }
246
247        assert !isBoundFunction(); // allocate never invoked on bound functions
248
249        final ScriptObject object = data.allocate(allocatorMap);
250
251        if (object != null) {
252            final Object prototype = getPrototype();
253            if (prototype instanceof ScriptObject) {
254                object.setInitialProto((ScriptObject)prototype);
255            }
256
257            if (object.getProto() == null) {
258                object.setInitialProto(getObjectPrototype());
259            }
260        }
261
262        return object;
263    }
264
265    /**
266     * Return Object.prototype - used by "allocate"
267     * @return Object.prototype
268     */
269    protected abstract ScriptObject getObjectPrototype();
270
271    /**
272     * Creates a version of this function bound to a specific "self" and other arguments, as per
273     * {@code Function.prototype.bind} functionality in ECMAScript 5.1 section 15.3.4.5.
274     * @param self the self to bind to this function. Can be null (in which case, null is bound as this).
275     * @param args additional arguments to bind to this function. Can be null or empty to not bind additional arguments.
276     * @return a function with the specified self and parameters bound.
277     */
278    protected ScriptFunction makeBoundFunction(final Object self, final Object[] args) {
279        return makeBoundFunction(data.makeBoundFunctionData(this, self, args));
280    }
281
282    /**
283     * Create a version of this function as in {@link ScriptFunction#makeBoundFunction(Object, Object[])},
284     * but using a {@link ScriptFunctionData} for the bound data.
285     *
286     * @param boundData ScriptFuntionData for the bound function
287     * @return a function with the bindings performed according to the given data
288     */
289    protected abstract ScriptFunction makeBoundFunction(ScriptFunctionData boundData);
290
291    @Override
292    public final String safeToString() {
293        return toSource();
294    }
295
296    @Override
297    public String toString() {
298        return data.toString();
299    }
300
301    /**
302     * Get this function as a String containing its source code. If no source code
303     * exists in this ScriptFunction, its contents will be displayed as {@code [native code]}
304     * @return string representation of this function's source
305     */
306    public final String toSource() {
307        return data.toSource();
308    }
309
310    /**
311     * Get the prototype object for this function
312     * @return prototype
313     */
314    public abstract Object getPrototype();
315
316    /**
317     * Set the prototype object for this function
318     * @param prototype new prototype object
319     */
320    public abstract void setPrototype(Object prototype);
321
322    /**
323     * Create a function that invokes this function synchronized on {@code sync} or the self object
324     * of the invocation.
325     * @param sync the Object to synchronize on, or undefined
326     * @return synchronized function
327     */
328   public abstract ScriptFunction makeSynchronizedFunction(Object sync);
329
330    /**
331     * Return the invoke handle bound to a given ScriptObject self reference.
332     * If callee parameter is required result is rebound to this.
333     *
334     * @param self self reference
335     * @return bound invoke handle
336     */
337    public final MethodHandle getBoundInvokeHandle(final Object self) {
338        return MH.bindTo(bindToCalleeIfNeeded(data.getGenericInvoker(scope)), self);
339    }
340
341    /**
342     * Bind the method handle to this {@code ScriptFunction} instance if it needs a callee parameter. If this function's
343     * method handles don't have a callee parameter, the handle is returned unchanged.
344     * @param methodHandle the method handle to potentially bind to this function instance.
345     * @return the potentially bound method handle
346     */
347    private MethodHandle bindToCalleeIfNeeded(final MethodHandle methodHandle) {
348        return ScriptFunctionData.needsCallee(methodHandle) ? MH.bindTo(methodHandle, this) : methodHandle;
349
350    }
351
352    /**
353     * Get the name for this function
354     * @return the name
355     */
356    public final String getName() {
357        return data.getName();
358    }
359
360
361    /**
362     * Get the scope for this function
363     * @return the scope
364     */
365    public final ScriptObject getScope() {
366        return scope;
367    }
368
369    /**
370     * Prototype getter for this ScriptFunction - follows the naming convention
371     * used by Nasgen and the code generator
372     *
373     * @param self  self reference
374     * @return self's prototype
375     */
376    public static Object G$prototype(final Object self) {
377        return self instanceof ScriptFunction ?
378            ((ScriptFunction)self).getPrototype() :
379            UNDEFINED;
380    }
381
382    /**
383     * Prototype setter for this ScriptFunction - follows the naming convention
384     * used by Nasgen and the code generator
385     *
386     * @param self  self reference
387     * @param prototype prototype to set
388     */
389    public static void S$prototype(final Object self, final Object prototype) {
390        if (self instanceof ScriptFunction) {
391            ((ScriptFunction)self).setPrototype(prototype);
392        }
393    }
394
395    /**
396     * Length getter - ECMA 15.3.3.2: Function.length
397     * @param self self reference
398     * @return length
399     */
400    public static int G$length(final Object self) {
401        if (self instanceof ScriptFunction) {
402            return ((ScriptFunction)self).data.getArity();
403        }
404
405        return 0;
406    }
407
408    /**
409     * Name getter - ECMA Function.name
410     * @param self self refence
411     * @return the name, or undefined if none
412     */
413    public static Object G$name(final Object self) {
414        if (self instanceof ScriptFunction) {
415            return ((ScriptFunction)self).getName();
416        }
417
418        return UNDEFINED;
419    }
420
421    /**
422     * Get the prototype for this ScriptFunction
423     * @param constructor constructor
424     * @return prototype, or null if given constructor is not a ScriptFunction
425     */
426    public static ScriptObject getPrototype(final Object constructor) {
427        if (constructor instanceof ScriptFunction) {
428            final Object proto = ((ScriptFunction)constructor).getPrototype();
429            if (proto instanceof ScriptObject) {
430                return (ScriptObject)proto;
431            }
432        }
433
434        return null;
435    }
436
437    // These counters are updated only in debug mode.
438    private static int constructorCount;
439    private static int invokes;
440    private static int allocations;
441
442    /**
443     * @return the constructorCount
444     */
445    public static int getConstructorCount() {
446        return constructorCount;
447    }
448
449    /**
450     * @return the invokes
451     */
452    public static int getInvokes() {
453        return invokes;
454    }
455
456    /**
457     * @return the allocations
458     */
459    public static int getAllocations() {
460        return allocations;
461    }
462
463    @Override
464    protected GuardedInvocation findNewMethod(final CallSiteDescriptor desc, final LinkRequest request) {
465        final MethodType type = desc.getMethodType();
466        assert desc.getMethodType().returnType() == Object.class && !NashornCallSiteDescriptor.isOptimistic(desc);
467        final CompiledFunction cf = data.getBestConstructor(type, scope);
468        final GuardedInvocation bestCtorInv = new GuardedInvocation(cf.getConstructor(), cf.getOptimisticAssumptionsSwitchPoint());
469        //TODO - ClassCastException
470        return new GuardedInvocation(pairArguments(bestCtorInv.getInvocation(), type), getFunctionGuard(this, cf.getFlags()), bestCtorInv.getSwitchPoints(), null);
471    }
472
473    @SuppressWarnings("unused")
474    private static Object wrapFilter(final Object obj) {
475        if (obj instanceof ScriptObject || !ScriptFunctionData.isPrimitiveThis(obj)) {
476            return obj;
477        }
478        return Context.getGlobal().wrapAsObject(obj);
479    }
480
481
482    @SuppressWarnings("unused")
483    private static Object globalFilter(final Object object) {
484        // replace whatever we get with the current global object
485        return Context.getGlobal();
486    }
487
488    /**
489     * dyn:call call site signature: (callee, thiz, [args...])
490     * generated method signature:   (callee, thiz, [args...])
491     *
492     * cases:
493     * (a) method has callee parameter
494     *   (1) for local/scope calls, we just bind thiz and drop the second argument.
495     *   (2) for normal this-calls, we have to swap thiz and callee to get matching signatures.
496     * (b) method doesn't have callee parameter (builtin functions)
497     *   (3) for local/scope calls, bind thiz and drop both callee and thiz.
498     *   (4) for normal this-calls, drop callee.
499     *
500     * @return guarded invocation for call
501     */
502    @Override
503    protected GuardedInvocation findCallMethod(final CallSiteDescriptor desc, final LinkRequest request) {
504        final MethodType type = desc.getMethodType();
505
506        final String  name       = getName();
507        final boolean isUnstable = request.isCallSiteUnstable();
508        final boolean scopeCall  = NashornCallSiteDescriptor.isScope(desc);
509        final boolean isCall     = !scopeCall && data.isBuiltin() && "call".equals(name);
510        final boolean isApply    = !scopeCall && data.isBuiltin() && "apply".equals(name);
511
512        final boolean isApplyOrCall = isCall | isApply;
513
514        if (isUnstable && !isApplyOrCall) {
515            //megamorphic - replace call with apply
516            final MethodHandle handle;
517            //ensure that the callsite is vararg so apply can consume it
518            if (type.parameterCount() == 3 && type.parameterType(2) == Object[].class) {
519                // Vararg call site
520                handle = ScriptRuntime.APPLY.methodHandle();
521            } else {
522                // (callee, this, args...) => (callee, this, args[])
523                handle = MH.asCollector(ScriptRuntime.APPLY.methodHandle(), Object[].class, type.parameterCount() - 2);
524            }
525
526            // If call site is statically typed to take a ScriptFunction, we don't need a guard, otherwise we need a
527            // generic "is this a ScriptFunction?" guard.
528            return new GuardedInvocation(
529                    handle,
530                    null,
531                    (SwitchPoint)null,
532                    ClassCastException.class);
533        }
534
535        MethodHandle boundHandle;
536        MethodHandle guard = null;
537
538        // Special handling of Function.apply and Function.call. Note we must be invoking
539        if (isApplyOrCall && !isUnstable) {
540            final Object[] args = request.getArguments();
541            if (Bootstrap.isCallable(args[1])) {
542                return createApplyOrCallCall(isApply, desc, request, args);
543            }
544        } //else just fall through and link as ordinary function or unstable apply
545
546        final int programPoint = NashornCallSiteDescriptor.isOptimistic(desc) ? NashornCallSiteDescriptor.getProgramPoint(desc) : INVALID_PROGRAM_POINT;
547        final CompiledFunction cf = data.getBestInvoker(type, scope);
548        final GuardedInvocation bestInvoker =
549                new GuardedInvocation(
550                        cf.createInvoker(type.returnType(), programPoint),
551                        cf.getOptimisticAssumptionsSwitchPoint());
552
553        final MethodHandle callHandle = bestInvoker.getInvocation();
554
555        if (data.needsCallee()) {
556            if (scopeCall && needsWrappedThis()) {
557                // (callee, this, args...) => (callee, [this], args...)
558                boundHandle = MH.filterArguments(callHandle, 1, SCRIPTFUNCTION_GLOBALFILTER);
559            } else {
560                // It's already (callee, this, args...), just what we need
561                boundHandle = callHandle;
562            }
563        } else if (data.isBuiltin() && "extend".equals(data.getName())) {
564            // NOTE: the only built-in named "extend" is NativeJava.extend. As a special-case we're binding the
565            // current lookup as its "this" so it can do security-sensitive creation of adapter classes.
566            boundHandle = MH.dropArguments(MH.bindTo(callHandle, desc.getLookup()), 0, type.parameterType(0), type.parameterType(1));
567        } else if (scopeCall && needsWrappedThis()) {
568            // Make a handle that drops the passed "this" argument and substitutes either Global or Undefined
569            // (this, args...) => ([this], args...)
570            boundHandle = MH.filterArguments(callHandle, 0, SCRIPTFUNCTION_GLOBALFILTER);
571            // ([this], args...) => ([callee], [this], args...)
572            boundHandle = MH.dropArguments(boundHandle, 0, type.parameterType(0));
573        } else {
574            // (this, args...) => ([callee], this, args...)
575            boundHandle = MH.dropArguments(callHandle, 0, type.parameterType(0));
576        }
577
578        // For non-strict functions, check whether this-object is primitive type.
579        // If so add a to-object-wrapper argument filter.
580        // Else install a guard that will trigger a relink when the argument becomes primitive.
581        if (!scopeCall && needsWrappedThis()) {
582            if (ScriptFunctionData.isPrimitiveThis(request.getArguments()[1])) {
583                boundHandle = MH.filterArguments(boundHandle, 1, WRAPFILTER);
584            } else {
585                guard = getNonStrictFunctionGuard(this);
586            }
587        }
588
589        boundHandle = pairArguments(boundHandle, type);
590
591        return new GuardedInvocation(boundHandle, guard == null ? getFunctionGuard(this, cf.getFlags()) : guard, bestInvoker.getSwitchPoints(), null);
592    }
593
594    private GuardedInvocation createApplyOrCallCall(final boolean isApply, final CallSiteDescriptor desc, final LinkRequest request, final Object[] args) {
595        final MethodType descType = desc.getMethodType();
596        final int paramCount = descType.parameterCount();
597        if(descType.parameterType(paramCount - 1).isArray()) {
598            // This is vararg invocation of apply or call. This can normally only happen when we do a recursive
599            // invocation of createApplyOrCallCall (because we're doing apply-of-apply). In this case, create delegate
600            // linkage by unpacking the vararg invocation and use pairArguments to introduce the necessary spreader.
601            return createVarArgApplyOrCallCall(isApply, desc, request, args);
602        }
603
604        final boolean passesThis = paramCount > 2;
605        final boolean passesArgs = paramCount > 3;
606        final int realArgCount = passesArgs ? paramCount - 3 : 0;
607
608        final Object appliedFn = args[1];
609        final boolean appliedFnNeedsWrappedThis = needsWrappedThis(appliedFn);
610
611        //box call back to apply
612        CallSiteDescriptor appliedDesc = desc;
613        final SwitchPoint applyToCallSwitchPoint = Global.instance().getChangeCallback("apply");
614        //enough to change the proto switchPoint here
615
616        final boolean isApplyToCall = NashornCallSiteDescriptor.isApplyToCall(desc);
617        final boolean isFailedApplyToCall = isApplyToCall && applyToCallSwitchPoint.hasBeenInvalidated();
618
619        // R(apply|call, ...) => R(...)
620        MethodType appliedType = descType.dropParameterTypes(0, 1);
621        if (!passesThis) {
622            // R() => R(this)
623            appliedType = appliedType.insertParameterTypes(1, Object.class);
624        } else if (appliedFnNeedsWrappedThis) {
625            appliedType = appliedType.changeParameterType(1, Object.class);
626        }
627
628        if (isApply || isFailedApplyToCall) {
629            if (passesArgs) {
630                // R(this, args) => R(this, Object[])
631                appliedType = appliedType.changeParameterType(2, Object[].class);
632                // drop any extraneous arguments for the apply fail case
633                if (isFailedApplyToCall) {
634                    appliedType = appliedType.dropParameterTypes(3, paramCount - 1);
635                }
636            } else {
637                // R(this) => R(this, Object[])
638                appliedType = appliedType.insertParameterTypes(2, Object[].class);
639            }
640        }
641
642        appliedDesc = appliedDesc.changeMethodType(appliedType);
643
644        // Create the same arguments for the delegate linking request that would be passed in an actual apply'd invocation
645        final Object[] appliedArgs = new Object[isApply ? 3 : appliedType.parameterCount()];
646        appliedArgs[0] = appliedFn;
647        appliedArgs[1] = passesThis ? appliedFnNeedsWrappedThis ? ScriptFunctionData.wrapThis(args[2]) : args[2] : ScriptRuntime.UNDEFINED;
648        if (isApply && !isFailedApplyToCall) {
649            appliedArgs[2] = passesArgs ? NativeFunction.toApplyArgs(args[3]) : ScriptRuntime.EMPTY_ARRAY;
650        } else {
651            if (passesArgs) {
652                if (isFailedApplyToCall) {
653                    final Object[] tmp = new Object[args.length - 3];
654                    System.arraycopy(args, 3, tmp, 0, tmp.length);
655                    appliedArgs[2] = NativeFunction.toApplyArgs(tmp);
656                } else {
657                    assert !isApply;
658                    System.arraycopy(args, 3, appliedArgs, 2, args.length - 3);
659                }
660            } else if (isFailedApplyToCall) {
661                appliedArgs[2] = ScriptRuntime.EMPTY_ARRAY;
662            }
663        }
664
665        // Ask the linker machinery for an invocation of the target function
666        final LinkRequest appliedRequest = request.replaceArguments(appliedDesc, appliedArgs);
667        GuardedInvocation appliedInvocation;
668        try {
669            appliedInvocation = Bootstrap.getLinkerServices().getGuardedInvocation(appliedRequest);
670        } catch (final RuntimeException | Error e) {
671            throw e;
672        } catch (final Exception e) {
673            throw new RuntimeException(e);
674        }
675        assert appliedRequest != null; // Bootstrap.isCallable() returned true for args[1], so it must produce a linkage.
676
677        final Class<?> applyFnType = descType.parameterType(0);
678        MethodHandle inv = appliedInvocation.getInvocation(); //method handle from apply invocation. the applied function invocation
679
680        if (isApply && !isFailedApplyToCall) {
681            if (passesArgs) {
682                // Make sure that the passed argArray is converted to Object[] the same way NativeFunction.apply() would do it.
683                inv = MH.filterArguments(inv, 2, NativeFunction.TO_APPLY_ARGS);
684            } else {
685                // If the original call site doesn't pass argArray, pass in an empty array
686                inv = MH.insertArguments(inv, 2, (Object)ScriptRuntime.EMPTY_ARRAY);
687            }
688        }
689
690        if (isApplyToCall) {
691            if (isFailedApplyToCall) {
692                //take the real arguments that were passed to a call and force them into the apply instead
693                Context.getContextTrusted().getLogger(ApplySpecialization.class).info("Collection arguments to revert call to apply in " + appliedFn);
694                inv = MH.asCollector(inv, Object[].class, realArgCount);
695            } else {
696                appliedInvocation = appliedInvocation.addSwitchPoint(applyToCallSwitchPoint);
697            }
698        }
699
700        if (!passesThis) {
701            // If the original call site doesn't pass in a thisArg, pass in Global/undefined as needed
702            inv = bindImplicitThis(appliedFn, inv);
703        } else if (appliedFnNeedsWrappedThis) {
704            // target function needs a wrapped this, so make sure we filter for that
705            inv = MH.filterArguments(inv, 1, WRAP_THIS);
706        }
707        inv = MH.dropArguments(inv, 0, applyFnType);
708
709        MethodHandle guard = appliedInvocation.getGuard();
710        // If the guard checks the value of "this" but we aren't passing thisArg, insert the default one
711        if (!passesThis && guard.type().parameterCount() > 1) {
712            guard = bindImplicitThis(appliedFn, guard);
713        }
714        final MethodType guardType = guard.type();
715
716        // We need to account for the dropped (apply|call) function argument.
717        guard = MH.dropArguments(guard, 0, descType.parameterType(0));
718        // Take the "isApplyFunction" guard, and bind it to this function.
719        MethodHandle applyFnGuard = MH.insertArguments(IS_APPLY_FUNCTION, 2, this);
720        // Adapt the guard to receive all the arguments that the original guard does.
721        applyFnGuard = MH.dropArguments(applyFnGuard, 2, guardType.parameterArray());
722        // Fold the original function guard into our apply guard.
723        guard = MH.foldArguments(applyFnGuard, guard);
724
725        return appliedInvocation.replaceMethods(inv, guard);
726    }
727
728    /*
729     * This method is used for linking nested apply. Specialized apply and call linking will create a variable arity
730     * call site for an apply call; when createApplyOrCallCall sees a linking request for apply or call with
731     * Nashorn-style variable arity call site (last argument type is Object[]) it'll delegate to this method.
732     * This method converts the link request from a vararg to a non-vararg one (unpacks the array), then delegates back
733     * to createApplyOrCallCall (with which it is thus mutually recursive), and adds appropriate argument spreaders to
734     * invocation and the guard of whatever createApplyOrCallCall returned to adapt it back into a variable arity
735     * invocation. It basically reduces the problem of vararg call site linking of apply and call back to the (already
736     * solved by createApplyOrCallCall) non-vararg call site linking.
737     */
738    private GuardedInvocation createVarArgApplyOrCallCall(final boolean isApply, final CallSiteDescriptor desc,
739            final LinkRequest request, final Object[] args) {
740        final MethodType descType = desc.getMethodType();
741        final int paramCount = descType.parameterCount();
742        final Object[] varArgs = (Object[])args[paramCount - 1];
743        // -1 'cause we're not passing the vararg array itself
744        final int copiedArgCount = args.length - 1;
745        int varArgCount = varArgs.length;
746
747        // Spread arguments for the delegate createApplyOrCallCall invocation.
748        final Object[] spreadArgs = new Object[copiedArgCount + varArgCount];
749        System.arraycopy(args, 0, spreadArgs, 0, copiedArgCount);
750        System.arraycopy(varArgs, 0, spreadArgs, copiedArgCount, varArgCount);
751
752        // Spread call site descriptor for the delegate createApplyOrCallCall invocation. We drop vararg array and
753        // replace it with a list of Object.class.
754        final MethodType spreadType = descType.dropParameterTypes(paramCount - 1, paramCount).appendParameterTypes(
755                Collections.<Class<?>>nCopies(varArgCount, Object.class));
756        final CallSiteDescriptor spreadDesc = desc.changeMethodType(spreadType);
757
758        // Delegate back to createApplyOrCallCall with the spread (that is, reverted to non-vararg) request/
759        final LinkRequest spreadRequest = request.replaceArguments(spreadDesc, spreadArgs);
760        final GuardedInvocation spreadInvocation = createApplyOrCallCall(isApply, spreadDesc, spreadRequest, spreadArgs);
761
762        // Add spreader combinators to returned invocation and guard.
763        return spreadInvocation.replaceMethods(
764                // Use standard ScriptObject.pairArguments on the invocation
765                pairArguments(spreadInvocation.getInvocation(), descType),
766                // Use our specialized spreadGuardArguments on the guard (see below).
767                spreadGuardArguments(spreadInvocation.getGuard(), descType));
768    }
769
770    private static MethodHandle spreadGuardArguments(final MethodHandle guard, final MethodType descType) {
771        final MethodType guardType = guard.type();
772        final int guardParamCount = guardType.parameterCount();
773        final int descParamCount = descType.parameterCount();
774        final int spreadCount = guardParamCount - descParamCount + 1;
775        if (spreadCount <= 0) {
776            // Guard doesn't dip into the varargs
777            return guard;
778        }
779
780        final MethodHandle arrayConvertingGuard;
781        // If the last parameter type of the guard is an array, then it is already itself a guard for a vararg apply
782        // invocation. We must filter the last argument with toApplyArgs otherwise deeper levels of nesting will fail
783        // with ClassCastException of NativeArray to Object[].
784        if(guardType.parameterType(guardParamCount - 1).isArray()) {
785            arrayConvertingGuard = MH.filterArguments(guard, guardParamCount - 1, NativeFunction.TO_APPLY_ARGS);
786        } else {
787            arrayConvertingGuard = guard;
788        }
789
790        return ScriptObject.adaptHandleToVarArgCallSite(arrayConvertingGuard, descParamCount);
791    }
792
793    private static MethodHandle bindImplicitThis(final Object fn, final MethodHandle mh) {
794         final MethodHandle bound;
795         if(fn instanceof ScriptFunction && ((ScriptFunction)fn).needsWrappedThis()) {
796             bound = MH.filterArguments(mh, 1, SCRIPTFUNCTION_GLOBALFILTER);
797         } else {
798             bound = mh;
799         }
800         return MH.insertArguments(bound, 1, ScriptRuntime.UNDEFINED);
801     }
802
803    /**
804     * Used for noSuchMethod/noSuchProperty and JSAdapter hooks.
805     *
806     * These don't want a callee parameter, so bind that. Name binding is optional.
807     */
808    MethodHandle getCallMethodHandle(final MethodType type, final String bindName) {
809        return pairArguments(bindToNameIfNeeded(bindToCalleeIfNeeded(data.getGenericInvoker(scope)), bindName), type);
810    }
811
812    private static MethodHandle bindToNameIfNeeded(final MethodHandle methodHandle, final String bindName) {
813        if (bindName == null) {
814            return methodHandle;
815        }
816
817        // if it is vararg method, we need to extend argument array with
818        // a new zeroth element that is set to bindName value.
819        final MethodType methodType = methodHandle.type();
820        final int parameterCount = methodType.parameterCount();
821        final boolean isVarArg = parameterCount > 0 && methodType.parameterType(parameterCount - 1).isArray();
822
823        if (isVarArg) {
824            return MH.filterArguments(methodHandle, 1, MH.insertArguments(ADD_ZEROTH_ELEMENT, 1, bindName));
825        }
826        return MH.insertArguments(methodHandle, 1, bindName);
827    }
828
829    /**
830     * Get the guard that checks if a {@link ScriptFunction} is equal to
831     * a known ScriptFunction, using reference comparison
832     *
833     * @param function The ScriptFunction to check against. This will be bound to the guard method handle
834     *
835     * @return method handle for guard
836     */
837    private static MethodHandle getFunctionGuard(final ScriptFunction function, final int flags) {
838        assert function.data != null;
839        // Built-in functions have a 1-1 correspondence to their ScriptFunctionData, so we can use a cheaper identity
840        // comparison for them.
841        if (function.data.isBuiltin()) {
842            return Guards.getIdentityGuard(function);
843        }
844        return MH.insertArguments(IS_FUNCTION_MH, 1, function.data);
845    }
846
847    /**
848     * Get a guard that checks if a {@link ScriptFunction} is equal to
849     * a known ScriptFunction using reference comparison, and whether the type of
850     * the second argument (this-object) is not a JavaScript primitive type.
851     *
852     * @param function The ScriptFunction to check against. This will be bound to the guard method handle
853     *
854     * @return method handle for guard
855     */
856    private static MethodHandle getNonStrictFunctionGuard(final ScriptFunction function) {
857        assert function.data != null;
858        return MH.insertArguments(IS_NONSTRICT_FUNCTION, 2, function.data);
859    }
860
861    @SuppressWarnings("unused")
862    private static boolean isFunctionMH(final Object self, final ScriptFunctionData data) {
863        return self instanceof ScriptFunction && ((ScriptFunction)self).data == data;
864    }
865
866    @SuppressWarnings("unused")
867    private static boolean isNonStrictFunction(final Object self, final Object arg, final ScriptFunctionData data) {
868        return self instanceof ScriptFunction && ((ScriptFunction)self).data == data && arg instanceof ScriptObject;
869    }
870
871    @SuppressWarnings("unused")
872    private static boolean isApplyFunction(final boolean appliedFnCondition, final Object self, final Object expectedSelf) {
873        // NOTE: we're using self == expectedSelf as we're only using this with built-in functions apply() and call()
874        return appliedFnCondition && self == expectedSelf;
875    }
876
877    @SuppressWarnings("unused")
878    private static Object[] addZerothElement(final Object[] args, final Object value) {
879        // extends input array with by adding new zeroth element
880        final Object[] src = args == null? ScriptRuntime.EMPTY_ARRAY : args;
881        final Object[] result = new Object[src.length + 1];
882        System.arraycopy(src, 0, result, 1, src.length);
883        result[0] = value;
884        return result;
885    }
886
887    @SuppressWarnings("unused")
888    private static Object invokeSync(final ScriptFunction func, final Object sync, final Object self, final Object... args)
889            throws Throwable {
890        final Object syncObj = sync == UNDEFINED ? self : sync;
891        synchronized (syncObj) {
892            return func.invoke(self, args);
893        }
894    }
895
896    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
897        return MH.findStatic(MethodHandles.lookup(), ScriptFunction.class, name, MH.type(rtype, types));
898    }
899
900    private static MethodHandle findOwnMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
901        return MH.findVirtual(MethodHandles.lookup(), ScriptFunction.class, name, MH.type(rtype, types));
902    }
903}
904
905