ast-eval
v0.4.2 static-eval ecmascript esprima ast es-trim estrim espurify ast-eval static and 6 more...
ast-eval
Statically evaluate expressions in AST, also known as constants folding. Useful for precompilation tasks.
Use
npm install --save ast-eval
var esprima = require('esprima');
var gen = require('escodegen').generate;
var astEval = require('ast-eval');
var ast = esprima.parse('[1, 2 === "2", 3+4*10, [2] === 2]');
ast = astEval(ast);
gen(ast); //'[1, false, 43, false]'
API
preeval(Node, options) → Node
Evaluate expressions in a Node, return a new Node with optimized shorten expression nodes.
Features
Fold expressions
- Binary expressions:
1000 * 60 * 60
→36e6
- Logical expressions:
{a:1} && {b:2}
→true
- Math expressions:
Math.sin(Math.Pi / 2 )
→1
- Binary expressions:
Fold arrays
- Safe methods:
[1,2,3,new Date].concat(4, [5], new Date)
→[1,2,3,new Date,4,5, new Date]
- Unsafe methods:
[1,2,3].map(function(x){ return x*2})
→[2,4,6]
- Static methods:
Array.from([1, 2, 3], function(x){ return x*2; })
→[2,4,6]
- Prototype methods:
Array.prototype.slice.call([1,2,3], 1,2)
→[2]
- Safe methods:
Fold static globals (what’s that?)
Decompute object access (optionally)
-
a['x'] = 1
→a.x = 1
-
Fold strings
-
'a b c'.split(' ')
→['a', 'b', 'c']
-
-
- Simple flow analysis:
var x = 1; x + 2;
→3;
- Scope analysis
- Method substitution:
var slice = Array.prototype.slice; var x = [1,2,3]; var y = slice(x)'
- Simple flow analysis:
Fold loops
-
var x = []; for (var i = 0; i < 10; i++) {x[i] = 10*i;}
-
Fold proxy functions
Remove unused props
Undead code
- Empty isolated functions
- Remove unused variables (after enabling constants)
- Remove unused functions
- Remove unused properties
Fold clone-code
a.x
×3 →var _a = a; _a.x
Data-flow analysis
- Precall functions
- Substitute variables
Provide exports
Fold primitives
- new Array([1,2,3,...])
- [1,2,3,...]
Rearrange things
- Hoist functions (place after first use)
- Fold variable declarations
References
- List of compiler optimizations — ideas of folding.
- Substack’s static-eval — evaluate static expressions.
- esmangle
npm i [email protected]
Metadata
- Unlicensed
- Whatever
- Deema Ywanov
- released 2/13/2015