# JS-Interpreter Documentation

JS-Interpreter is a sandboxed JavaScript interpreter written in JavaScript. It allows for execution of arbitrary JavaScript code line by line. Execution is completely isolated from the main JavaScript environment. Multiple instances of the JS-Interpreter allow for multi-threaded concurrent JavaScript without the use of Web Workers.

Play with the JS-Interpreter demo.

Get the source code.

## Usage

Start by including the two JavaScript source files:

        <script src="acorn.js"></script>
        <script src="interpreter.js"></script>

Alternatively, use the compressed bundle (70kb):

        <script src="acorn_interpreter.js"></script>

Next, instantiate an interpreter with the JavaScript code that needs to be parsed:

        var myCode = 'var a=1; for(var i=0;i<4;i++){a*=i;} a;';
        var myInterpreter = new Interpreter(myCode);

Additional JavaScript code may be added at any time (frequently used to interactively call previously defined functions):

        myInterpreter.appendCode('foo();');

To run the code step by step, call the `step` function repeatedly until it returns false:

        function nextStep() {
          if (myInterpreter.step()) {
            window.setTimeout(nextStep, 0);
          }
        }
        nextStep();

Alternatively, if the code is known to be safe from infinite loops, it may be executed to completion by calling the `run` function once:

        myInterpreter.run();

In cases where the code encounters asynchronous API calls (see below), `run` will return true if it is blocked and needs to be reexecuted at a later time.

## External API

Similar to the `eval` function, the result of the last statement executed is available in `myInterpreter.value`:

        var myInterpreter = new Interpreter('6 * 7');
        myInterpreter.run();
        alert(myInterpreter.value);

Additionally, API calls may be added to the interpreter's global scope during creation. Here is the addition of `alert()` and a `url` variable:

        var myCode = 'alert(url);';
        var initFunc = function(interpreter, scope) {
          interpreter.setProperty(scope, 'url', String(location));

          var wrapper = function(text) {
            return alert(text);
          };
          interpreter.setProperty(scope, 'alert',
              interpreter.createNativeFunction(wrapper));
        };
        var myInterpreter = new Interpreter(myCode, initFunc);

Alternatively, API calls may be added to an object:

        var myCode = 'robot.forwards(robot.fast);';
        var initFunc = function(interpreter, scope) {
          // Create 'robot' global object.
          var robot = interpreter.nativeToPseudo({});
          interpreter.setProperty(scope, 'robot', robot);

          // Define 'robot.fast' property.
          interpreter.setProperty(robot, 'fast', 99);

          // Define 'robot.forwards' function.
          var wrapper = function(speed) {
            return realRobot.forwards(speed);
          };
          interpreter.setProperty(robot, 'forwards',
              interpreter.createNativeFunction(wrapper));
        };
        var myInterpreter = new Interpreter(myCode, initFunc);

Only primitives (numbers, strings, booleans, null and undefined) may be passed in and out of the interpreter during execution. Objects and functions are not compatible between native and interpreted code. See the JSON demo for an example of exchanging JSON between the browser and the interpreter.

Asynchronous API functions may wrapped so that they appear to be synchronous to interpreter. For example, a `getXhr(url)` function that returns the contents of an XMLHttpRequest could be defined in `initFunc` like this:

        var wrapper = function(href, callback) {
          var req = new XMLHttpRequest();
          req.open('GET', href, true);
          req.onreadystatechange = function() {
            if (req.readyState == 4 && req.status == 200) {
              callback(req.responseText);
            }
          };
          req.send(null);
        };
        interpreter.setProperty(scope, 'getXhr',
            interpreter.createAsyncFunction(wrapper));

This snippet uses `createAsyncFunction` in the same way that `createNativeFunction` was used earlier. The difference is that the wrapped asynchronous function's return value is ignored. Instead, an extra callback function is passed in when the wrapper is called. When the wrapper is ready to return, it calls the callback function with the value it wishes to return. From the point of view of the code running inside the JS-Interpreter, a function call was made and the result was returned immediately.

For a working example, see the async demo.

## Serialization

A unique feature of the JS-Interpreter is its ability to pause execution, serialize the current state, then resume the execution at that point at a later time. Loops, variables, closures, and all other state is preserved.

Uses of this feature include continuously executing programs that survive a server reboot, loading a stack image that has been computed up to a certain point, forking execution, or rolling back to a stored state.

One drawback is that the serialized format is not human-readable, and it is also not guaranteed that future versions of the JS-Interpreter will be able to parse the serialization from older versions. Another drawback is that serialization reaches beyond the public API, and thus does not work with the compressed bundle (acorn_interpreter.js). Yet another drawback is that the serialization format is rather large; it has a 60 kb overhead due to the standard polyfills.

For a working example, see the serialization demo.

## Threading

JavaScript is single-threaded, but the JS-Interpreter allows one to run multiple threads at the same time. Creating two or more completely independent threads that run separately from each other is trivial: just create two or more instances of the Interpreter, each with its own code, and alternate calling each interpreter's step function. They may communicate indirectly with each other through any external APIs that are provided.

A slightly more complex case is where two or more threads should share the same global scope. To implement this, 1) create one JS-Interpreter, 2) create a separate list of stacks, 3) assign the `.scope` property of the root node of each stack to the interpreter's `.global` property, 4) then assign the desired stack to the interpreter's `stateStack` property before calling `step`.

For a working example, see the thread demo.

## Security

A common use-case of the JS-Interpreter is to sandbox potentially hostile code. The interpreter is secure by default: it does not use blacklists to prevent dangerous actions, instead it creates its own virtual machine with no external APIs except as provided by the developer. To date not one security bug has been reported.

Infinite loops are handled by calling the `step` function a maximum number of times, or by calling `step` indefinitely many times but using a setTimeout between each call to ensure other tasks have a chance to execute.

Memory bombs (e.g. `var x='X'; while(1) x=x+x;`) can be detected by periodically serializing the interpereter into a JSON string, and aborting execution if the string length is too long.

## Regular Expressions

Pathological regular expressions can execute in geometric time. For example `'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac'.match(/^(a+)+b/)` will effectively crash any JavaScript runtime. JS-Interpreter has a variety of methods for safely dealing with regular expressions depending on the platform.

## Limitations

The version of JavaScript implemented by the interpreter has a few differences from that which executes in a browser:

API
  None of the DOM APIs are exposed. That's kind of the point of a sandbox. If you need these, write your own interfaces.
ES6
  More recent additions to JavaScript such as `let` or `Set` aren't implemented. Babel is a good method of transpiling newer versions of JavaScript to ES5.
toString & valueOf
  User-created functions are not called when casting objects to primitives.
Performance
  The interpreter is not particularly efficient. It currently runs about 200 times slower than native JavaScript.

## Node.js

JS-Intepreter can be run server-side using Node.js. For a minimal demo, just run: `node demos/node.js`

## Dependency

The only dependency is Acorn, a beautifully written JavaScript parser by Marijn Haverbeke. It is included in the JS-Interpreter package.

## Compatibility

The limiting factor for browser support is the use of `Object.create(null)` to create hash objects in both Acorn and JS-Interpreter. This results in the following minimum browser requirements:

- Chrome 5
- Firefox 4.0
- IE 9
- Edge (all versions)
- Opera 11.6
- Safari 5
- Node.js (all versions)

Additionally, if safely executing regular expressions is required, then IE 11 is the minimum version of IE that supports Web Workers via Blobs.

## Disclaimer

This project is not an official Google product.