Evaluate JavaScript abstract syntax tree in ESTree format
npm install estrevalEvaluate JavaScript abstract syntax tree in ESTree format
This is a sandboxed runtime to evaluate JavaScript expressions.
Here is an example page to interact with it.
#### Language
The interpreter supports a reasonable subset of ES5, the 5th Edition of the ECMAScript language specification (PDF). In addition, some modern syntax is supported:
- Array function expression
- Block scope, let and const
- Class
- JSX - No React or renderer yet
- Spread and rest expression
Notably missing are Promise and async/await, because there is no event loop.
The main function parses and evaluates an expression.
``js
const estreval = require('estreval')
estreval('1 + 2 * 3') // 7
`
The expression can be given as string, or an object in ESTree format.
The second argument is a context object (optional). It defines the global context of variables to which the code will have access.
`js
const context = { x: 3 }
estreval('y => x * y', context)(5) // 15
`
The third argument is an options object (optional).
`js`
estreval(code, context, options)
It can have the following properties.
- timeout - Maximum amount of time (in milliseconds) allowed for the code - Default: 100maxSteps
- - Maximum number of steps allowed for the code - Default: 1024
The default parser uses Acorn.
It can be imported by itself.
`js
const parse = require('estreval/parse')
const tree = parse('y => x * y') // ESTree format
`
To use a custom parser, first import the evaluate function separately.
The following example uses Esprima.
`js
const evaluate = require('estreval/evaluate')
const { parseScript: parse } = require('esprima')
const tree = parse('y => x * y')
const context = { x: 3 }
const options = { parse }
evaluate(tree, context, options)(5) // 15
`
The parse function can be passed as the parse option. It will be used when new instances of Function are created inside the runtime. Otherwise, the use of Function will throw an error.
#### Babel parser
To use the Babel parser, specify its built-in plugin estree to convert the syntax tree to ESTree format.
`js
const { parse } = require('@babel/parser')
const tree = parse(code, {
plugins: ['estree']
})
`
This is necessary because Babel uses its own AST format, with some differences from the ESTree specification.
Start a read-eval-print loop to interact with the runtime in the terminal.
``
node repl
The following functions are provided for convenience.
- print( any ) - Show value using inspect and console.logparse( string )
- - Parse given string and print abstract syntax tree
#### Reload
Enter .reload in the REPL to reload the library after editing its files.
Build unminified for development, watch files for changes, and start server for test page
``
npm run dev
Build minified for production
```
npm run build
- eval5
- estime
- notevil and its forks
- evaljs
- closure-interpreter
- esper.js
- sandboxr
- JS-Interpreter
- narcissus