Implement Function.prototype.toString()

This commit is contained in:
Tor Andersson
2014-01-19 14:24:21 +01:00
parent 48e3fdb718
commit 3da05690f1
2 changed files with 37 additions and 3 deletions
+36 -2
View File
@@ -1,4 +1,5 @@
#include "js.h"
#include "jscompile.h"
#include "jsobject.h"
#include "jsrun.h"
#include "jsstate.h"
@@ -12,6 +13,39 @@ static int jsB_Function_prototype(js_State *J, int n)
return 1;
}
static int Fp_toString(js_State *J, int nargs)
{
js_Object *self = js_toobject(J, 0);
char *s;
int i, n;
if (!js_iscallable(J, 0))
jsR_error(J, "TypeError");
if (self->type == JS_CFUNCTION || self->type == JS_CSCRIPT) {
js_Function *F = self->u.f.function;
n = strlen("function () { ... }");
n += strlen(F->name);
for (i = 0; i < F->numparams; i++)
n += strlen(F->params[i]) + 1;
s = malloc(n);
strcpy(s, "function ");
strcat(s, F->name);
strcat(s, "(");
for (i = 0; i < F->numparams; i++) {
if (i > 0) strcat(s, ",");
strcat(s, F->params[i]);
}
strcat(s, ") { ... }");
js_pushstring(J, s);
free(s);
} else {
js_pushliteral(J, "function () { ... }");
}
return 1;
}
static int Fp_apply(js_State *J, int n)
{
int i, argc;
@@ -72,8 +106,8 @@ void jsB_initfunction(js_State *J)
{
js_copy(J, -2);
js_setproperty(J, -2, "constructor");
// jsB_propf(J, "toString", Fp_toString, 2);
// jsB_propf(J, "apply", Fp_apply, 2);
jsB_propf(J, "toString", Fp_toString, 2);
jsB_propf(J, "apply", Fp_apply, 2);
jsB_propf(J, "call", Fp_call, 1);
}
js_setproperty(J, -2, "prototype");
+1 -1
View File
@@ -724,7 +724,7 @@ static void cfunbody(JF, js_Ast *name, js_Ast *params, js_Ast *body)
emitfunction(J, F, F);
emitstring(J, F, OP_FUNDEC, name->string);
} else {
F->name = "<anonymous>";
F->name = "";
}
cparams(J, F, params);