This project has moved and is read-only. For the latest updates, please go here.

Finding Variable References in Code Snippet

Jun 20, 2014 at 4:03 PM
Hi,

I have small snippets of javascript code that contain 1-10 references to variables that belong to a 6000+ survey. The vast majority of these items do not have values, and even of the ones that do only a small minority (usually no more than 10) are actually referenced in each snippet of code.

Instantiating all 6000+ variables is proving to be too slow and costly to do for each snippet.

Is there a way to pull out all the variable references/names in a snippet of code before it is actually executed? That way, I could see which ones were actually required and pre-load their values ahead of the code to be run.

Otherwise, I fear I'll have to do some sort of string/regex search, which I would like to avoid.
Coordinator
Jun 21, 2014 at 7:38 PM
Greetings!

It sounds like you're looking for a JavaScript parsing or code analysis library. Esprima is one that's written in JavaScript.

Good luck!
Jun 23, 2014 at 2:50 PM
Hi,

I ended up finding out that Jint includes a parser that can do what I was looking for. Here is an example of how I used it:
List<string> itemRefs = new List<string>();
        JavaScriptParser jpParser = new JavaScriptParser();

        Program parsedJS = jpParser.Parse(formulaToEval, new ParserOptions { Comment = true, Source = formulaToEval, Tokens = true, Tolerant = true });

        foreach (Token jsToken in parsedJS.Tokens)
        {
            string tokenVal = jsToken.Value.ToString();

            if (jsToken.Type != Tokens.Identifier )
                continue;



            itemRefs.Add(tokenVal );
        }

        return itemRefs;