pegjs/lib/util/vm.js

59 lines
1.1 KiB
JavaScript
Raw Normal View History

2018-02-02 07:42:03 +01:00
"use strict";
2018-04-05 09:16:50 +02:00
const code = ( () => {
2018-02-02 07:42:03 +01:00
2018-04-05 09:16:50 +02:00
let preface = "";
const MODULE_VARS = {
2018-02-02 07:42:03 +01:00
2018-04-05 09:16:50 +02:00
"module": true,
"process": true,
"code": true,
"runInContext": true,
"source": true,
"preface": true,
};
Object.keys( MODULE_VARS ).forEach( name => {
preface += `var ${ name } = void 0;`;
2018-04-05 09:16:50 +02:00
} );
2018-04-05 09:16:50 +02:00
function generate( name ) {
2018-04-05 09:16:50 +02:00
return `${ ( MODULE_VARS[ name ] ? "" : "var " ) + name } = __context.${ name };`;
2018-04-05 09:16:50 +02:00
}
return { generate, preface };
} )();
module.exports = {
2018-02-02 07:42:03 +01:00
2018-04-05 09:16:50 +02:00
// `eval` the given source, using properties found in `context` as top-level
// variables, while hiding some variables in this module from the source.
//
// Based on `vm.runInContext` found in Node.js, this is a cross-env solution.
2018-04-05 09:16:50 +02:00
runInContext( source, __context ) {
let preface = code.preface;
if ( typeof __context === "object" ) {
2018-04-05 09:16:50 +02:00
Object.keys( __context ).forEach( name => {
2018-04-05 09:16:50 +02:00
preface += code.generate( name );
2018-04-05 09:16:50 +02:00
} );
}
2018-04-05 09:16:50 +02:00
return eval( preface + source );
2018-02-02 07:42:03 +01:00
},
};