[antlr-interest] detecting scope

Johannes Luber jaluber at gmx.de
Sun Aug 3 13:34:11 PDT 2008


rkevinburton at charter.net schrieb:
> 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?
> 
> Thank you.
> 
> Kevin
> 

Don't try to encode the various options of modifiers for the various 
definitions in the grammar. Assuming C# as language, this causes ANTLR 
only to complain about the ambiguity if "public" belongs to a method or 
a class. After all a class can contain both possiblities. Another 
problem is that classes may be "private" only when nested, but you still 
end up allowing it for unnested classes.

Well, you could work with switches, but at some point you will realize 
that some features can't be solved in a single pass - like referencing a 
method before its definition. The proper solution is create a common 
modifier rule, which contains all valid modifiers, and to use a symbol 
table. Then in the second pass you can look if somewhere an illegal 
modifer is used. An added bonus is to have improved error messages for 
common cases, too.

Johannes


More information about the antlr-interest mailing list