ast-eval
v0.8.0
Published
Statically evaluate AST
Downloads
33
Maintainers
Readme
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
[x] 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
- [x] Binary expressions:
[x] 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 x*2; })
→[2,4,6]
- [ ] Prototype methods:
Array.prototype.slice.call([1,2,3], 1,2)
→[2]
- [x] Safe methods:
[ ] Fold static globals (what’s that?)
[x] Decompute object access (optionally)
- [x]
a['x'] = 1
→a.x = 1
- [x]
[x] Fold strings
- [x]
'a b c'.split(' ')
→['a', 'b', 'c']
- [x]
- [ ] 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