function.c 30.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright 2008 Jacek Caban for CodeWeavers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

19 20
#include <assert.h>

21
#include "jscript.h"
22
#include "engine.h"
23 24 25 26 27

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(jscript);

28 29
typedef struct _function_vtbl_t function_vtbl_t;

30
typedef struct {
31
    jsdisp_t dispex;
32
    const function_vtbl_t *vtbl;
33 34 35 36
    DWORD flags;
    DWORD length;
} FunctionInstance;

37
struct _function_vtbl_t {
38
    HRESULT (*call)(script_ctx_t*,FunctionInstance*,IDispatch*,unsigned,unsigned,jsval_t*,jsval_t*);
39
    HRESULT (*toString)(FunctionInstance*,jsstr_t**);
40
    function_code_t* (*get_code)(FunctionInstance*);
41
    void (*destructor)(FunctionInstance*);
42 43
};

44 45 46 47 48 49 50
typedef struct {
    FunctionInstance function;
    scope_chain_t *scope_chain;
    bytecode_t *code;
    function_code_t *func_code;
} InterpretedFunction;

51 52
typedef struct {
    FunctionInstance function;
53
    builtin_invoke_t proc;
54
    const WCHAR *name;
55 56
} NativeFunction;

57 58 59 60 61 62 63 64
typedef struct {
    FunctionInstance function;
    FunctionInstance *target;
    IDispatch *this;
    unsigned argc;
    jsval_t args[1];
} BindFunction;

65 66
typedef struct {
    jsdisp_t jsdisp;
67
    InterpretedFunction *function;
68 69 70
    jsval_t *buf;
    call_frame_t *frame;
    unsigned argc;
71 72
} ArgumentsInstance;

73 74
static HRESULT create_bind_function(script_ctx_t*,FunctionInstance*,IDispatch*,unsigned,jsval_t*,jsdisp_t**r);

75 76 77 78 79
static inline FunctionInstance *function_from_jsdisp(jsdisp_t *jsdisp)
{
    return CONTAINING_RECORD(jsdisp, FunctionInstance, dispex);
}

80 81
static inline FunctionInstance *function_from_vdisp(vdisp_t *vdisp)
{
82
    return function_from_jsdisp(vdisp->u.jsdisp);
83 84 85 86 87 88 89
}

static inline FunctionInstance *function_this(vdisp_t *jsthis)
{
    return is_vclass(jsthis, JSCLASS_FUNCTION) ? function_from_vdisp(jsthis) : NULL;
}

90 91 92 93 94
static inline ArgumentsInstance *arguments_from_jsdisp(jsdisp_t *jsdisp)
{
    return CONTAINING_RECORD(jsdisp, ArgumentsInstance, jsdisp);
}

95
static HRESULT Arguments_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
96
        jsval_t *r)
97 98 99 100 101
{
    FIXME("\n");
    return E_NOTIMPL;
}

102 103
static void Arguments_destructor(jsdisp_t *jsdisp)
{
104
    ArgumentsInstance *arguments = arguments_from_jsdisp(jsdisp);
105

106 107
    TRACE("(%p)\n", arguments);

108 109 110 111 112 113 114
    if(arguments->buf) {
        unsigned i;
        for(i = 0; i < arguments->argc; i++)
            jsval_release(arguments->buf[i]);
        heap_free(arguments->buf);
    }

115
    jsdisp_release(&arguments->function->function.dispex);
116 117 118 119 120
    heap_free(arguments);
}

static unsigned Arguments_idx_length(jsdisp_t *jsdisp)
{
121
    ArgumentsInstance *arguments = arguments_from_jsdisp(jsdisp);
122
    return arguments->argc;
123 124
}

125 126
static jsval_t *get_argument_ref(ArgumentsInstance *arguments, unsigned idx)
{
127 128 129 130 131
    if(arguments->buf)
        return arguments->buf + idx;
    if(arguments->frame->base_scope->frame || idx >= arguments->frame->function->param_cnt)
        return arguments->jsdisp.ctx->stack + arguments->frame->arguments_off + idx;
    return NULL;
132 133 134
}

static HRESULT Arguments_idx_get(jsdisp_t *jsdisp, unsigned idx, jsval_t *r)
135
{
136
    ArgumentsInstance *arguments = arguments_from_jsdisp(jsdisp);
137
    jsval_t *ref;
138 139 140

    TRACE("%p[%u]\n", arguments, idx);

141 142
    if((ref = get_argument_ref(arguments, idx)))
        return jsval_copy(*ref, r);
143

144
    /* FIXME: Accessing by name won't work for duplicated argument names */
145 146
    return jsdisp_propget_name(arguments->frame->base_scope->jsobj,
                               arguments->function->func_code->params[idx], r);
147 148 149 150
}

