Skip to content

Commit 82813f2

Browse files
isaacsry
authored andcommitted
Execute repl code in new context
1 parent 3c7873b commit 82813f2

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

lib/repl.js

+25-14
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,25 @@
1313
// repl.start("node > ").scope.foo = "stdin is fun"; // expose foo to repl scope
1414

1515
var sys = require('sys');
16+
var evalcx = process.binding('evals').Script.runInNewContext;
17+
var path = require("path");
18+
var scope;
19+
20+
function setScope (self) {
21+
scope = {};
22+
for (var i in global) scope[i] = global[i];
23+
scope.module = module;
24+
scope.require = require;
25+
}
26+
1627

1728
// Can overridden with custom print functions, such as `probe` or `eyes.js`
1829
exports.writer = sys.inspect;
1930

2031
function REPLServer(prompt, stream) {
2132
var self = this;
22-
23-
self.scope = {};
33+
if (!scope) setScope();
34+
self.scope = scope;
2435
self.buffered_cmd = '';
2536
self.prompt = prompt || "node> ";
2637
self.stream = stream || process.openStdin();
@@ -61,20 +72,20 @@ REPLServer.prototype.readline = function (cmd) {
6172
// This try is for determining if the command is complete, or should
6273
// continue onto the next line.
6374
try {
64-
self.buffered_cmd = self.convertToScope(self.buffered_cmd);
65-
66-
// Scope the readline with self.scope to provide "local" vars and make Douglas Crockford cry
67-
with (self.scope) {
68-
var ret = eval(self.buffered_cmd);
69-
if (ret !== undefined) {
70-
self.scope['_'] = ret;
71-
self.stream.write(exports.writer(ret) + "\n");
72-
}
75+
// Scope the readline with self.scope
76+
// with(){} and eval() are considered bad.
77+
var ret = evalcx(self.buffered_cmd, scope, "repl");
78+
if (ret !== undefined) {
79+
scope._ = ret;
80+
self.stream.write(exports.writer(ret) + "\n");
7381
}
74-
82+
7583
self.buffered_cmd = '';
7684
} catch (e) {
77-
if (!(e instanceof SyntaxError)) throw e;
85+
// instanceof doesn't work across context switches.
86+
if (!(e && e.constructor && e.constructor.name === "SyntaxError")) {
87+
throw e;
88+
}
7889
}
7990
} catch (e) {
8091
// On error: Print the error and clear the buffer
@@ -107,7 +118,7 @@ REPLServer.prototype.parseREPLKeyword = function (cmd) {
107118
case ".clear":
108119
self.stream.write("Clearing Scope...\n");
109120
self.buffered_cmd = '';
110-
self.scope = {};
121+
setScope();
111122
self.displayPrompt();
112123
return true;
113124
case ".exit":

0 commit comments

Comments
 (0)