@alu0101051420/constant-folding
Version:
107 lines (82 loc) • 3.12 kB
HTML
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: utils.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: utils.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>const espree = require("espree");
/**
* Creates a new AST node containing the info received
* @param {string} literal to be assigned as value of the node
* @returns {Object} the resulting AST node
*/
const newNode = (literal) => {
return espree.parse(literal, { ecmaVersion: 6 }).body[0].expression
}
/**
* Translates a js Array into an AST node containing its information
* @param {Array} array to be translated
* @returns {Object} the resulting AST node
*/
const newArrayNode = (array) => {
return {
"type": "ArrayExpression",
"elements": array.map((element) => newNode(element))
}
}
/**
* Checks if an AST node's info is of constant nature
* @param {Object} code to be checked
* @returns {bool}
*/
const isConstant = (code) => {
return code.type === "Literal" ||
code.type === "Identifier" ||
Array.isArray(code) && code.every((val) => isConstant(val)) ||
code.type === "ArrayExpression" && code.elements.every((val) => isConstant(val)) ||
code.type == "BinaryExpression" && code.left.type == "Literal" && code.right.type == "Literal";
}
/**
* Extracts the "value" of an AST node, it being its id, raw value, or array of elements
* @param {Object} node
* @returns {*} the value contained in the node
*/
const getValue = (node) => {
return node.raw ? `${node.raw}` :
node.id ? node.id :
node.name ? node.name :
node.elements ? node.elements.map(e => getValue(e)) : "";
}
module.exports = {
newNode,
getValue,
newArrayNode,
isConstant
}
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#arrayConstantFolding">arrayConstantFolding</a></li><li><a href="global.html#binaryConstantFolding">binaryConstantFolding</a></li><li><a href="global.html#constantFolding">constantFolding</a></li><li><a href="global.html#getValue">getValue</a></li><li><a href="global.html#isConstant">isConstant</a></li><li><a href="global.html#newArrayNode">newArrayNode</a></li><li><a href="global.html#newNode">newNode</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.10</a> on Thu Mar 10 2022 14:45:42 GMT+0000 (Western European Standard Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>