static HRESULT Arguments_idx_put(jsdisp_t *jsdisp, unsigned idx, jsval_t val)
{
151
    ArgumentsInstance *arguments = arguments_from_jsdisp(jsdisp);
152 153
    jsval_t *ref;
    HRESULT hres;
154 155 156

    TRACE("%p[%u] = %s\n", arguments, idx, debugstr_jsval(val));

157 158 159
    if((ref = get_argument_ref(arguments, idx))) {
        jsval_t copy;
        hres = jsval_copy(val, &copy);
160 161
        if(FAILED(hres))
            return hres;
162 163 164 165

        jsval_release(*ref);
        *ref = copy;
        return S_OK;
166 167
    }

168
    /* FIXME: Accessing by name won't work for duplicated argument names */
169 170
    return jsdisp_propput_name(arguments->frame->base_scope->jsobj,
                               arguments->function->func_code->params[idx], val);
171 172
}

173 174
static const builtin_info_t Arguments_info = {
    JSCLASS_ARGUMENTS,
175
    Arguments_value,
176
    0, NULL,
177
    Arguments_destructor,
178
    NULL,
179 180 181
    Arguments_idx_length,
    Arguments_idx_get,
    Arguments_idx_put
182 183
};

184
HRESULT setup_arguments_object(script_ctx_t *ctx, call_frame_t *frame)
185
{
186
    ArgumentsInstance *args;
187 188
    HRESULT hres;

189
    args = heap_alloc_zero(sizeof(*args));
190 191 192
    if(!args)
        return E_OUTOFMEMORY;

193
    hres = init_dispex_from_constr(&args->jsdisp, ctx, &Arguments_info, ctx->object_constr);
194 195 196 197 198
    if(FAILED(hres)) {
        heap_free(args);
        return hres;
    }

199
    args->function = (InterpretedFunction*)function_from_jsdisp(jsdisp_addref(frame->function_instance));
200
    args->argc = frame->argc;
201
    args->frame = frame;
202

203
    hres = jsdisp_define_data_property(&args->jsdisp, L"length", PROPF_WRITABLE | PROPF_CONFIGURABLE,
204
                                       jsval_number(args->argc));
205
    if(SUCCEEDED(hres))
206
        hres = jsdisp_define_data_property(&args->jsdisp, L"callee", PROPF_WRITABLE | PROPF_CONFIGURABLE,
207
                                           jsval_obj(&args->function->function.dispex));
208
    if(SUCCEEDED(hres))
209
        hres = jsdisp_propput(frame->base_scope->jsobj, L"arguments", PROPF_WRITABLE, TRUE, jsval_obj(&args->jsdisp));
210
    if(FAILED(hres)) {
211
        jsdisp_release(&args->jsdisp);
212 213 214
        return hres;
    }

215
    frame->arguments_obj = &args->jsdisp;
216
    return S_OK;
217 218
}

219 220 221 222 223 224 225 226 227
void detach_arguments_object(jsdisp_t *args_disp)
{
    ArgumentsInstance *arguments = arguments_from_jsdisp(args_disp);
    call_frame_t *frame = arguments->frame;
    const BOOL on_stack = frame->base_scope->frame == frame;
    HRESULT hres;

    /* Reset arguments value to cut the reference cycle. Note that since all activation contexts have
     * their own arguments property, it's impossible to use prototype's one during name lookup */
228
    jsdisp_propput_name(frame->base_scope->jsobj, L"arguments", jsval_undefined());
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    arguments->frame = NULL;

    /* Don't bother coppying arguments if call frame holds the last reference. */
    if(arguments->jsdisp.ref > 1) {
        arguments->buf = heap_alloc(arguments->argc * sizeof(*arguments->buf));
        if(arguments->buf) {
            int i;

            for(i = 0; i < arguments->argc ; i++) {
                if(on_stack || i >= frame->function->param_cnt)
                    hres = jsval_copy(arguments->jsdisp.ctx->stack[frame->arguments_off + i], arguments->buf+i);
                else
                    hres = jsdisp_propget_name(frame->base_scope->jsobj, frame->function->params[i], arguments->buf+i);
                if(FAILED(hres))
                    arguments->buf[i] = jsval_undefined();
            }
        }else {
            ERR("out of memory\n");
            arguments->argc = 0;
        }
    }

    jsdisp_release(frame->arguments_obj);
}

254
HRESULT Function_invoke(jsdisp_t *func_this, IDispatch *jsthis, WORD flags, unsigned argc, jsval_t *argv, jsval_t *r)
255 256 257
{
    FunctionInstance *function;

258
    TRACE("func %p this %p\n", func_this, jsthis);
259 260

    assert(is_class(func_this, JSCLASS_FUNCTION));
261
    function = function_from_jsdisp(func_this);
262

263
    return function->vtbl->call(function->dispex.ctx, function, jsthis, flags, argc, argv, r);
264 265
}

