开发者

Is it possible to stack Yacc grammar rule code?

开发者 https://www.devze.com 2022-12-12 14:18 出处:网络
Lets say I need to run some initialization code everytime I match a rule how can I reduce the redundancy?

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();开发者_如何学Go }
     ;


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消