Release 1.5.29.
[wine] / dlls / jscript / function.c
1 /*
2  * Copyright 2008 Jacek Caban for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include <assert.h>
20
21 #include "jscript.h"
22 #include "engine.h"
23
24 #include "wine/debug.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(jscript);
27
28 typedef struct {
29     jsdisp_t dispex;
30     builtin_invoke_t value_proc;
31     const WCHAR *name;
32     DWORD flags;
33     scope_chain_t *scope_chain;
34     bytecode_t *code;
35     function_code_t *func_code;
36     DWORD length;
37     jsdisp_t *arguments;
38 } FunctionInstance;
39
40 typedef struct {
41     jsdisp_t jsdisp;
42     FunctionInstance *function;
43     jsdisp_t *var_obj;
44 } ArgumentsInstance;
45
46 static inline FunctionInstance *function_from_vdisp(vdisp_t *vdisp)
47 {
48     return (FunctionInstance*)vdisp->u.jsdisp;
49 }
50
51 static inline FunctionInstance *function_this(vdisp_t *jsthis)
52 {
53     return is_vclass(jsthis, JSCLASS_FUNCTION) ? function_from_vdisp(jsthis) : NULL;
54 }
55
56 static const WCHAR prototypeW[] = {'p','r','o','t','o','t', 'y', 'p','e',0};
57
58 static const WCHAR lengthW[] = {'l','e','n','g','t','h',0};
59 static const WCHAR toStringW[] = {'t','o','S','t','r','i','n','g',0};
60 static const WCHAR applyW[] = {'a','p','p','l','y',0};
61 static const WCHAR callW[] = {'c','a','l','l',0};
62 static const WCHAR argumentsW[] = {'a','r','g','u','m','e','n','t','s',0};
63
64 static HRESULT init_parameters(jsdisp_t *var_disp, FunctionInstance *function, unsigned argc, jsval_t *argv)
65 {
66     DWORD i=0;
67     HRESULT hres;
68
69     for(i=0; i < function->func_code->param_cnt; i++) {
70         hres = jsdisp_propput_name(var_disp, function->func_code->params[i],
71                 i < argc ? argv[i] : jsval_undefined());
72         if(FAILED(hres))
73             return hres;
74     }
75
76     return S_OK;
77 }
78
79 static HRESULT Arguments_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
80         jsval_t *r)
81 {
82     FIXME("\n");
83     return E_NOTIMPL;
84 }
85
86 static void Arguments_destructor(jsdisp_t *jsdisp)
87 {
88     ArgumentsInstance *arguments = (ArgumentsInstance*)jsdisp;
89
90     jsdisp_release(&arguments->function->dispex);
91     jsdisp_release(arguments->var_obj);
92     heap_free(arguments);
93 }
94
95 static unsigned Arguments_idx_length(jsdisp_t *jsdisp)
96 {
97     ArgumentsInstance *arguments = (ArgumentsInstance*)jsdisp;
98     return arguments->function->length;
99 }
100
101 static HRESULT Arguments_idx_get(jsdisp_t *jsdisp, unsigned idx, jsval_t *res)
102 {
103     ArgumentsInstance *arguments = (ArgumentsInstance*)jsdisp;
104
105     TRACE("%p[%u]\n", arguments, idx);
106
107     /* FIXME: Accessing by name won't work for duplicated argument names */
108     return jsdisp_propget_name(arguments->var_obj, arguments->function->func_code->params[idx], res);
109 }
110
111 static HRESULT Arguments_idx_put(jsdisp_t *jsdisp, unsigned idx, jsval_t val)
112 {
113     ArgumentsInstance *arguments = (ArgumentsInstance*)jsdisp;
114
115     TRACE("%p[%u] = %s\n", arguments, idx, debugstr_jsval(val));
116
117     /* FIXME: Accessing by name won't work for duplicated argument names */
118     return jsdisp_propput_name(arguments->var_obj, arguments->function->func_code->params[idx], val);
119 }
120
121 static const builtin_info_t Arguments_info = {
122     JSCLASS_ARGUMENTS,
123     {NULL, Arguments_value, 0},
124     0, NULL,
125     Arguments_destructor,
126     NULL,
127     Arguments_idx_length,
128     Arguments_idx_get,
129     Arguments_idx_put
130 };
131
132 static HRESULT create_arguments(script_ctx_t *ctx, FunctionInstance *calee, jsdisp_t *var_obj,
133         unsigned argc, jsval_t *argv, jsdisp_t **ret)
134 {
135     ArgumentsInstance *args;
136     unsigned i;
137     HRESULT hres;
138
139     static const WCHAR caleeW[] = {'c','a','l','l','e','e',0};
140
141     args = heap_alloc_zero(sizeof(*args));
142     if(!args)
143         return E_OUTOFMEMORY;
144
145     hres = init_dispex_from_constr(&args->jsdisp, ctx, &Arguments_info, ctx->object_constr);
146     if(FAILED(hres)) {
147         heap_free(args);
148         return hres;
149     }
150
151     jsdisp_addref(&calee->dispex);
152     args->function = calee;
153     args->var_obj = jsdisp_addref(var_obj);
154
155     /* Store unnamed arguments directly in arguments object */
156     for(i = calee->length; i < argc; i++) {
157         WCHAR buf[12];
158
159         static const WCHAR formatW[] = {'%','d',0};
160
161         sprintfW(buf, formatW, i);
162         hres = jsdisp_propput_dontenum(&args->jsdisp, buf, argv[i]);
163         if(FAILED(hres))
164             break;
165     }
166
167     if(SUCCEEDED(hres)) {
168         hres = jsdisp_propput_dontenum(&args->jsdisp, lengthW, jsval_number(argc));
169         if(SUCCEEDED(hres))
170             hres = jsdisp_propput_dontenum(&args->jsdisp, caleeW, jsval_disp(to_disp(&calee->dispex)));
171     }
172     if(FAILED(hres)) {
173         jsdisp_release(&args->jsdisp);
174         return hres;
175     }
176
177     *ret = &args->jsdisp;
178     return S_OK;
179 }
180
181 static HRESULT create_var_disp(script_ctx_t *ctx, FunctionInstance *function, unsigned argc, jsval_t *argv, jsdisp_t **ret)
182 {
183     jsdisp_t *var_disp;
184     HRESULT hres;
185
186     hres = create_dispex(ctx, NULL, NULL, &var_disp);
187     if(FAILED(hres))
188         return hres;
189
190     hres = init_parameters(var_disp, function, argc, argv);
191     if(FAILED(hres)) {
192         jsdisp_release(var_disp);
193         return hres;
194     }
195
196     *ret = var_disp;
197     return S_OK;
198 }
199
200 static HRESULT invoke_source(script_ctx_t *ctx, FunctionInstance *function, IDispatch *this_obj, unsigned argc, jsval_t *argv,
201         jsval_t *r)
202 {
203     jsdisp_t *var_disp, *arg_disp;
204     exec_ctx_t *exec_ctx;
205     scope_chain_t *scope;
206     HRESULT hres;
207
208     if(!function->func_code) {
209         FIXME("no source\n");
210         return E_FAIL;
211     }
212
213     hres = create_var_disp(ctx, function, argc, argv, &var_disp);
214     if(FAILED(hres))
215         return hres;
216
217     hres = create_arguments(ctx, function, var_disp, argc, argv, &arg_disp);
218     if(FAILED(hres)) {
219         jsdisp_release(var_disp);
220         return hres;
221     }
222
223     hres = jsdisp_propput(var_disp, argumentsW, PROPF_DONTDELETE, jsval_obj(arg_disp));
224     if(FAILED(hres)) {
225         jsdisp_release(arg_disp);
226         jsdisp_release(var_disp);
227         return hres;
228     }
229
230     hres = scope_push(function->scope_chain, var_disp, to_disp(var_disp), &scope);
231     if(SUCCEEDED(hres)) {
232         hres = create_exec_ctx(ctx, this_obj, var_disp, scope, FALSE, &exec_ctx);
233         scope_release(scope);
234
235         if(SUCCEEDED(hres)) {
236             jsdisp_t *prev_args;
237
238             prev_args = function->arguments;
239             function->arguments = arg_disp;
240             hres = exec_source(exec_ctx, function->code, function->func_code, FALSE, r);
241             function->arguments = prev_args;
242
243             exec_release(exec_ctx);
244         }
245     }
246
247     /* Reset arguments value to cut the reference cycle. Note that since all activation contexts have
248      * their own arguments property, it's impossible to use prototype's one during name lookup */
249     jsdisp_propput_name(var_disp, argumentsW, jsval_undefined());
250
251     jsdisp_release(arg_disp);
252     jsdisp_release(var_disp);
253     return hres;
254 }
255
256 static HRESULT invoke_constructor(script_ctx_t *ctx, FunctionInstance *function, unsigned argc, jsval_t *argv,
257         jsval_t *r)
258 {
259     jsdisp_t *this_obj;
260     jsval_t var;
261     HRESULT hres;
262
263     hres = create_object(ctx, &function->dispex, &this_obj);
264     if(FAILED(hres))
265         return hres;
266
267     hres = invoke_source(ctx, function, to_disp(this_obj), argc, argv, &var);
268     if(FAILED(hres)) {
269         jsdisp_release(this_obj);
270         return hres;
271     }
272
273     if(is_object_instance(var)) {
274         jsdisp_release(this_obj);
275         *r = var;
276     }else {
277         jsval_release(var);
278         *r = jsval_obj(this_obj);
279     }
280     return S_OK;
281 }
282
283 static HRESULT invoke_value_proc(script_ctx_t *ctx, FunctionInstance *function, IDispatch *this_disp, WORD flags,
284         unsigned argc, jsval_t *argv, jsval_t *r)
285 {
286     vdisp_t vthis;
287     HRESULT hres;
288
289     if(this_disp)
290         set_disp(&vthis, this_disp);
291     else if(ctx->host_global)
292         set_disp(&vthis, ctx->host_global);
293     else
294         set_jsdisp(&vthis, ctx->global);
295
296     hres = function->value_proc(ctx, &vthis, flags, argc, argv, r);
297
298     vdisp_release(&vthis);
299     return hres;
300 }
301
302 static HRESULT call_function(script_ctx_t *ctx, FunctionInstance *function, IDispatch *this_obj,
303         unsigned argc, jsval_t *argv, jsval_t *r)
304 {
305     if(function->value_proc)
306         return invoke_value_proc(ctx, function, this_obj, DISPATCH_METHOD, argc, argv, r);
307
308     return invoke_source(ctx, function, this_obj, argc, argv, r);
309 }
310
311 static HRESULT function_to_string(FunctionInstance *function, jsstr_t **ret)
312 {
313     jsstr_t *str;
314
315     static const WCHAR native_prefixW[] = {'\n','f','u','n','c','t','i','o','n',' '};
316     static const WCHAR native_suffixW[] =
317         {'(',')',' ','{','\n',' ',' ',' ',' ','[','n','a','t','i','v','e',' ','c','o','d','e',']','\n','}','\n'};
318
319     if(function->value_proc) {
320         DWORD name_len;
321         WCHAR *ptr;
322
323         name_len = strlenW(function->name);
324         ptr = jsstr_alloc_buf((sizeof(native_prefixW)+sizeof(native_suffixW))/sizeof(WCHAR) + name_len, &str);
325         if(!ptr)
326             return E_OUTOFMEMORY;
327
328         memcpy(ptr, native_prefixW, sizeof(native_prefixW));
329         memcpy(ptr += sizeof(native_prefixW)/sizeof(WCHAR), function->name, name_len*sizeof(WCHAR));
330         memcpy(ptr + name_len, native_suffixW, sizeof(native_suffixW));
331     }else {
332         str = jsstr_alloc_len(function->func_code->source, function->func_code->source_len);
333         if(!str)
334             return E_OUTOFMEMORY;
335     }
336
337     *ret = str;
338     return S_OK;
339 }
340
341 HRESULT Function_invoke(jsdisp_t *func_this, IDispatch *jsthis, WORD flags, unsigned argc, jsval_t *argv, jsval_t *r)
342 {
343     FunctionInstance *function;
344
345     TRACE("func %p this %p\n", func_this, jsthis);
346
347     assert(is_class(func_this, JSCLASS_FUNCTION));
348     function = (FunctionInstance*)func_this;
349
350     if(function->value_proc)
351         return invoke_value_proc(function->dispex.ctx, function, jsthis, flags, argc, argv, r);
352
353     if(flags == DISPATCH_CONSTRUCT)
354         return invoke_constructor(function->dispex.ctx, function, argc, argv, r);
355
356     assert(flags == DISPATCH_METHOD);
357     return invoke_source(function->dispex.ctx, function, jsthis, argc, argv, r);
358 }
359
360 static HRESULT Function_length(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
361         jsval_t *r)
362 {
363     FunctionInstance *This = function_from_vdisp(jsthis);
364
365     TRACE("%p %d\n", This, This->length);
366
367     switch(flags) {
368     case DISPATCH_PROPERTYGET:
369         *r = jsval_number(This->length);
370         break;
371     default:
372         FIXME("unimplemented flags %x\n", flags);
373         return E_NOTIMPL;
374     }
375
376     return S_OK;
377 }
378
379 static HRESULT Function_toString(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
380         jsval_t *r)
381 {
382     FunctionInstance *function;
383     jsstr_t *str;
384     HRESULT hres;
385
386     TRACE("\n");
387
388     if(!(function = function_this(jsthis)))
389         return throw_type_error(ctx, JS_E_FUNCTION_EXPECTED, NULL);
390
391     hres = function_to_string(function, &str);
392     if(FAILED(hres))
393         return hres;
394
395     if(r)
396         *r = jsval_string(str);
397     else
398         jsstr_release(str);
399     return S_OK;
400 }
401
402 static HRESULT array_to_args(script_ctx_t *ctx, jsdisp_t *arg_array, unsigned *argc, jsval_t **ret)
403 {
404     jsval_t *argv, val;
405     DWORD length, i;
406     HRESULT hres;
407
408     hres = jsdisp_propget_name(arg_array, lengthW, &val);
409     if(FAILED(hres))
410         return hres;
411
412     hres = to_uint32(ctx, val, &length);
413     jsval_release(val);
414     if(FAILED(hres))
415         return hres;
416
417     argv = heap_alloc(length * sizeof(*argv));
418     if(!argv)
419         return E_OUTOFMEMORY;
420
421     for(i=0; i<length; i++) {
422         hres = jsdisp_get_idx(arg_array, i, argv+i);
423         if(hres == DISP_E_UNKNOWNNAME) {
424             argv[i] = jsval_undefined();
425         }else if(FAILED(hres)) {
426             while(i--)
427                 jsval_release(argv[i]);
428             heap_free(argv);
429             return hres;
430         }
431     }
432
433     *argc = length;
434     *ret = argv;
435     return S_OK;
436 }
437
438 static HRESULT Function_apply(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv, jsval_t *r)
439 {
440     FunctionInstance *function;
441     jsval_t *args = NULL;
442     unsigned i, cnt = 0;
443     IDispatch *this_obj = NULL;
444     HRESULT hres = S_OK;
445
446     TRACE("\n");
447
448     if(!(function = function_this(jsthis)))
449         return throw_type_error(ctx, JS_E_FUNCTION_EXPECTED, NULL);
450
451     if(argc) {
452         if(!is_undefined(argv[0]) && !is_null(argv[0])) {
453             hres = to_object(ctx, argv[0], &this_obj);
454             if(FAILED(hres))
455                 return hres;
456         }
457     }
458
459     if(argc >= 2) {
460         jsdisp_t *arg_array = NULL;
461
462         if(is_object_instance(argv[1])) {
463             arg_array = iface_to_jsdisp((IUnknown*)get_object(argv[1]));
464             if(arg_array &&
465                (!is_class(arg_array, JSCLASS_ARRAY) && !is_class(arg_array, JSCLASS_ARGUMENTS) )) {
466                 jsdisp_release(arg_array);
467                 arg_array = NULL;
468             }
469         }
470
471         if(arg_array) {
472             hres = array_to_args(ctx, arg_array, &cnt, &args);
473             jsdisp_release(arg_array);
474         }else {
475             FIXME("throw TypeError\n");
476             hres = E_FAIL;
477         }
478     }
479
480     if(SUCCEEDED(hres))
481         hres = call_function(ctx, function, this_obj, cnt, args, r);
482
483     if(this_obj)
484         IDispatch_Release(this_obj);
485     for(i=0; i < cnt; i++)
486         jsval_release(args[i]);
487     heap_free(args);
488     return hres;
489 }
490
491 static HRESULT Function_call(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
492         jsval_t *r)
493 {
494     FunctionInstance *function;
495     IDispatch *this_obj = NULL;
496     unsigned cnt = 0;
497     HRESULT hres;
498
499     TRACE("\n");
500
501     if(!(function = function_this(jsthis)))
502         return throw_type_error(ctx, JS_E_FUNCTION_EXPECTED, NULL);
503
504     if(argc) {
505         if(!is_undefined(argv[0]) && !is_null(argv[0])) {
506             hres = to_object(ctx, argv[0], &this_obj);
507             if(FAILED(hres))
508                 return hres;
509         }
510
511         cnt = argc-1;
512     }
513
514     hres = call_function(ctx, function, this_obj, cnt, argv+1, r);
515
516     if(this_obj)
517         IDispatch_Release(this_obj);
518     return hres;
519 }
520
521 HRESULT Function_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
522         jsval_t *r)
523 {
524     FunctionInstance *function;
525
526     TRACE("\n");
527
528     if(!is_vclass(jsthis, JSCLASS_FUNCTION)) {
529         ERR("dispex is not a function\n");
530         return E_FAIL;
531     }
532
533     function = (FunctionInstance*)jsthis->u.jsdisp;
534
535     switch(flags) {
536     case DISPATCH_METHOD:
537         assert(function->value_proc != NULL);
538         return invoke_value_proc(ctx, function, NULL, flags, argc, argv, r);
539
540     case DISPATCH_PROPERTYGET: {
541         HRESULT hres;
542         jsstr_t *str;
543
544         hres = function_to_string(function, &str);
545         if(FAILED(hres))
546             return hres;
547
548         *r = jsval_string(str);
549         break;
550     }
551
552     case DISPATCH_CONSTRUCT:
553         assert(function->value_proc != NULL);
554         return invoke_value_proc(ctx, function, NULL, flags, argc, argv, r);
555
556     default:
557         FIXME("not implemented flags %x\n", flags);
558         return E_NOTIMPL;
559     }
560
561     return S_OK;
562 }
563
564 static HRESULT Function_arguments(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags,
565         unsigned argc, jsval_t *argv, jsval_t *r)
566 {
567     FunctionInstance *function = (FunctionInstance*)jsthis->u.jsdisp;
568     HRESULT hres = S_OK;
569
570     TRACE("\n");
571
572     switch(flags) {
573     case DISPATCH_PROPERTYGET: {
574         *r = function->arguments ? jsval_obj(jsdisp_addref(function->arguments)) : jsval_null();
575         break;
576     }
577     case DISPATCH_PROPERTYPUT:
578         break;
579     default:
580         FIXME("unimplemented flags %x\n", flags);
581         hres = E_NOTIMPL;
582     }
583
584     return hres;
585 }
586
587 static void Function_destructor(jsdisp_t *dispex)
588 {
589     FunctionInstance *This = (FunctionInstance*)dispex;
590
591     if(This->code)
592         release_bytecode(This->code);
593     if(This->scope_chain)
594         scope_release(This->scope_chain);
595     heap_free(This);
596 }
597
598 static const builtin_prop_t Function_props[] = {
599     {applyW,                 Function_apply,                 PROPF_METHOD|2},
600     {argumentsW,             Function_arguments,             0},
601     {callW,                  Function_call,                  PROPF_METHOD|1},
602     {lengthW,                Function_length,                0},
603     {toStringW,              Function_toString,              PROPF_METHOD}
604 };
605
606 static const builtin_info_t Function_info = {
607     JSCLASS_FUNCTION,
608     {NULL, Function_value, 0},
609     sizeof(Function_props)/sizeof(*Function_props),
610     Function_props,
611     Function_destructor,
612     NULL
613 };
614
615 static const builtin_prop_t FunctionInst_props[] = {
616     {argumentsW,             Function_arguments,             0},
617     {lengthW,                Function_length,                0}
618 };
619
620 static const builtin_info_t FunctionInst_info = {
621     JSCLASS_FUNCTION,
622     {NULL, Function_value, 0},
623     sizeof(FunctionInst_props)/sizeof(*FunctionInst_props),
624     FunctionInst_props,
625     Function_destructor,
626     NULL
627 };
628
629 static HRESULT create_function(script_ctx_t *ctx, const builtin_info_t *builtin_info, DWORD flags,
630         BOOL funcprot, jsdisp_t *prototype, FunctionInstance **ret)
631 {
632     FunctionInstance *function;
633     HRESULT hres;
634
635     function = heap_alloc_zero(sizeof(FunctionInstance));
636     if(!function)
637         return E_OUTOFMEMORY;
638
639     if(funcprot)
640         hres = init_dispex(&function->dispex, ctx, builtin_info, prototype);
641     else if(builtin_info)
642         hres = init_dispex_from_constr(&function->dispex, ctx, builtin_info, ctx->function_constr);
643     else
644         hres = init_dispex_from_constr(&function->dispex, ctx, &FunctionInst_info, ctx->function_constr);
645     if(FAILED(hres)) {
646         heap_free(function);
647         return hres;
648     }
649
650     function->flags = flags;
651     function->length = flags & PROPF_ARGMASK;
652
653     *ret = function;
654     return S_OK;
655 }
656
657 static inline HRESULT set_prototype(script_ctx_t *ctx, jsdisp_t *dispex, jsdisp_t *prototype)
658 {
659     return jsdisp_propput_dontenum(dispex, prototypeW, jsval_obj(prototype));
660 }
661
662 HRESULT create_builtin_function(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
663         const builtin_info_t *builtin_info, DWORD flags, jsdisp_t *prototype, jsdisp_t **ret)
664 {
665     FunctionInstance *function;
666     HRESULT hres;
667
668     hres = create_function(ctx, builtin_info, flags, FALSE, NULL, &function);
669     if(FAILED(hres))
670         return hres;
671
672     if(builtin_info)
673         hres = jsdisp_propput_const(&function->dispex, lengthW, jsval_number(function->length));
674     if(SUCCEEDED(hres))
675         hres = set_prototype(ctx, &function->dispex, prototype);
676     if(FAILED(hres)) {
677         jsdisp_release(&function->dispex);
678         return hres;
679     }
680
681     function->value_proc = value_proc;
682     function->name = name;
683
684     *ret = &function->dispex;
685     return S_OK;
686 }
687
688 static HRESULT set_constructor_prop(script_ctx_t *ctx, jsdisp_t *constr, jsdisp_t *prot)
689 {
690     static const WCHAR constructorW[] = {'c','o','n','s','t','r','u','c','t','o','r',0};
691
692     return jsdisp_propput_dontenum(prot, constructorW, jsval_obj(constr));
693 }
694
695 HRESULT create_builtin_constructor(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
696         const builtin_info_t *builtin_info, DWORD flags, jsdisp_t *prototype, jsdisp_t **ret)
697 {
698     jsdisp_t *constr;
699     HRESULT hres;
700
701     hres = create_builtin_function(ctx, value_proc, name, builtin_info, flags, prototype, &constr);
702     if(FAILED(hres))
703         return hres;
704
705     hres = set_constructor_prop(ctx, constr, prototype);
706     if(FAILED(hres)) {
707         jsdisp_release(constr);
708         return hres;
709     }
710
711     *ret = constr;
712     return S_OK;
713 }
714
715 HRESULT create_source_function(script_ctx_t *ctx, bytecode_t *code, function_code_t *func_code,
716         scope_chain_t *scope_chain, jsdisp_t **ret)
717 {
718     FunctionInstance *function;
719     jsdisp_t *prototype;
720     HRESULT hres;
721
722     hres = create_object(ctx, NULL, &prototype);
723     if(FAILED(hres))
724         return hres;
725
726     hres = create_function(ctx, NULL, PROPF_CONSTR, FALSE, NULL, &function);
727     if(SUCCEEDED(hres)) {
728         hres = set_prototype(ctx, &function->dispex, prototype);
729         if(SUCCEEDED(hres))
730             hres = set_constructor_prop(ctx, &function->dispex, prototype);
731         if(FAILED(hres))
732             jsdisp_release(&function->dispex);
733     }
734     jsdisp_release(prototype);
735     if(FAILED(hres))
736         return hres;
737
738     if(scope_chain) {
739         scope_addref(scope_chain);
740         function->scope_chain = scope_chain;
741     }
742
743     bytecode_addref(code);
744     function->code = code;
745     function->func_code = func_code;
746     function->length = function->func_code->param_cnt;
747
748     *ret = &function->dispex;
749     return S_OK;
750 }
751
752 static HRESULT construct_function(script_ctx_t *ctx, unsigned argc, jsval_t *argv, IDispatch **ret)
753 {
754     WCHAR *str = NULL, *ptr;
755     unsigned len = 0, i = 0;
756     bytecode_t *code;
757     jsdisp_t *function;
758     jsstr_t **params = NULL;
759     int j = 0;
760     HRESULT hres = S_OK;
761
762     static const WCHAR function_anonymousW[] = {'f','u','n','c','t','i','o','n',' ','a','n','o','n','y','m','o','u','s','('};
763     static const WCHAR function_beginW[] = {')',' ','{','\n'};
764     static const WCHAR function_endW[] = {'\n','}',0};
765
766     if(argc) {
767         params = heap_alloc(argc*sizeof(*params));
768         if(!params)
769             return E_OUTOFMEMORY;
770
771         if(argc > 2)
772             len = (argc-2)*2; /* separating commas */
773         for(i=0; i < argc; i++) {
774             hres = to_string(ctx, argv[i], params+i);
775             if(FAILED(hres))
776                 break;
777             len += jsstr_length(params[i]);
778         }
779     }
780
781     if(SUCCEEDED(hres)) {
782         len += (sizeof(function_anonymousW) + sizeof(function_beginW) + sizeof(function_endW)) / sizeof(WCHAR);
783         str = heap_alloc(len*sizeof(WCHAR));
784         if(str) {
785             memcpy(str, function_anonymousW, sizeof(function_anonymousW));
786             ptr = str + sizeof(function_anonymousW)/sizeof(WCHAR);
787             if(argc > 1) {
788                 while(1) {
789                     ptr += jsstr_flush(params[j], ptr);
790                     if(++j == argc-1)
791                         break;
792                     *ptr++ = ',';
793                     *ptr++ = ' ';
794                 }
795             }
796             memcpy(ptr, function_beginW, sizeof(function_beginW));
797             ptr += sizeof(function_beginW)/sizeof(WCHAR);
798             if(argc)
799                 ptr += jsstr_flush(params[argc-1], ptr);
800             memcpy(ptr, function_endW, sizeof(function_endW));
801
802             TRACE("%s\n", debugstr_w(str));
803         }else {
804             hres = E_OUTOFMEMORY;
805         }
806     }
807
808     while(i)
809         jsstr_release(params[--i]);
810     heap_free(params);
811     if(FAILED(hres))
812         return hres;
813
814     hres = compile_script(ctx, str, NULL, NULL, FALSE, FALSE, &code);
815     heap_free(str);
816     if(FAILED(hres))
817         return hres;
818
819     if(code->global_code.func_cnt != 1 || code->global_code.var_cnt) {
820         ERR("Invalid parser result!\n");
821         release_bytecode(code);
822         return E_UNEXPECTED;
823     }
824
825     hres = create_source_function(ctx, code, code->global_code.funcs, NULL, &function);
826     release_bytecode(code);
827     if(FAILED(hres))
828         return hres;
829
830     *ret = to_disp(function);
831     return S_OK;
832 }
833
834 static HRESULT FunctionConstr_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
835         jsval_t *r)
836 {
837     HRESULT hres;
838
839     TRACE("\n");
840
841     switch(flags) {
842     case DISPATCH_CONSTRUCT: {
843         IDispatch *ret;
844
845         hres = construct_function(ctx, argc, argv, &ret);
846         if(FAILED(hres))
847             return hres;
848
849         *r = jsval_disp(ret);
850         break;
851     }
852     default:
853         FIXME("unimplemented flags %x\n", flags);
854         return E_NOTIMPL;
855     }
856
857     return S_OK;
858 }
859
860 static HRESULT FunctionProt_value(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, unsigned argc, jsval_t *argv,
861         jsval_t *r)
862 {
863     FIXME("\n");
864     return E_NOTIMPL;
865 }
866
867 HRESULT init_function_constr(script_ctx_t *ctx, jsdisp_t *object_prototype)
868 {
869     FunctionInstance *prot, *constr;
870     HRESULT hres;
871
872     static const WCHAR FunctionW[] = {'F','u','n','c','t','i','o','n',0};
873
874     hres = create_function(ctx, &Function_info, PROPF_CONSTR, TRUE, object_prototype, &prot);
875     if(FAILED(hres))
876         return hres;
877
878     prot->value_proc = FunctionProt_value;
879     prot->name = prototypeW;
880
881     hres = create_function(ctx, &FunctionInst_info, PROPF_CONSTR|1, TRUE, &prot->dispex, &constr);
882     if(SUCCEEDED(hres)) {
883         constr->value_proc = FunctionConstr_value;
884         constr->name = FunctionW;
885         hres = set_prototype(ctx, &constr->dispex, &prot->dispex);
886         if(SUCCEEDED(hres))
887             hres = set_constructor_prop(ctx, &constr->dispex, &prot->dispex);
888         if(FAILED(hres))
889             jsdisp_release(&constr->dispex);
890     }
891     jsdisp_release(&prot->dispex);
892     if(FAILED(hres))
893         return hres;
894
895     ctx->function_constr = &constr->dispex;
896     return S_OK;
897 }