266
static HRESULT Function_get_length(script_ctx_t *ctx, jsdisp_t *jsthis, jsval_t *r)
267
{
268
    TRACE("%p\n", jsthis);
269

270
    *r = jsval_number(function_from_jsdisp(jsthis)->length);
271
    return S_OK;
272 273
}

274
static HRESULT Function_toString(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
275
        jsval_t *r)
276
{
277
    FunctionInstance *function;
278
    jsstr_t *str;
279 280 281 282
    HRESULT hres;

    TRACE("\n");

283
    if(!(function = function_this(jsthis)))
284
        return JS_E_FUNCTION_EXPECTED;
285

286
    hres = function->vtbl->toString(function, &str);
287 288 289
    if(FAILED(hres))
        return hres;

290 291 292
    if(r)
        *r = jsval_string(str);
    else
293
        jsstr_release(str);
294
    return S_OK;
295 296
}

297
static HRESULT array_to_args(script_ctx_t *ctx, jsdisp_t *arg_array, unsigned *argc, jsval_t **ret)
298
{
299
    jsval_t *argv, val;
300 301 302
    DWORD length, i;
    HRESULT hres;

303
    hres = jsdisp_propget_name(arg_array, L"length", &val);
304 305 306
    if(FAILED(hres))
        return hres;

307
    hres = to_uint32(ctx, val, &length);
308
    jsval_release(val);
309 310 311
    if(FAILED(hres))
        return hres;

312
    argv = heap_alloc(length * sizeof(*argv));
313
    if(!argv)
314 315 316
        return E_OUTOFMEMORY;

    for(i=0; i<length; i++) {
317
        hres = jsdisp_get_idx(arg_array, i, argv+i);
318 319 320
        if(hres == DISP_E_UNKNOWNNAME) {
            argv[i] = jsval_undefined();
        }else if(FAILED(hres)) {
321
            while(i--)
322
                jsval_release(argv[i]);
323 324 325 326 327
            heap_free(argv);
            return hres;
        }
    }

328 329
    *argc = length;
    *ret = argv;
330 331 332
    return S_OK;
}

333
static HRESULT Function_apply(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv, jsval_t *r)
334
{
335
    FunctionInstance *function;
336
    jsval_t *args = NULL;
337
    unsigned i, cnt = 0;
338
    IDispatch *this_obj = NULL;
339 340 341 342
    HRESULT hres = S_OK;

    TRACE("\n");

343
    if(!(function = function_this(jsthis)) && (jsthis->flags & VDISP_JSDISP))
344
        return JS_E_FUNCTION_EXPECTED;
345 346

    if(argc) {
347
        if(!is_undefined(argv[0]) && !is_null(argv[0])) {
348
            hres = to_object(ctx, argv[0], &this_obj);
349 350 351
            if(FAILED(hres))
                return hres;
        }
352 353 354
    }

    if(argc >= 2) {
355
        jsdisp_t *arg_array = NULL;
356

357
        if(is_object_instance(argv[1])) {
358
            arg_array = iface_to_jsdisp(get_object(argv[1]));
359 360
            if(arg_array &&
               (!is_class(arg_array, JSCLASS_ARRAY) && !is_class(arg_array, JSCLASS_ARGUMENTS) )) {
361 362 363 364 365 366
                jsdisp_release(arg_array);
                arg_array = NULL;
            }
        }

        if(arg_array) {
367
            hres = array_to_args(ctx, arg_array, &cnt, &args);
368 369
            jsdisp_release(arg_array);
        }else {
370
            FIXME("throw TypeError\n");
371 372 373 374
            hres = E_FAIL;
        }
    }

375 376
    if(SUCCEEDED(hres)) {
        if(function) {
377
            hres = function->vtbl->call(ctx, function, this_obj, flags, cnt, args, r);
378 379 380 381 382 383 384 385 386 387 388
        }else {
            jsval_t res;
            hres = disp_call_value(ctx, jsthis->u.disp, this_obj, DISPATCH_METHOD, cnt, args, &res);
            if(SUCCEEDED(hres)) {
                if(r)
                    *r = res;
                else
                    jsval_release(res);
            }
        }
    }
389 390 391

    if(this_obj)
        IDispatch_Release(this_obj);
392
    for(i=0; i < cnt; i++)
393
        jsval_release(args[i]);
394
    heap_free(args);
395
    return hres;
396 397
}

398
static HRESULT Function_call(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
399
        jsval_t *r)
