Reputation: 1239
I have created an interpreter similar to Visual Basic and now adding some variable scope. My source for information is CH8 of The Definitive Antlr Reference and its accompanying code. Essentially the examples use Listeners and my code uses Visitors.
I would appreciate it if someone could clarify or correct my understanding of things:
In terms of scopes, I should use the Listener model (as per the book Cymbol examples) to first walk a tree to create the scope/variable information by overriding the appropriate enter/exit functions relating to functions and blocks where I need to capture the scope change. Secondly, having created the scopes, do I then Visit the tree to run the program? e.g. where I have VisitEnterFunction and VisitExitFunction I should then push and pop scopes.
Thanks in advance for helping me establish the proper way to do this. Kevin
Upvotes: 2
Views: 708
Reputation: 818
There is more than one way to implement nested scopes. To resolve symbols which are defined later in the source a two pass approach is mandatory. The first pass could build a Symbol tree which is later user at runtime in a current scope stack. A second option would be attaching the scope as annotation to the syntax tree itself. Again I cannot recommend the book Language implementation patterns high enough for the questions you encounter - exactly this stuff is covered there.
Upvotes: 2