Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all functions that are called by another function

In JavaScript, is it possible to obtain a list of all functions that are called by another function? I want to create a tree of function dependencies, to analyze how the functions in a script are related to each other (and which functions are required by which other functions).

For example:

getAllCalledFunctions(funcA); //this should return [funcB, funcC, funcD], since these are the functions that are required by funcA.

function getAllCalledFunctions(functionName){
    //how should I implement this?
}

function funcA(){
    funcB();
    funcC();
}

function funcB(){
    funcD();
}

function funcC(){
    funcD();
}

function funcD(){
    console.log("This function is called by funcC and funcD");
}
like image 324
Anderson Green Avatar asked Mar 16 '13 04:03

Anderson Green


2 Answers

Esprima may help you. It is a Javascript parser that can help you do static code analysis.

Here's a quick example (http://jsfiddle.net/fyBvT/):

var code = 'function funcA() { funcB(); funcC(); } function funcB(){ funcD(); } function funcC() { funcD(); } function funcD(){ console.log("This function is called by funcC and funcD"); }';
var syntax = esprima.parse(code);

var funcs = [];
_.each(syntax.body, function(i) {
    if (i.type == 'FunctionDeclaration') {
        var func = {name: i.id.name};

        _.each(i.body.body, function(j) {
            if (j.type == 'ExpressionStatement' && j.expression.type == 'CallExpression') {
                func.calls = func.calls || [];
                func.calls.push(j.expression.callee.name);
            }
        });

        funcs.push(func);
    }
});

console.log(funcs);

Clearly this needs a lot of help to offer much value, but it might give you some idea of what's possible and where to start.

like image 133
Trevor Dixon Avatar answered Oct 16 '22 14:10

Trevor Dixon


Interesting question. I too question the motive behind it... Hopefully it's just for debugging or understanding the structure of the application better.

Here's a WILD idea: Just throwing it out there...

If you could tie into each function, you can get the callee by:

arguments.callee.name

And write that to a global variable (perhaps an object with each key being the name of the function, and the value being an array of function names).

like image 27
Aaron Blenkush Avatar answered Oct 16 '22 15:10

Aaron Blenkush