400
{
401 402
    FunctionInstance *function;
    IDispatch *this_obj = NULL;
403
    unsigned cnt = 0;
404 405 406 407
    HRESULT hres;

    TRACE("\n");

408
    if(!(function = function_this(jsthis)))
409
        return JS_E_FUNCTION_EXPECTED;
410 411

    if(argc) {
412
        if(!is_undefined(argv[0]) && !is_null(argv[0])) {
413
            hres = to_object(ctx, argv[0], &this_obj);
414 415 416 417
            if(FAILED(hres))
                return hres;
        }

418
        cnt = argc-1;
419 420
    }

421
    hres = function->vtbl->call(ctx, function, this_obj, flags, cnt, argv + 1, r);
422 423 424 425

    if(this_obj)
        IDispatch_Release(this_obj);
    return hres;
426 427
}

428 429 430
static HRESULT Function_bind(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
        jsval_t *r)
{
431
    IDispatch *bound_this = NULL;
432 433 434 435 436 437 438
    FunctionInstance *function;
    jsdisp_t *new_function;
    HRESULT hres;

    TRACE("\n");

    if(!(function = function_this(jsthis)))
439
        return JS_E_FUNCTION_EXPECTED;
440 441 442 443 444 445

    if(argc < 1) {
        FIXME("no this argument\n");
        return E_NOTIMPL;
    }

446 447 448
    if(is_object_instance(argv[0])) {
        bound_this = get_object(argv[0]);
    }else if(!is_null(argv[0])) {
449 450 451 452
        FIXME("%s is not an object instance\n", debugstr_jsval(argv[0]));
        return E_NOTIMPL;
    }

453
    hres = create_bind_function(ctx, function, bound_this, argc - 1, argv + 1, &new_function);
454 455 456 457 458 459 460 461 462 463
    if(FAILED(hres))
        return hres;

    if(r)
        *r = jsval_obj(new_function);
    else
        jsdisp_release(new_function);
    return S_OK;
}

464
HRESULT Function_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
465
        jsval_t *r)
466
{
467 468 469 470
    FunctionInstance *function;

    TRACE("\n");

471
    if(!is_vclass(jsthis, JSCLASS_FUNCTION)) {
472 473 474 475
        ERR("dispex is not a function\n");
        return E_FAIL;
    }

476
    function = function_from_jsdisp(jsthis->u.jsdisp);
477
    return function->vtbl->call(ctx, function, NULL, flags, argc, argv, r);
478
}
479

480
HRESULT Function_get_value(script_ctx_t *ctx, jsdisp_t *jsthis, jsval_t *r)
481
{
482
    FunctionInstance *function = function_from_jsdisp(jsthis);
483 484
    jsstr_t *str;
    HRESULT hres;
485

486
    TRACE("\n");
487

488
    hres = function->vtbl->toString(function, &str);
489 490
    if(FAILED(hres))
        return hres;
491

492
    *r = jsval_string(str);
493
    return S_OK;
494 495
}

496
static HRESULT Function_get_arguments(script_ctx_t *ctx, jsdisp_t *jsthis, jsval_t *r)
497
{
498
    FunctionInstance *function = function_from_jsdisp(jsthis);
499
    call_frame_t *frame;
500
    HRESULT hres;
501 502 503

    TRACE("\n");

504 505
    for(frame = ctx->call_ctx; frame; frame = frame->prev_frame) {
        if(frame->function_instance == &function->dispex) {
506 507 508 509 510
            if(!frame->arguments_obj) {
                hres = setup_arguments_object(ctx, frame);
                if(FAILED(hres))
                    return hres;
            }
511 512 513 514 515 516
            *r = jsval_obj(jsdisp_addref(frame->arguments_obj));
            return S_OK;
        }
    }

    *r = jsval_null();
517
    return S_OK;
518 519
}

520 521 522 523 524 525 526 527 528 529
function_code_t *Function_get_code(jsdisp_t *jsthis)
{
    FunctionInstance *function;

    assert(is_class(jsthis, JSCLASS_FUNCTION));
    function = function_from_jsdisp(jsthis);

    return function->vtbl->get_code(function);
}

530
static void Function_destructor(jsdisp_t *dispex)
531
{
532 533 534
    FunctionInstance *function = function_from_jsdisp(dispex);
    function->vtbl->destructor(function);
    heap_free(function);
535 536 537
}

static const builtin_prop_t Function_props[] = {
538 539 540 541 542 543
    {L"apply",               Function_apply,                 PROPF_METHOD|2},
    {L"arguments",           NULL, 0,                        Function_get_arguments},
    {L"bind",                Function_bind,                  PROPF_METHOD|PROPF_ES5|1},
    {L"call",                Function_call,                  PROPF_METHOD|1},
    {L"length",              NULL, 0,                        Function_get_length},
    {L"toString",            Function_toString,              PROPF_METHOD}
544 545 546 547
};

static const builtin_info_t Function_info = {
    JSCLASS_FUNCTION,
548
    Function_value,
549
    ARRAY_SIZE(Function_props),
550 551 552 553 554
    Function_props,
    Function_destructor,
    NULL
};

