【问题标题】:How to avoid a shift reduce conflict in a LALR grammar for parsing nested lists?如何避免 LALR 语法中用于解析嵌套列表的移位减少冲突?
【发布时间】:2011-09-28 10:45:30
【问题描述】:

我想创建一个 LALR 语法来解析嵌套列表,但我总是遇到移位/减少冲突。

我有 list1,它是 type1 项目和 list2 的列表:

<list1> ::= <type1> | <type1> <list1> ;
<type1> ::= A | B | <list2> ;

我有一个 list2,它是 type2 项目的列表:

<list2> ::= <type2> | <type2> <list2> ;
<type2> ::= X | Y ;

此语法会产生移位/归约错误。如何避免?

这是具体的Bigloo 来源:

(lalr-grammar 
  (comment
   new-line 
   text-chunk
   white-space)
  (input
   (()                '())
   ((node-list)       node-list))
  (node-list
   ((node)            (cons node '()))
   ((node node-list)  (cons node node-list)))
  (node
   ((comment)         (cons 'comment comment))
   ((new-line)        (cons 'new-line new-line))
   ((text)            (cons 'text text))
   ((white-space)     (cons 'white-space white-space)))
  (text
   ((text-chunk)      (cons 'text text-chunk))
   ((text-chunk text) (cons 'text (string-append text-chunk text)))))

终端是:comment、new-line、text-chunk 和 white-space。 非终结符是:输入、节点列表、节点和文本。

Bigloo 抱怨文本到文本块的缩减规则:

*** WARNING:bigloo:lalr-grammar
** Shift/Reduce conflict: 
 - shift to state 2
 - reduce rule (text --> text-chunk)
on token `text-chunk'

但我不认为这是一个 Bigloo 问题。好像是语法问题。

【问题讨论】:

    标签: scheme grammar lalr shift-reduce-conflict bigloo


    【解决方案1】:

    语法实际上是模棱两可的,因为type2实例序列可以在list2级别上累积,但也可以看作type1实例序列。

    例如这个输入

     X X
    

    可以解析为

     list1(
       type1(
         list2(
           type2(
             X)
           list2(
             type2(
               X)))))
    

    也可以作为

     list1(
       type1(
         list2(
           type2(
             X)))
       list1(
         type1(
           list2(
             type2(
               X)))))
    

    list1 级别上引入分隔符怎么样?这样就可以解决问题了。

    【讨论】:

    • 谢谢!你说的对。我能够通过两种方式解决问题。首先,可以膨胀语法以正确地引导解析器。但是第二种解决方案要优雅得多。我可以在我的 Bigloo 语法中为 type2 终端指定优先级。这样,解析器不会将 type2 元素列表视为 type1 元素列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多