@alu0101240374/addlogging
Version:
59 lines (53 loc) • 1.98 kB
JavaScript
/**
* Universidad de La Laguna
* Escuela Superior de Ingenieria y Tecnologia
* Grado de Ingenieri Informatica
* @author Gabriel Garcia Jaubert
* @date 10 mar 2020
* @brief This program adds logg messages of called functions
*/
const util = require('util');
var escodegen = require('escodegen');
var espree = require('espree');
var estraverse = require('estraverse');
module.exports = {addLogging};
/**
* Function that reads the ast-tree, locates the function node
* and and calls addBeforeCode for adding the log.
*
* @param {code} Code code we want to add logs on
* @param {string} Pattern Only functions that match
* the pattern substring will be add
*/
function addLogging(code, pattern) {
var ast = espree.parse(code, {ecmaVersion: 6, loc: true});
let patternRegEx = new RegExp(pattern);
estraverse.traverse(ast, {
enter: function(node, parent) {
if ((node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression') &&
(pattern == undefined || node.id == undefined ||
patternRegEx.test(node.id.name))) {
addBeforeCode(node);
}
}
});
return escodegen.generate(ast);
}
/**
* Receives a node, creates the console message, creates a ast node
* and concatenates it to the received node
*
* @param {code} Code code we want to add loggs on
* @param {string} Pattern Only functions that match the pattern substring
* will be logged
*/
function addBeforeCode(node) {
var name = node.id ? node.id.name : '<anonymous function>';
let parameters = node.params.map(param => `\$\{${param.name}\}`);
var beforeCode = `console.log(\`Entering ${name}(${parameters}) at line ${node.loc.start.line}\`);`;
var beforeNodes = espree.parse(beforeCode, { ecmaVersion: 6 }).body;
node.body.body = beforeNodes.concat(node.body.body);
}