555
static const builtin_prop_t FunctionInst_props[] = {
556 557
    {L"arguments",           NULL, 0,                        Function_get_arguments},
    {L"length",              NULL, 0,                        Function_get_length}
558 559 560 561
};

static const builtin_info_t FunctionInst_info = {
    JSCLASS_FUNCTION,
562
    Function_value,
563
    ARRAY_SIZE(FunctionInst_props),
564 565 566 567 568
    FunctionInst_props,
    Function_destructor,
    NULL
};

569 570
static HRESULT create_function(script_ctx_t *ctx, const builtin_info_t *builtin_info, const function_vtbl_t *vtbl, size_t size,
        DWORD flags, BOOL funcprot, jsdisp_t *prototype, void **ret)
571 572 573 574
{
    FunctionInstance *function;
    HRESULT hres;

575
    function = heap_alloc_zero(size);
576 577 578
    if(!function)
        return E_OUTOFMEMORY;

579
    if(funcprot)
580
        hres = init_dispex(&function->dispex, ctx, builtin_info, prototype);
581 582
    else if(builtin_info)
        hres = init_dispex_from_constr(&function->dispex, ctx, builtin_info, ctx->function_constr);
583
    else
584
        hres = init_dispex_from_constr(&function->dispex, ctx, &FunctionInst_info, ctx->function_constr);
585 586
    if(FAILED(hres)) {
        heap_free(function);
587
        return hres;
588
    }
589

590
    function->vtbl = vtbl;
591 592 593
    function->flags = flags;
    function->length = flags & PROPF_ARGMASK;

594 595 596
    *ret = function;
    return S_OK;
}
597

598
static HRESULT NativeFunction_call(script_ctx_t *ctx, FunctionInstance *func, IDispatch *this_disp, unsigned flags,
599 600
        unsigned argc, jsval_t *argv, jsval_t *r)
{
601
    NativeFunction *function = (NativeFunction*)func;
602 603 604 605 606 607
    vdisp_t vthis;
    HRESULT hres;

    if(this_disp)
        set_disp(&vthis, this_disp);
    else
608
        set_disp(&vthis, lookup_global_host(ctx));
609

610
    hres = function->proc(ctx, &vthis, flags & ~DISPATCH_JSCRIPT_INTERNAL_MASK, argc, argv, r);
611 612 613 614 615

    vdisp_release(&vthis);
    return hres;
}

616
static HRESULT NativeFunction_toString(FunctionInstance *func, jsstr_t **ret)
617
{
618
    NativeFunction *function = (NativeFunction*)func;
619 620 621 622
    DWORD name_len;
    jsstr_t *str;
    WCHAR *ptr;

623 624
    static const WCHAR native_prefixW[] = L"\nfunction ";
    static const WCHAR native_suffixW[] = L"() {\n    [native code]\n}\n";
625 626

    name_len = function->name ? lstrlenW(function->name) : 0;
627
    str = jsstr_alloc_buf(ARRAY_SIZE(native_prefixW) + ARRAY_SIZE(native_suffixW) + name_len - 2, &ptr);
628 629 630 631
    if(!str)
        return E_OUTOFMEMORY;

    memcpy(ptr, native_prefixW, sizeof(native_prefixW));
632
    ptr += ARRAY_SIZE(native_prefixW) - 1;
633 634 635 636 637 638 639 640
    memcpy(ptr, function->name, name_len*sizeof(WCHAR));
    ptr += name_len;
    memcpy(ptr, native_suffixW, sizeof(native_suffixW));

    *ret = str;
    return S_OK;
}

641 642 643 644 645
static function_code_t *NativeFunction_get_code(FunctionInstance *function)
{
    return NULL;
}

646 647 648 649
static void NativeFunction_destructor(FunctionInstance *function)
{
}

650
static const function_vtbl_t NativeFunctionVtbl = {
651
    NativeFunction_call,
652
    NativeFunction_toString,
653
    NativeFunction_get_code,
654
    NativeFunction_destructor
655 656
};

657
HRESULT create_builtin_function(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
658
        const builtin_info_t *builtin_info, DWORD flags, jsdisp_t *prototype, jsdisp_t **ret)
659
{
660
    NativeFunction *function;
661 662
    HRESULT hres;

663
    hres = create_function(ctx, builtin_info, &NativeFunctionVtbl, sizeof(NativeFunction), flags, FALSE, NULL, (void**)&function);
664 665 666
    if(FAILED(hres))
        return hres;

667
    if(builtin_info)
668
        hres = jsdisp_define_data_property(&function->function.dispex, L"length", 0,
669
                                           jsval_number(function->function.length));
670
    if(SUCCEEDED(hres))
671
        hres = jsdisp_define_data_property(&function->function.dispex, L"prototype", 0, jsval_obj(prototype));
672
    if(FAILED(hres)) {
673
        jsdisp_release(&function->function.dispex);
674 675 676
        return hres;
    }

677
    function->proc = value_proc;
678
    function->name = name;
679

680
    *ret = &function->function.dispex;
681 682
    return S_OK;
}
683

