[antlr-interest] OO design question

Terence Parr parrt at jguru.com
Thu Jun 13 15:42:56 PDT 2002

On Thursday, June 13, 2002, at 03:19  PM, Trey Spiva wrote:

>>>> So!  How do you get a good separable chunk called an Analyzer without
>>>> making the implementation fully of crappy switch-statements?  I.e., 
>>>> how
>>>> do I use aspect programming w/o losing the polymorphism convenience?!
>>>> Anybody wanna lend me some smarts?
>>> Have you thought about using a Visitor Pattern?
>> I think a visitor is really what i'm talking about; perhaps I'm asking
>> about a good way to implement it :)
> Well how about this.
> public class Analyzer implements LookaheadVistor
> {
>   ...
> }
> When you want to retrieve the lookahead information make the call
> GrammarElement element = <Some Grammar Element>
> ...
> element.lookahead(Analyzer);
> The GrammerElement will still be responsible of calculating the 
> lookahead
> and will be using the analyzer to calculating the lookahead.  You will 
> also
> be able to change how the lookahead is calculated by changing the
> implementation of the LookaheadVistor that is used by the 
> GrammerElement.

Yeah, I was just reading about this "mix-in class" concept in an AspectJ 
paper.  Seems that the method overloading would make things work ok 
without a switch.  The analyzer would route to the element and the 
element would route back to the analyzer thus getting the polymorphism 
and separation:

class GrammarTokenRef extends GrammarElement {
   public LookaheadSet lookahead(int k) {
     analyzer.lookahead(this, k);

class GrammarSubrule extends GrammarElement {
   public LookaheadSet lookahead(int k) {
     analyzer.lookahead(this, k);

Note that the "this" ref in the lookahead method call forces the 
compiler to bind to the object specific lookahead method as in:

class Analyzer {
   public LookaheadSet lookahead(GrammarTokenRef node, int k) {...}
   public LookaheadSet lookahead(GrammarSubrule node, int k) {...}

Also as you mention, the analyzer variable in GrammarElement superclass 
can be set at runtime to change the behavior :)  This might be a cute 
way to try the approx lookahead and if it fails, swap in the full LL(k) 
bad boy.

Anyway, the main analysis engine would be able to say node.lookahead(k) 
and yet all code for this aspect would live in the Analyzer--the 
lookahead method in the GrammarElement is just a ping-pong back into the 
analyzer.  This is suboptimal of course since you can't add an "aspect" 
w/o adding a ping-pong method in each GrammarElement.

Co-founder, http://www.jguru.com
Creator, ANTLR Parser Generator: http://www.antlr.org


Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 

More information about the antlr-interest mailing list