@alu0101051420/constant-folding
Version:
49 lines (41 loc) • 1.15 kB
JavaScript
const estraverse = require("estraverse");
;
module.exports = eggConstantFolding;
/**
* A function that does constant folding onto the code it receives
* @param {string} code A string containing the code to do the constant folding on
* @returns {string} Returns the resulting code
*/
function eggConstantFolding(ast) {
const operations = ['+', '-', '/', '*'];
estraverse.traverse(ast, {
leave: function (n) {
if (
n.type === "apply" &&
n.args.length === 2 &&
operations.includes(n.operator.name) &&
n.args[0].type === "value" && n.args[1].type === "value"
) {
binaryConstantFolding(n);
}
},
keys: {
apply: ['operator', 'args'],
property: ['operator', 'args'],
word: [],
value: [],
}
}
);
return ast;
}
/**
* Does ConstantFolding on binaryExpression nodes. I.E. turns 2+3 into 5.
* @param {Object} n an AST node representing a binaryExpression.
*/
function binaryConstantFolding(n) {
n.type = "value";
n.value = eval(`${n.args[0].value} ${n.operator.name} ${n.args[1].value}`);
delete n.args;
delete n.operator;
}