All files constant-folding.js

95.76% Statements 113/118
93.9% Branches 77/82
100% Functions 7/7
95.65% Lines 110/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269  1x 1x 1x 1x 1x   1x   1x                         23x 23x   334x 16x   318x 23x   295x 10x       23x 23x 23x   3x   20x   19x   1x 1x 1x               23x                     16x 16x 16x 16x 16x                     10x   10x 4x 4x 2x     2x       6x 6x 3x     3x     6x 3x     10x 10x 10x 10x                       23x 14x 14x 8x 8x 2x 2x     6x   8x 4x   8x     6x 6x 6x 4x 4x     2x   6x 6x 26x 26x 22x   4x 4x   26x   6x       9x 9x 9x 6x 6x     3x     9x 6x   9x 3x 3x 9x 9x 6x     3x   9x   23x 23x                     34x 34x 80x 28x   52x 48x 17x     31x     4x 4x           34x                     20x 20x 265x 221x 39x   182x 182x 24x       20x                                                    
// See https://github.com/babel/minify/tree/master/packages/babel-plugin-minify-constant-folding
const fs = require("fs");
const deb = require('../src/deb.js');
const escodegen = require("escodegen");
const espree = require("espree");
const estraverse = require("estraverse");
 
"use strict";
 
module.exports = constantFolding;
 
 
/**
 * A function that creates the AST of the given code and modifies it for
 * allowing the use of array and strings methods.
 *
 * @param      {string}  code     A string with the js program code.
 * @param      {string}  pattern  The pattern (other parameters).
 * @return     {string}  Returns a string with the output in AST format or JS
 *                       format.
 */
function constantFolding(code, pattern) {
	const t = espree.parse(code, { ecmaVersion: 6, loc: false });
	estraverse.traverse(t, {
		leave: function (n, p) {
			if (n.type == "BinaryExpression" && n.left.type == "Literal" && n.right.type == "Literal") { 
				replaceByLiteral(n); 
			}
			else if (n.type == "CallExpression") {
				replaceByCallExpression(n);
			}
			else if (n.type == "MemberExpression" && p.type != "CallExpression") {
				replaceByMemberExpression(n);
			}	
		},
	});
	let result = "";
	let c = escodegen.generate(t);
	if (pattern == "--ast" || pattern == "-a") {
		//result = 'AST Json code: \n\n';
		result += JSON.stringify(t, 0, 2);
	}
	else if (pattern == "--js" || pattern == "-j") {
		//result = '\n\n---\n\n JavaScript code:\n\n';
		result += generateOutput(c);
	}
	else Eif (pattern == "--deb" || pattern == "-d") {
		result += generateOutput(c);
		deb(t);
	}
	else {
		result = 'AST Json code: \n\n';
		result += JSON.stringify(t, 0, 2);
		result += '\n\n---\n\n JavaScript code:\n\n';
		result += generateOutput(c);
	}
	return result;
}
 
 
/**
 * Modifies the literal node for computing the operations and apply constant
 * folding.
 *
 * @param      {<type>}  node    The node.
 */
function replaceByLiteral(node) {
	node.type = "Literal";
	node.value = eval(`${node.left.raw} ${node.operator} ${node.right.raw}`);
	node.raw = String(node.value);
	delete node.left;
	delete node.right;
}
 
 
/**
 * Modifies the member expression node for allowing use for array and strings
 * methods.
 *
 * @param      {Node}  node    The node.
 */
function replaceByMemberExpression(node) {
	node.type = "Literal";
	// Array methods
	if (node.object.type == "ArrayExpression") {
		var arr = generateArray(node.object.elements);
		if (node.property.type == "Literal") {
			node.value = eval(`[${arr}][${node.property.value}]`);
		}
		else {
			node.value = eval(`[${arr}].${node.property.name}`);
		}
	}
	// String and number methods
	else Eif (node.object.type == "Literal") {
		if (node.property.type == "Literal") {
			node.value = eval(`"${node.object.value}"[${node.property.value}]`);
		}
		else {
			node.value = eval(`"${node.object.value}".${node.property.name}`);
		}
		// Add quotes to strings
		if (typeof(node.value) != "number") {
			node.value = "\"" + node.value + "\"";
		}
	}
	node.raw = String(node.value);
	node.computed = true;
	delete node.object;
	delete node.property;
}
 
 
/**
 * Modifies the call expression node for allowing use for array and strings
 * methods.
 *
 * @param      {Node}  node    The node.
 */
