YACC规则没有减少

时间:2015-03-19 01:29:16

标签: yacc rules

这是我的代码calc.y.我一直收到错误: yacc:1规则永不减少 yacc:3减少/减少冲突

不确定这意味着什么

我在其他地方做了一些研究,但我现在迷路了。我猜测所引用的规则是程序和陈述,但即便如此......减少规则是什么意思?

%{
  #include <stdio.h>
  FILE *outfile;
  int yyline = 1;
  int yycolumn = 1;
%}

%union{
  int nw;
  struct{
    int v;
    char s[1000];
  }attr;
}

%token   SEMInumber
%token   LPARENnumber
%token   <nw> ICONSTnumber
%token   BEGINnumber
%token   PROGRAMnumber
%token   MINUSnumber
%token   TIMESnumber
%token   <nw> VARnumber
%token   INTnumber
%token   EOFnumber
%token   COMMAnumber
%token   RPARENnumber
%token   <nw>IDnumber
%token   ENDnumber
%token   ISnumber
%token   PLUSnumber
%token   DIVnumber
%token   PRINTnumber
%token   EQnumber

%type <attr> exp
%type <attr> term
%type <attr> factor
%%


program: PROGRAMnumber IDnumber ISnumber compstate
         ;

compstate: BEGINnumber {print_header();} statement ENDnumber{print_end();}
           | BEGINnumber {print_header();} statement SEMInumber statement ENDnumber{print_end();}
           ;

statement: IDnumber EQnumber exp
           | PRINTnumber exp
 | declaration
           ;

declaration: VARnumber IDnumber
             | VARnumber IDnumber COMMAnumber IDnumber
             ;

exp: term {$$.v = $1.v; strcpy($$.s, $1.s);}
     | exp PLUSnumber term {$$.v = $1.v + $3.v; sprintf($$.s, "(%s) + (%s)", $1. s, $3.s);}
     | exp MINUSnumber term {$$.v = $1.v - $3.v; sprintf($$.s, "(%s) - (%s)", $1. s, $3.s);}
     ;

term: factor {$$.v = $1.v; strcpy($$.s, $1.s);}
      | term TIMESnumber factor {$$.v = $1.v * $3.v; sprintf($$.s, "(%s) * (%s)", $1.s, $3.s);}
      | term DIVnumber factor {$$.v = $1.v / $3.v; sprintf($$.s, "(%s) / (%s)", $1.s, $3.s);}
      ;

 factor: ICONSTnumber {$$.v = $1; sprintf($$.s, "%d", $1);}
          | IDnumber {$$.v = $1.v; strcpy($$.s,  $1.s);}
          | LPARENnumber exp RPARENnumber {$$.v = $2.v; strcpy($$.s,  $2.s);}
;


%%


int main()
{
  if(!yyparse())
    {
      printf("accept\n");
    }
  else
    printf("reject\n");
}

void print_header() {}
void print_end(){}

void yyerror(const char *str)
{
  printf("yyerror: %s at line %d\n", str, yyline);
}

2 个答案:

答案 0 :(得分:2)

当compstate移动BEGINnumber标记时,中间规则操作{print_header();}的两个内部规则可以减少,从而导致R / R冲突。你可以替换

compstate: BEGINnumber {print_header();} statement ENDnumber{print_end();}
           | BEGINnumber {print_header();} statement SEMInumber statement 
ENDnumber{print_end();}
           ;

,例如

begin_number:
    BEGINnumber { print_header(); }

compstate: begin_number statement ENDnumber{print_end();}
           | begin_number statement SEMInumber statement 
ENDnumber{print_end();}
           ;

解决冲突。

答案 1 :(得分:-1)

信息性消息 %s:%d规则永不减少
从来没有使用过某些规则,因为它们没有在语法中使用,或者因为它们没有使用 在转移/减少或减少/减少冲突的失败结束。要么改变 语法使用规则或删除它们。