How do I extract undefined global variables using ANTLR V4

I have a Python grammar and a textbox where users can write simple python expressions, such as this one:

(lambda x: str(x))(wanted_input)

The expression is then injected with wanted_input (by using an artificial context created when we execute the python expr).

I am interested if it is possible to use Parse Tree Listeners to extract wanted_input which are basically undefined global variables.

Answer

Yes, that’s possible.

I believe there are exactly three types of expressions that can introduce new variable names: lambdas, list comprehensions and generator comprehensions. So in your listener or visitor, you’ll want to add the newly introduced variables to the current scope when entering these three types of expressions and then remove them again when exiting (making sure to handle the case where a variable is shadowed – some kind of stack is usually the tool of choice here). Then when you see a variable, you simply check whether it’s defined in the current scope. If not, it’s one of the variables you want to extract.