ast-eval v0.8.0
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 x Binary expressions: `1000 60 60
→
36e6` x Logical expressions:{a:1} && {b:2}
→true
* x Math expressions:Math.sin(Math.Pi / 2 )
→1
Fold arrays x Safe methods:
[1,2,3,new Date].concat(4, [5], new Date)
→[1,2,3,new Date,4,5, new Date]
x Unsafe methods:[1,2,3].map(function(x){ return x*2})
→[2,4,6]
Static methods: `Array.from(1, 2, 3, function(x){ return x2; })→
2,4,6* [ ] Prototype methods:
Array.prototype.slice.call(1,2,3, 1,2)→
2`Fold static globals (what’s that?)
Decompute object access (optionally) * x
a['x'] = 1
→a.x = 1
Fold strings * x
'a b c'.split(' ')
→['a', 'b', 'c']
Propagate constants 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)'
Fold loops `var x = []; for (var i = 0; i < 10; i++) {xi = 10i;}`
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
Provide exports
Fold primitives new Array(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