为什么Bison会给出冲突:2 Shift Reduce错误

时间:2014-06-27 04:42:50

标签: compiler-construction bison context-free-grammar

我正在尝试下面的YACC语法部分,但它给了我,这有什么问题?我该如何解决?是否有一些规则来定义Bison / YACC中的语法?

C:\Users\Dilan\Documents\LexProgram\miniProject>bison -dy videostore.y
conflicts: 1 shift/reduce

我的YACC代码是:

%start VideoStore
%token title
%token type
%token name
%token days


%%

VideoStore  :   MOVIES CUSTOMERS
        |  CUSTOMERS MOVIES  
        |  MOVIES
        |  CUSTOMERS
        ;


MOVIES      :   MOVIES MOVIE
        |   MOVIE
        ;

MOVIE       :   title type RENTALS2
        ;

RENTALS2    :   RENTALS2 RENTAL2
        |   RENTAL2
        ;

RENTAL2     :   CUSTOMER1
        ;


CUSTOMER1   :   name days
        ;

CUSTOMERS   :   CUSTOMERS CUSTOMER
        |   CUSTOMER
        ;

CUSTOMER    :   name days RENTALS
        ;
RENTALS     :   RENTALS RENTAL
        |   RENTAL
        ;

RENTAL      :   MOVIE1
        ;

MOVIE1      :   title type
        ;

%%
int trace=0;

我的问题是VideoStore.y:冲突:2次/减少 怎么能为此写LEX?

1 个答案:

答案 0 :(得分:2)

使用-v选项bison,它会显示一个.output文件,显示所有状态以及发生冲突的位置。在您的情况下,您在状态16和20中存在冲突:

state 16

    7 MOVIE: title type RENTALS2 .
    8 RENTALS2: RENTALS2 . RENTAL2

    name  shift, and go to state 15

    name      [reduce using rule 7 (MOVIE)]
    $default  reduce using rule 7 (MOVIE)

    RENTAL2    go to state 24
    CUSTOMER1  go to state 18

这告诉您问题是解析器无法确定MOVIE规则的结尾位于单个前瞻标记的位置 - MOVIE以一个序列结束或更多RENTAL2个规则,但由于RENTAL2name开头,而MOVIE之后的内容(例如CUSTOMER规则)也会从name它无法判断是否应该尝试匹配更多RENTAL2

最常见的是,您可以通过在RENTALS2列表末尾使用某种分隔符来解决此问题,例如';'