ast-eval

0.8.0 • Public • Published

ast-eval Build Status experimental

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 * 6036e6
    • Logical expressions: {a:1} && {b:2}true
    • Math expressions: Math.sin(Math.Pi / 2 )1
  • 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]
  • Fold static globals (what’s that?)

  • Decompute object access (optionally)

    • a['x'] = 1a.x = 1
  • Fold strings

    • '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++) {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

NPM

Dependents (2)

Package Sidebar

Install

npm i ast-eval

Weekly Downloads

6

Version

0.8.0

License

Unlicensed

Last publish

Collaborators

  • dfcreative