Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all global references in a function?

I have a javascript function, I want to pass the function to another function and then:

  • identify all the global variables used within the function.
  • identify all the global function calls used within the function. [Harder]
  • Have this information returned in an obj.
  • Do this cleanly.

For instance:

function foo() {
    var a; // ignored
    global = 2; // want 'global'
    bar(global); // want 'bar'
};

var obj = identifier(foo); // Need to write this function 'identifier'! :)
console.log(obj); // Produces: {globar:2, bar = bar()};

Note: I am looking for a clean way. I have considered turning the function to a string, parsing each line and processing it. I feel this might not be a fool proof plan and there will be a better way. If there is not a better way I'll come back and share my solution.

Thank you

like image 936
Joshua Secretan Avatar asked May 16 '26 17:05

Joshua Secretan


1 Answers

You can use Esprima or another JS AST parser to turn the function into a clean structure. Then you can recursively analyse it. It is a bit too big to write as a StackOverflow answer, but in a nutshell, start with:

var ast = esprima.parse(foo);

Dive into .body, and recursively analyse it. Look for .type == "VariableDeclaration", that will contain local variables. Also take a look at .params of your function, those are also local. As you scan, look for .type == "Indentifier" and .type == "CallExpression"; those will use variables and functions, so check them against your list of local variables. You will need to do it in two passes, first to gather locals, then to find globals. Also, as you find .type == "FunctionDeclaration" or .type == "FunctionExpression", you have to make a new scope: move the local variables list into something like inherited locals, and make a new locals list, in order for the inner scope variables not to bleed into the outer scope.

Lots of details need to be ironed out; you can check ESTree project to see what node types are possible.

Lastly, I'd tentatively agree with zerkms: unless you are writing an editor or something similar, this is likely an XY-problem.

like image 60
Amadan Avatar answered May 18 '26 09:05

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!