【问题标题】:shift/reduce conflict in Happy转移/减少快乐中的冲突
【发布时间】:2012-05-17 15:16:21
【问题描述】:

如何制定正确的规则来解析 if-then[-else] 大小写? 这是一些语法:

{
 module TestGram (tparse) where
}

%tokentype    { String  }
%token one    { "1"     } 
       if     { "if"    }
       then   { "then"  }
       else   { "else"  }

%name tparse  

%%

statement : if one then statement else statement {"if 1 then ("++$4++") else ("++$6++")"}
          | if one then statement                {"if 1 then ("++$4++")"}
          | one                                  {"1"}


{
 happyError = error "parse error"
}

此语法正确解析以下表达式:

> tparse ["if","1","then","if","1","then","1","else","1"]
"if 1 then (if 1 then (1) else (1))"

但编译会引发有关移位/减少冲突的警告。快乐的文档包含此类冲突的示例: http://www.haskell.org/happy/doc/html/sec-conflict-tips.html

这里有两种解决方案,第一种是改变递归类型(在这种情况下不清楚如何做)。第二个是不改变任何东西。这个选项对我来说没问题,但我需要咨询。

【问题讨论】:

  • 不太了解happy,但这是well-known example of an ambiguous grammar。 (例如,the 示例,每个人在教授解析器生成器等时都会开始使用。)解决这些问题的通常方法是选择默认括号,而另一个需要括号;这可以通过使用两种“语句”来实现:一种允许 if/then/else 子句和 if/then 子句,另一种不允许。
  • 可以将冲突留在原地。它传统上存在于带有可选 else 的语言的 LALR 语法中。解析器默认做正确的事,所以没有什么好担心的。

标签: haskell shift-reduce-conflict happy


【解决方案1】:

请注意,可以使用 LALR(1) 中的语法解决此问题,而不会发生 S/R 冲突:

stmt: open
    | closed

open: if one then stmt             {"if 1 then ("++$4++")"}
    | if one then closed else open {"if 1 then ("++$4++") else ("++$6++")"}

closed: one                            {"1"}
      | if one then closed else closed {"if 1 then ("++$4++") else ("++$6++")"}

这个想法来自resolving the dangling else/if-else ambiguity的这个页面。

基本概念是我们将语句分类为“开放”或“封闭”:开放语句是那些至少有一个 if 且不与后面的 else;关闭的是那些根本没有 if 的,或者确实有它们,但它们都与 else 配对。

解析if one then if one then one else one从而解析:

  • . if — 换班
  • if . one — 换班
  • if one . then — 转变
  • if one then . if — 转变
  • if one then if . one — 换班
  • if one then if one . then — 转变
  • if one then if one then . one — 换班
  • if one then if one then (one) . else — 减少 closed 规则 1
  • if one then if one then closed . else — 换班
  • if one then if one then closed else . one — 换班
  • if one then if one then closed else (one) . — 减少 closed 规则 1
  • if one then (if one then closed else closed) . — 减少 closed 规则 2
  • if one then (closed) . — 减少 stmt 规则 2
  • (if one then stmt) . — 减少 open 规则 1
  • (open) . — 减少 stmt 规则 1
  • stmt . — 停止

(当减少发生时,我已经说明了发生了哪个减少规则,并在被减少的标记周围加上了括号。)

我们可以看到解析器在 LALR(1) 中没有歧义(或者更确切地说,Happy 或 bison 会告诉我们 ;-)),并且遵循规则会产生正确的解释,内部 if 与 else 一起减少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多