级联移位-减少冲突 [英] Concatenation shift-reduce conflict

查看:101
本文介绍了级联移位-减少冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JavaCUP的LR(1)解析器,我有一个简单的语法,它可以识别标识符和字符串的串联表达式.我还想添加一些空函数调用作为可能的串联参数.但是,当我尝试这样做时,会导致移位/减少冲突.

I have a simple grammar for JavaCUP's LR(1) parser that recognises concatenation expressions of identifiers and strings. I also want to add some empty function calls as a possible concatenation argument. However, when I try that, it leads to a shift/reduce conflict.

语法:

precedence left PLUS;

e ::= e exp
      | exp;

exp ::= concat
      | literal;

concatenation ::= exp PLUS exp
                | LPAREN exp RPAREN;


literal ::= IDENTIFIER
          | STRING
          | IDENTIFIER LPAREN RPAREN; // THIS PRODUCES THE ERROR

输入:

x + x + (x)            // match
"foo" + x              // match
(("goo") + (((y))))    // match

function_name() + x + "foo" + (other_func())    // what I also want

冲突:

Warning : *** Shift/Reduce conflict found in state #12
between literal ::= IDENTIFIER (*) 
and     literal ::= IDENTIFIER (*) LPAREN RPAREN  
under symbol LPAREN

我尝试了许多不同的操作,例如在文字和second ::= | LPAREN RPAREN;处隐藏了IDENTIFIER second这样的标识符,但我无法使其正常工作.

I have tried many different things like hiding identifier like IDENTIFIER second at literal and second ::= | LPAREN RPAREN; but I can't make it work.

推荐答案

似乎出现这种情况的上下文位于类似

The context in which this seems to come up is in expressions like

x + x()

解析器在看到x + x之后无法分辨是将x + x还原为exp还是将(移位.换句话说,它无法判断是否将表达式解释为

where the parser, after seeing x + x, can't tell whether it's supposed to reduce x + x back to exp or shift the (. In other words, it can't tell whether to interpret the expression as

x + [x()]

或为

[x + x]()

我认为您可以通过添加优先级规则来解决此问题,该规则为在此特定上下文中的开放括号赋予比添加优先级更高的优先级.这样,当解析器在这种状态下看到移位并减少动作时,便知道在开放括号上进行移位而不是减小.

I think you can address this by adding in a precedence rule that gives the open parenthesis in this particular context higher precedence than addition. That way, when the parser sees the shift and reduce action in this state, it knows to shift on an open parenthesis rather than reduce.

这篇关于级联移位-减少冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