Mercurial > spidermonkey-playground
diff spidermonkey-playground.cpp @ 6:500e267ed094
Added a really simple securableModule require() implementation.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Fri, 19 Jun 2009 09:33:13 -0700 |
parents | 1f38f4f61768 |
children | e14f496e6e08 |
line wrap: on
line diff
--- a/spidermonkey-playground.cpp Fri Jun 19 03:49:44 2009 -0700 +++ b/spidermonkey-playground.cpp Fri Jun 19 09:33:13 2009 -0700 @@ -4,7 +4,7 @@ #include "wrapper.h" -#define MAX_SCRIPT_SIZE 50000 +#define MAX_SCRIPT_SIZE 100000 #define TCB_FILENAME "tcb.js" /* The class of the global object. */ @@ -55,6 +55,48 @@ return JS_TRUE; } +static JSBool require(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, + jsval *rval) +{ + char *filename; + JSObject *exports; + + if (!JS_ConvertArguments(cx, argc, argv, "so", &filename, &exports)) + return JS_FALSE; + + FILE *f = fopen(filename, "r"); + if (!f) { + JS_ReportError(cx, "File not found"); + return JS_FALSE; + } + + char source[MAX_SCRIPT_SIZE]; + fread(source, MAX_SCRIPT_SIZE, 1, f); + fclose(f); + + JSContext *module_cx = JS_NewContext(JS_GetRuntime(cx), 8192); + JSObject *module_global = JS_NewObject(module_cx, &global_class, NULL, NULL); + JS_InitStandardClasses(module_cx, module_global); + JS_DefineProperty(module_cx, module_global, "imports", + OBJECT_TO_JSVAL(exports), NULL, NULL, 0); + JSObject *module_exports = JS_NewObject(module_cx, NULL, NULL, module_global); + JS_DefineProperty(module_cx, module_global, "exports", + OBJECT_TO_JSVAL(module_exports), NULL, NULL, 0); + + jsval module_rval; + if (!JS_EvaluateScript(module_cx, module_global, source, + strlen(source), filename, 1, &module_rval)) { + JS_DestroyContext(module_cx); + return JS_FALSE; + } + + *rval = OBJECT_TO_JSVAL(module_exports); + + JS_DestroyContext(module_cx); + + return JS_TRUE; +} + static JSBool stack(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { @@ -155,6 +197,7 @@ JS_FS("print", print, 1, 0, 0), JS_FS("wrap", wrap, 2, 0, 0), JS_FS("stack", stack, 0, 0, 0), + JS_FS("require", require, 2, 0, 0), JS_FS_END };