【发布时间】: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