How to remove Left recursive in this ANTLR grammar?

巧了我就是萌 提交于 2019-12-11 05:31:58

问题


I am trying to parse CSP(Communicating Sequential Processes) CSP Reference Manual. I have defined following grammar rules.

assignment
    : IDENT '=' processExpression
    ;
processExpression
    :   ( STOP
        | SKIP
        | chaos
        | prefix
        | prefixWithValue
        | seqComposition
        | interleaving
        | externalChoice

        ....

seqComposition
    :   processExpression ';' processExpression
    ;
interleaving
    :   processExpression '|||' processExpression
    ;
externalChoice
    :   processExpression '[]' processExpression
        ;

Now ANTLR reports that

seqComposition 
interleaving
externalChoice

are left recursive . Is there any way to remove this or I should better used Bison Flex for this type of grammar. (There are many such rules)


回答1:


Define a processTerm. Then write rules looking like

assignment
    : IDENT '=' processExpression
    ;
processTerm
    :   ( STOP
        | SKIP
        | chaos
        | prefix
        ...
processExpression
    :   ( processTerm
        | processTerm ';' processExpression
        | processTerm '|||' processExpression
        | processTerm '[]' processExpression

        ....

If you want to have things like seqComposition still defined, I think that would be OK as well. But you need to make sure that the parsing of processExpansion is going to always consume more text as you proceed through your rules.




回答2:


Read the guide to removing left recursion in on the ANTLR wiki. It helped me a lot.



来源:https://stackoverflow.com/questions/5425977/how-to-remove-left-recursive-in-this-antlr-grammar

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