684 685
static HRESULT set_constructor_prop(script_ctx_t *ctx, jsdisp_t *constr, jsdisp_t *prot)
{
686
    return jsdisp_define_data_property(prot, L"constructor", PROPF_WRITABLE | PROPF_CONFIGURABLE,
687
                                       jsval_obj(constr));
688 689
}

690 691 692 693 694 695 696 697 698 699
HRESULT create_builtin_constructor(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
        const builtin_info_t *builtin_info, DWORD flags, jsdisp_t *prototype, jsdisp_t **ret)
{
    jsdisp_t *constr;
    HRESULT hres;

    hres = create_builtin_function(ctx, value_proc, name, builtin_info, flags, prototype, &constr);
    if(FAILED(hres))
        return hres;

700
    hres = set_constructor_prop(ctx, constr, prototype);
701 702 703 704 705 706 707 708 709
    if(FAILED(hres)) {
        jsdisp_release(constr);
        return hres;
    }

    *ret = constr;
    return S_OK;
}

710
static HRESULT InterpretedFunction_call(script_ctx_t *ctx, FunctionInstance *func, IDispatch *this_obj, unsigned flags,
711 712
         unsigned argc, jsval_t *argv, jsval_t *r)
{
713
    InterpretedFunction *function = (InterpretedFunction*)func;
714
    jsdisp_t *new_obj = NULL;
715 716 717 718 719 720 721 722 723 724 725
    DWORD exec_flags = 0;
    HRESULT hres;

    TRACE("%p\n", function);

    if(ctx->state == SCRIPTSTATE_UNINITIALIZED || ctx->state == SCRIPTSTATE_CLOSED) {
        WARN("Script engine state does not allow running code.\n");
        return E_UNEXPECTED;
    }

    if(flags & DISPATCH_CONSTRUCT) {
726
        hres = create_object(ctx, &function->function.dispex, &new_obj);
727 728 729 730 731 732 733 734 735
        if(FAILED(hres))
            return hres;
        this_obj = to_disp(new_obj);
    }

    if(flags & DISPATCH_JSCRIPT_CALLEREXECSSOURCE)
        exec_flags |= EXEC_RETURN_TO_INTERP;
    if(flags & DISPATCH_CONSTRUCT)
        exec_flags |= EXEC_CONSTRUCTOR;
736 737
    hres = exec_source(ctx, exec_flags, function->code, function->func_code, function->scope_chain, this_obj,
                       &function->function.dispex, argc, argv, r);
738 739 740 741 742
    if(new_obj)
        jsdisp_release(new_obj);
    return hres;
}

743
static HRESULT InterpretedFunction_toString(FunctionInstance *func, jsstr_t **ret)
744
{
745 746
    InterpretedFunction *function = (InterpretedFunction*)func;

747 748 749 750
    *ret = jsstr_alloc_len(function->func_code->source, function->func_code->source_len);
    return *ret ? S_OK : E_OUTOFMEMORY;
}

751 752 753 754 755 756 757
static function_code_t *InterpretedFunction_get_code(FunctionInstance *func)
{
    InterpretedFunction *function = (InterpretedFunction*)func;

    return function->func_code;
}

758
static void InterpretedFunction_destructor(FunctionInstance *func)
759
{
760 761
    InterpretedFunction *function = (InterpretedFunction*)func;

762 763 764 765 766
    release_bytecode(function->code);
    if(function->scope_chain)
        scope_release(function->scope_chain);
}

767
static const function_vtbl_t InterpretedFunctionVtbl = {
768
    InterpretedFunction_call,
769
    InterpretedFunction_toString,
770
    InterpretedFunction_get_code,
771
    InterpretedFunction_destructor
772 773
};

774
HRESULT create_source_function(script_ctx_t *ctx, bytecode_t *code, function_code_t *func_code,
775
        scope_chain_t *scope_chain, jsdisp_t **ret)
