Pass an environment to eval()?

# Axel Rauschmayer (12 years ago)

Has this feature ever been considered?

For example:

$ var env = { __proto__: window, foo: 1 };
$ eval('var bar = foo+1', env);
$ env.bar
2

Useful for writing interpreters and more convenient for interacting with evaluated code than improvising something equivalent via Function.

Axel

# Brendan Eich (12 years ago)

Axel Rauschmayer <mailto:axel at rauschma.de> September 28, 2013 2:49 PM Has this feature ever been considered?

Lots of times, going back at least as far as

discussion:resurrected_eval

Read under "Resolved issues".

SpiderMonkey had a two-argument eval for ages, from before the modern era. We removed it. No one should be messing with the signature of eval at this point.

Module loader API supersedes all such ideas in ES6.

# Mark S. Miller (12 years ago)

On Sat, Sep 28, 2013 at 2:49 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

Has this feature ever been considered?

For example:

$ var env = { __proto__: window, foo: 1 };
$ eval('var bar = foo+1', env);
$ env.bar
2

See the "confine" function at < code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses/startSES.js#855>,

also documented in section 2.3 of < research.google.com/pubs/pub40673.html>.

# Mark S. Miller (12 years ago)

Actually, for this, confine isn't quite what you want, since you're providing the entire extensible virtual global. (The confine function's second argument is just the additions to the default powerless virtual global.) You want compileExpr from code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses/startSES.js#783 or the similar compileModule. To avoid the need for even mild translation, I rephrased your example to assign to the bar property of the pseudo-top-level "this".

> var env = {foo: 1};
undefined

> cajaVM.compileExpr('this.bar = foo+1')(env);
2

> env.bar
2

With mild translation (see the rewriteTopLevelVars mitigation option), you could use compileModule instead and have your original source string appear as you wrote it. Such mitigation unfortunately requires a full parser, and so is only available when SES is bundled with code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses/mitigateGotchas.js. Caja does bundle these together.

ES6 module loaders will make much of this mechanism unnecessary, while still enabling us to continue to support old SES code that uses the current API.