views:

44

answers:

2

Lets say I need to run some initialization code everytime I match a rule how can I reduce the redundancy?

rule : TOKEN1 { init(); token1Code(); }
     | TOKEN2 { init(); token2Code(); }
     ;

Also is it possible to do something like

rule : TOKEN1
     | TOKEN2
     { codeForToken1OrToken2(); }
     ;
A: 

Since this will really work:

rule : TOKEN1 { getToken(); init(); token1Code(); }
     | TOKEN2 { getToken(); init(); token2Code(); }
     ;

where getToken(); is the name of the function that matches the next token in the input (I don't remember the name of the function), you could put a call to some init(); inside it.

eKek0
You don't seem to be answering the question.
Martin York
+3  A: 

You can use something like:

rule : { init(); } real_rule { codeForToken1or2(); } ;

real_rule : TOKEN1 { token1Code(); }
          | TOKEN2 { token2Code(); }
          ;

But this may introduce conflicts, depending on how 'rule' is used.

Chris Dodd
this grammar is not the same as DevDevDev posted
eKek0
It accepts the same language, so its equivalent
Chris Dodd
The original grammar that you posted wasn't the same language. Now, you have corrected the error
eKek0
By the way, a grammar doesn't ACCEPT a language. What it does is to GENERATE a language. Only automatons accepts languages.
eKek0
@eKekO: Your splitting hares over correct semantics.
Martin York