i'm using visitor from ANTLR4 to develop an interpreter in c#. in my grammar, i have a rule for looping and a rule for assignment as below:
for_stmt
: FOR EACH ID IN collection DO NEWLINE+
(block NEWLINE*)?
END FOR
;
set_stmt
:SET ID '.' ID TO arithExpr
;
block
: for_stmt
| set_stmt
;
inside the for loop, we can have set statements like this:
for each record in recordCollection do
set record.name to 10
end for
the record used inside the set statement must be the same as the record used in the loop. how can i check this?
Your visitor can maintain a stack of variable definitions (scopes):
for_stmt
pushes the variable declarations onto the stack (and pops it after visiting the child nodes)set_stmt
inspects the stack and throws a runtime exception if it cannot find the accessed id on the stack