776
{
777
    InterpretedFunction *function;
778
    jsdisp_t *prototype;
779 780
    HRESULT hres;

781
    hres = create_object(ctx, NULL, &prototype);
782 783 784
    if(FAILED(hres))
        return hres;

785
    hres = create_function(ctx, NULL, &InterpretedFunctionVtbl, sizeof(InterpretedFunction), PROPF_CONSTR,
786
                           FALSE, NULL, (void**)&function);
787
    if(SUCCEEDED(hres)) {
788
        hres = jsdisp_define_data_property(&function->function.dispex, L"prototype", PROPF_WRITABLE,
789
                                           jsval_obj(prototype));
790
        if(SUCCEEDED(hres))
791
            hres = set_constructor_prop(ctx, &function->function.dispex, prototype);
792
        if(FAILED(hres))
793
            jsdisp_release(&function->function.dispex);
794
    }
795
    jsdisp_release(prototype);
796 797 798 799 800 801 802 803
    if(FAILED(hres))
        return hres;

    if(scope_chain) {
        scope_addref(scope_chain);
        function->scope_chain = scope_chain;
    }

804 805
    bytecode_addref(code);
    function->code = code;
806
    function->func_code = func_code;
807
    function->function.length = function->func_code->param_cnt;
808

809
    *ret = &function->function.dispex;
810 811
    return S_OK;
}
812

813 814 815 816 817 818 819 820 821 822 823 824
static HRESULT BindFunction_call(script_ctx_t *ctx, FunctionInstance *func, IDispatch *this_obj, unsigned flags,
         unsigned argc, jsval_t *argv, jsval_t *r)
{
    BindFunction *function = (BindFunction*)func;
    jsval_t *call_args = NULL;
    unsigned call_argc;
    HRESULT hres;

    TRACE("%p\n", function);

    call_argc = function->argc + argc;
    if(call_argc) {
825
        call_args = heap_alloc(call_argc * sizeof(*call_args));
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
        if(!call_args)
            return E_OUTOFMEMORY;

        if(function->argc)
            memcpy(call_args, function->args, function->argc * sizeof(*call_args));
        if(argc)
            memcpy(call_args + function->argc, argv, argc * sizeof(*call_args));
    }

    hres = function->target->vtbl->call(ctx, function->target, function->this, flags, call_argc, call_args, r);

    heap_free(call_args);
    return hres;
}

static HRESULT BindFunction_toString(FunctionInstance *function, jsstr_t **ret)
{
843
    *ret = jsstr_alloc(L"\nfunction() {\n    [native code]\n}\n");
844 845 846
    return *ret ? S_OK : E_OUTOFMEMORY;
}

847 848 849 850 851
static function_code_t *BindFunction_get_code(FunctionInstance *function)
{
    return NULL;
}

852 853 854 855 856 857 858 859 860 861
static void BindFunction_destructor(FunctionInstance *func)
{
    BindFunction *function = (BindFunction*)func;
    unsigned i;

    TRACE("%p\n", function);

    for(i = 0; i < function->argc; i++)
        jsval_release(function->args[i]);
    jsdisp_release(&function->target->dispex);
862 863
    if(function->this)
        IDispatch_Release(function->this);
864 865 866 867 868
}

static const function_vtbl_t BindFunctionVtbl = {
    BindFunction_call,
    BindFunction_toString,
869
    BindFunction_get_code,
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    BindFunction_destructor
};

static HRESULT create_bind_function(script_ctx_t *ctx, FunctionInstance *target, IDispatch *bound_this, unsigned argc,
                                    jsval_t *argv, jsdisp_t **ret)
{
    BindFunction *function;
    HRESULT hres;

    hres = create_function(ctx, NULL, &BindFunctionVtbl, FIELD_OFFSET(BindFunction, args[argc]), PROPF_METHOD,
                           FALSE, NULL, (void**)&function);
    if(FAILED(hres))
        return hres;

    jsdisp_addref(&target->dispex);
    function->target = target;

887 888
    if(bound_this)
        IDispatch_AddRef(function->this = bound_this);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903

    for(function->argc = 0; function->argc < argc; function->argc++) {
        hres = jsval_copy(argv[function->argc], function->args + function->argc);
        if(FAILED(hres)) {
            jsdisp_release(&function->function.dispex);
            return hres;
        }
    }

    function->function.length = target->length > argc ? target->length - argc : 0;

    *ret = &function->function.dispex;
    return S_OK;
}

