Browse Source

Initial implementation of process.evalcx

v0.7.4-release
Tim-Smart 15 years ago
committed by Ryan Dahl
parent
commit
ae10a48383
  1. 48
      src/node.cc
  2. 27
      test/simple/test-eval-cx.js

48
src/node.cc

@ -846,6 +846,53 @@ Handle<Value> DLOpen(const v8::Arguments& args) {
return Undefined(); return Undefined();
} }
// evalcx(code, sandbox={})
// Executes code in a new context
Handle<Value> EvalCX(const Arguments& args) {
HandleScope scope;
Local<String> code = args[0]->ToString();
Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
: Object::New();
// Create the new context
Persistent<Context> context = Context::New();
// Copy objects from global context, to our brand new context
Handle<Array> keys = sandbox->GetPropertyNames();
int i;
for (i = 0; i < keys->Length(); i++) {
Handle<String> key = keys->Get(Integer::New(i))->ToString();
Handle<Value> value = sandbox->Get(key);
context->Global()->Set(key, value->ToObject()->Clone());
}
// Enter and compile script
context->Enter();
// Catch errors
TryCatch try_catch;
Local<Script> script = Script::Compile(code, String::New("evalcx"));
Handle<Value> result;
if (script.IsEmpty()) {
result = ThrowException(try_catch.Exception());
} else {
result = script->Run();
if (result.IsEmpty()) {
result = ThrowException(try_catch.Exception());
}
}
// Clean up, clean up, everybody everywhere!
context->DetachGlobal();
context->Exit();
context.Dispose();
return scope.Close(result);
}
Handle<Value> Compile(const Arguments& args) { Handle<Value> Compile(const Arguments& args) {
HandleScope scope; HandleScope scope;
@ -1051,6 +1098,7 @@ static void Load(int argc, char *argv[]) {
// define various internal methods // define various internal methods
NODE_SET_METHOD(process, "loop", Loop); NODE_SET_METHOD(process, "loop", Loop);
NODE_SET_METHOD(process, "unloop", Unloop); NODE_SET_METHOD(process, "unloop", Unloop);
NODE_SET_METHOD(process, "evalcx", EvalCX);
NODE_SET_METHOD(process, "compile", Compile); NODE_SET_METHOD(process, "compile", Compile);
NODE_SET_METHOD(process, "_byteLength", ByteLength); NODE_SET_METHOD(process, "_byteLength", ByteLength);
NODE_SET_METHOD(process, "reallyExit", Exit); NODE_SET_METHOD(process, "reallyExit", Exit);

27
test/simple/test-eval-cx.js

@ -0,0 +1,27 @@
require("../common");
debug('evalcx a string');
var result = process.evalcx('"passed";');
assert.equal('passed', result);
debug('evalcx a thrown error');
assert.throws(function() {
process.evalcx('throw new Error("test");');
});
hello = 5;
process.evalcx('hello = 2');
assert.equal(5, hello);
code = "foo = 1; bar = 2;";
foo = 2;
obj = { foo : 0 };
process.evalcx(code, obj);
/* TODO?
assert.equal(1, obj.foo);
assert.equal(2, obj.bar);
*/
assert.equal(2, foo);
Loading…
Cancel
Save