Left Factoring & Removing Left Recursion JavaCC

∥☆過路亽.° 提交于 2019-12-06 04:57:34

You have a number of problems here. Most are dealt with in question 4.6 of the JavaCC FAQ. http://www.engr.mun.ca/~theo/JavaCC-FAQ/

First, there is a lot of left-factoring to do. Left factoring tries to move choices to later in the parse. E.g. if you have

void statement() #STM : {}
{
   identifier() <ASSIGNMENT> expression()
 | identifier() <ASSIGNMENT> <STRING>
 | identifier() <LBR> arg_list() <RBR>
}

and the parser is expecting a statement and the next item of input is an identifier, then the parser can't make the choice. Factor out the common parts on the left to get

void statement() #STM : {}
{
   identifier()
      (   <ASSIGNMENT> expression()
      |   <ASSIGNMENT> <STRING>
      |   <LBR> arg_list() <RBR>
      )
}

and then

void statement() #STM : {}
{
   identifier()
      (   <ASSIGNMENT> ( expression() | <STRING> )
      |   <LBR> arg_list() <RBR>
      )
}

Second, the nonterminal "matched" is useless, as there is no nonrecursive case. I suspect that you are trying to deal with the dangling else problem. This is not a good way to deal with the dangling else problem. See the JavaCC FAQ for a sensible way to deal with it.

Third, there is mutual left recursion between nonterminals "fragment" and "expression". I'm not sure what you are trying to accomplish here. There are several ways to deal with parsing expressions that don't use left recursion. See http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm for more information. My tutorial introduction to JavaCC might also help. http://www.engr.mun.ca/~theo/JavaCC-Tutorial/

Finally a word of advice. Start with a grammar for a small subset of your language and then add constructs one or two at a time. That way you won't have to deal with a lot of problems at once.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!