I am trying to detect all global variables referenced by a JavaScript code snippet using Jint.Parser.JavaScriptParser
. I'm doing this by following the code example from this issue to retrieve a list of tokens and then removing the names of any declared functions like so:
private List<string> FindIdentifiers()
{
JavaScriptParser parser = new JavaScriptParser();
Program program = parser.Parse(Source, new ParserOptions { Tokens = true });
List<string> allTokens = program.Tokens
.Where(t => t.Type == Jint.Parser.Tokens.Identifier)
.Select(t => t.Value.ToString())
.Distinct()
.ToList();
foreach (FunctionDeclaration declaration in program.FunctionDeclarations)
{
allTokens.Remove(declaration.Id.Name);
}
return allTokens;
}
This works fine for simple primitive variables, but when referencing a global variable that is an object, the parser also returns members of those objects as being of type Identifier
. Which is correct, but I need to distinguish between top-level identifiers and other kinds of identifiers like this, but as far as I can see, there is no way to do this. Anyone have a clever workaround?