[antlr-interest] detecting scope

Foust javafoust at gmail.com
Sat Aug 2 16:30:42 PDT 2008


Kevin wrote:
> I would like to implement a grammar that basically does what languages
> like C++ and C# do. They "know" about the context. For example within a
> classit is perfectly legal to have a statement like: private 'int a;'.
> But within a function the 'private' is not allowed. C++ allows 'static'
> with in a function (local) but C# does not. When defining a function
> within a class it is just another function (method) unless it is the
> same name as the enclosing class then it is a constructor. Etc. Using
> ANTLR how do I "detect" the "context" in which a statement is evaluated
> in. My first incination would be to define some variable when entering
> such an environment then recognize using that and the current tokens to
> fully parse the stream. But I was wondering if there was a better way.
> Maybe if I knew how to access the AST tree within a custom action I
> could "walk" up the tree to detect the environment? Any suggestions?

It appears that antlr gathers all the tokens up front, before any parser rules have been processed, so you may not be able to alter the actual tokens generated with a 'state'. 

But it's fairly straightforward to use the grammar to recognize only certain keywords in different contexts. Just have different lists of modifiers

	func_mods : STATIC | ...
	classvar_mods: PRIVATE | ...

and reference the each one in the correct context.

Recognizing a constructor will take a different approach. There is some discussion of using runtime information like that in the DAR (Definitive Antlr Reference). One way would be to keep track of the current class being parsed and preface the constructor rule with a test to check if the name of the current function matches the enclosing class name. You can create your own symbol table to do this, or possibly use the built-in dynamic scoping mechanism (also discussed in the book).

Brent




More information about the antlr-interest mailing list