function replaceByCallExpression(node) {
	// Array methods
	if (node.callee.object.type == "ArrayExpression") {
		var arr = generateArray(node.callee.object.elements);
		if (node.callee.property.name == "join" || node.callee.property.name == "shift" || node.callee.property.name == "pop") {
			node.type = "Literal";
			if (node.arguments.length > 0) {
				var args = generateArray(node.arguments);
				node.value = eval(`[${arr}].${node.callee.property.name}(${args})`);
			}
			else {
				node.value = eval(`[${arr}].${node.callee.property.name}()`);
			}
			if (node.callee.property.name === "join") {
				node.value = "\"" + node.value + "\"";
			}
			node.raw = String(node.value);	
		}
		else {
			node.type = "ArrayExpression";
			var result = "";
			if (node.arguments.length > 0) {
				var args = generateArray(node.arguments)
				result = eval(`[${arr}].${node.callee.property.name}(${args})`);
			}
			else {
				result = eval(`[${arr}].${node.callee.property.name}()`);
			}
			var tmp = new Array();
			for (var i = 0; i < result.length; i++) {
				var newNode =  Object.assign({} , node.callee.object.elements[0]);
				if (newNode.hasOwnProperty("name")) {
					newNode.name = result[i];
				}
				else Eif (newNode.hasOwnProperty("value")) {
					newNode.value = result[i];
				}
				tmp.push(newNode);
			}
			node.elements =  tmp;
		}
	}
	// String and number methods
	else Eif (node.callee.object.type == "Literal") {
		node.type = "Literal";
		if (node.arguments.length > 0) {
			var args = generateArray(node.arguments);
			node.value = eval(`"${node.callee.object.value}".${node.callee.property.name}(${args})`);
		}
		else {
			node.value = eval(`"${node.callee.object.value}".${node.callee.property.name}()`);
		}
		// Add quotes in string methods
		if (typeof(node.value) !== "number" && node.callee.property.name !== 'split') {
			node.value = "\"" + node.value + "\"";
		}
		if (typeof(node.value) !== "number" && node.callee.property.name === 'split') {
			let addQuotes = "";
			for (let i = 0; i < node.value.length; i++) {
				addQuotes += "\"" + node.value[i] + "\""
				if (i < node.value.length - 1) {
					addQuotes += ", ";
				}
			}
			node.value = addQuotes;
		}
		node.raw = String(node.value);
	}
	delete node.callee;
	delete node.arguments;
}
 
 
/**
 * Receives a node and generates an array from the elements of that node.
 *
 * @param      {Node}   node    The node.
 * @return     {Array}  Array with the elements of the node.
 */
function generateArray (node) {
	var arr = new Array();
	for (var i in node) {
		if (node[i].type === "Identifier") {
			arr.push(`"${node[i].name}"`);
		}
		else if (node[i].type === "Literal") {
			if (typeof(node[i].value) === "string") {
				arr.push(`"${node[i].value}"`);
			}
			else {
				arr.push(`${node[i].value}`);
			}
		}
		else Eif (node[i].type === "ArrayExpression") {
			arr.push(generateArray(node[i].elements));
		}
		else {
			console.log("Error, not valid expresion in generateArray");
		}
	}
	return arr;
}
 
 
/**
 * Modifies the JS output for printing it in one line and without many spaces.
 *
 * @param      {string}  code    The code
 * @return     {string}  The output with better format.
 */
function generateOutput(code) {
	let result = "";
	for (let i = 0; i < code.length; i++) {
		if (code[i] !== '\n' && code[i] !== '\'') {
			if (code[i] === ' ' && code[i - 1] === ' ') {
				continue;
			}
			result += code[i];
			if (code[i] === ';') {
				result += '\n';
			}
		}
	}
	return result;
}
 
// const input = `
// var f = 3+null;
// var e = 4 | 3;
// var d = 3+"c";
// var b = 9 +1;
// var a = 2+3*5+b;
// [a, b, c].concat([d, e], f, g, [h]);
// ["a", "b", "c"].join();
// ["a", "b", "c"].join('@');
// [1, 2, 3].length;
// [1, 2, 3][2-1];
// [1, 2, 3].shift();
// [1, 2, 3].slice(0, 1+1);
// [a, b, c].pop();
// [a, b, c].reverse();
// "abc"[0];
// "abc".charAt();
// "abc".charAt(1);
// "abc".length;
// "a,b,c".split(",");
// (100 + 23).toString();
// `;
 
// console.log(constantFolding(input, "--js"));