904
static HRESULT construct_function(script_ctx_t *ctx, unsigned argc, jsval_t *argv, IDispatch **ret)
905 906
{
    WCHAR *str = NULL, *ptr;
907
    unsigned len = 0, i = 0;
908
    bytecode_t *code;
909
    jsdisp_t *function;
910
    jsstr_t **params = NULL;
911
    int j = 0;
912 913
    HRESULT hres = S_OK;

914 915
    static const WCHAR function_anonymousW[] = L"function anonymous(";
    static const WCHAR function_beginW[] = L") {\n";
916
    static const WCHAR function_endW[] = L"\n}";
917 918

    if(argc) {
919
        params = heap_alloc(argc*sizeof(*params));
920 921 922 923 924 925
        if(!params)
            return E_OUTOFMEMORY;

        if(argc > 2)
            len = (argc-2)*2; /* separating commas */
        for(i=0; i < argc; i++) {
926
            hres = to_string(ctx, argv[i], params+i);
927 928
            if(FAILED(hres))
                break;
929
            len += jsstr_length(params[i]);
930 931 932 933
        }
    }

    if(SUCCEEDED(hres)) {
934
        len += ARRAY_SIZE(function_anonymousW) + ARRAY_SIZE(function_beginW) + ARRAY_SIZE(function_endW) - 2;
935 936 937
        str = heap_alloc(len*sizeof(WCHAR));
        if(str) {
            memcpy(str, function_anonymousW, sizeof(function_anonymousW));
938
            ptr = str + ARRAY_SIZE(function_anonymousW) - 1;
939 940
            if(argc > 1) {
                while(1) {
941
                    ptr += jsstr_flush(params[j], ptr);
942 943 944 945 946 947 948
                    if(++j == argc-1)
                        break;
                    *ptr++ = ',';
                    *ptr++ = ' ';
                }
            }
            memcpy(ptr, function_beginW, sizeof(function_beginW));
949
            ptr += ARRAY_SIZE(function_beginW) - 1;
950 951
            if(argc)
                ptr += jsstr_flush(params[argc-1], ptr);
952 953 954 955 956 957 958 959
            memcpy(ptr, function_endW, sizeof(function_endW));

            TRACE("%s\n", debugstr_w(str));
        }else {
            hres = E_OUTOFMEMORY;
        }
    }

960 961
    while(i)
        jsstr_release(params[--i]);
962 963 964 965
    heap_free(params);
    if(FAILED(hres))
        return hres;

966 967
    hres = compile_script(ctx, str, 0, 0, NULL, NULL, FALSE, FALSE,
                          ctx->call_ctx ? ctx->call_ctx->bytecode->named_item : NULL, &code);
968 969 970 971
    heap_free(str);
    if(FAILED(hres))
        return hres;

972
    if(code->global_code.func_cnt != 1 || code->global_code.var_cnt != 1) {
973
        ERR("Invalid parser result!\n");
974
        release_bytecode(code);
975 976 977
        return E_UNEXPECTED;
    }

978
    hres = create_source_function(ctx, code, code->global_code.funcs, NULL, &function);
979
    release_bytecode(code);
980 981 982
    if(FAILED(hres))
        return hres;

983
    *ret = to_disp(function);
984 985 986
    return S_OK;
}

987
static HRESULT FunctionConstr_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
988
        jsval_t *r)
989
{
990 991 992 993 994
    HRESULT hres;

    TRACE("\n");

    switch(flags) {
995
    case DISPATCH_METHOD:
996 997 998
    case DISPATCH_CONSTRUCT: {
        IDispatch *ret;

999
        hres = construct_function(ctx, argc, argv, &ret);
1000 1001 1002
        if(FAILED(hres))
            return hres;

1003
        *r = jsval_disp(ret);
1004 1005 1006 1007 1008 1009 1010 1011
        break;
    }
    default:
        FIXME("unimplemented flags %x\n", flags);
        return E_NOTIMPL;
    }

    return S_OK;
1012 1013
}

1014
static HRESULT FunctionProt_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
1015
        jsval_t *r)
1016 1017 1018 1019 1020
{
    FIXME("\n");
    return E_NOTIMPL;
}

1021
HRESULT init_function_constr(script_ctx_t *ctx, jsdisp_t *object_prototype)
1022
{
1023
    NativeFunction *prot, *constr;
1024 1025
    HRESULT hres;

1026 1027
    hres = create_function(ctx, &Function_info, &NativeFunctionVtbl, sizeof(NativeFunction), PROPF_CONSTR,
                           TRUE, object_prototype, (void**)&prot);
1028 1029 1030
    if(FAILED(hres))
        return hres;

1031
    prot->proc = FunctionProt_value;
1032
    prot->name = L"prototype";
1033

1034 1035
    hres = create_function(ctx, &FunctionInst_info, &NativeFunctionVtbl, sizeof(NativeFunction), PROPF_CONSTR|1,
                           TRUE, &prot->function.dispex, (void**)&constr);
1036
    if(SUCCEEDED(hres)) {
1037
        constr->proc = FunctionConstr_value;
1038 1039
        constr->name = L"Function";
        hres = jsdisp_define_data_property(&constr->function.dispex, L"prototype", 0, jsval_obj(&prot->function.dispex));
1040
        if(SUCCEEDED(hres))
1041
            hres = set_constructor_prop(ctx, &constr->function.dispex, &prot->function.dispex);
1042
        if(FAILED(hres))
1043
            jsdisp_release(&constr->function.dispex);
1044
    }
1045
    jsdisp_release(&prot->function.dispex);
1046 1047 1048
    if(FAILED(hres))
        return hres;

1049
    ctx->function_constr = &constr->function.dispex;
1050
    return S_OK;
1051
}