vm_evaluate.js (2333B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var minstd = require( '@stdlib/random/base/minstd-shuffle' ); 24 var createContext = require( './context.js' ); 25 var asyncSource = require( './async.js' ); 26 var syncSource = require( './sync.js' ); 27 var compile = require( './vm_compile.js' ); 28 29 30 // MAIN // 31 32 /** 33 * Evaluates source code within a V8 virtual machine context. 34 * 35 * @private 36 * @param {string} src - source code 37 * @param {Object} opts - options 38 * @param {string} filename - filename 39 * @param {string} dirname - directory name 40 * @param {Callback} clbk - callback to invoke upon completion 41 * @returns {void} 42 */ 43 function evaluate( src, opts, filename, dirname, clbk ) { 44 var context; 45 var tmp; 46 var fcn; 47 var err; 48 var id; 49 50 // Create an id: 51 id = minstd(); 52 53 // Create an execution context: 54 context = createContext( done ); 55 56 // Generate the source code to evaluate... 57 if ( opts.asynchronous ) { 58 src = asyncSource( id, src, opts ); 59 } else { 60 src = syncSource( id, src, opts ); 61 } 62 // Compile the source code: 63 fcn = compile( filename, src ); 64 65 // Execute the source code: 66 tmp = fcn.call( context, require, filename, dirname ); 67 68 // Check that the snippet did not prematurely return... 69 if ( tmp !== id ) { 70 err = new Error( 'evaluation error. Unable to retrieve evaluation results. Ensure that the provided snippet does not return prematurely.' ); 71 return done( err ); 72 } 73 /** 74 * Callback invoked upon executing source code. 75 * 76 * @private 77 * @param {(Error|null)} error - error object 78 * @param {NonNegativeIntegerArray} results - results 79 * @returns {void} 80 */ 81 function done( error, results ) { 82 if ( error ) { 83 return clbk( error ); 84 } 85 return clbk( null, results ); 86 } 87 } 88 89 90 // EXPORTS // 91 92 module.exports = evaluate;