Shift减少冲突,财务计算器使用编译器

Shift reduce conflict, financial calculator using compiler

本文关键字:计算器 编译器 冲突 Shift      更新时间:2023-10-16

每当我添加'(' term ')' { $$=$2; }时,我得到shift减少冲突我要做的操作是:(5) + (5)
(5.5) + (5),
((5.5) + (5)) - (5),
((5.5) / (5.5)) * (5),等

我对shift - reduce解析有点困惑,我们的教授只教我们如何在示例语法中shift - reduce解析,但不教如何将其应用于cpp。

我用的是野牛。

%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int yylex();
#define YYERROR_VERBOSE
void yyerror(const char *msg){
printf("ERROR(PARSER): %sn", msg);
}
double vars[26];
%}
%union{
double dvalue;
int varindex;
}
%token <dvalue> NUMBER
%token <varindex> NAME
%type <dvalue> expression
%type <dvalue> term
%type <dvalue> varornum
%%
statementlist : statement 'n'
| statement 'n' statementlist
;
statement : NAME '=' expression { vars[$1] = $1;}
| expression { printf("ANS: %fn", $1); }
;
expression: '(' expression ')' { $$ = $2;}
| expression '+' term { $$ = $1 + $3;}
| expression '-' term { $$ = $1 - $3;}
| term { $$ = $1; }
;
term : '(' term ')' { $$ = $2;}
| term '*' varornum { $$ = $1 * $3;}
| term '/' varornum {
if ($3==0) {
printf("ERROR: Divide %f by zeron", $1);
} else {
$$ = $1 / $3;
}
}
| varornum { $$ = $1; }
;
varornum : NUMBER { $$ = $1; }
| NAME { $$ = vars[$1];}
;
%%
main(){
yyparse();
}

您的语法中已经包含了'(' expr ')' { $$=$2; }。添加'(' term ')' { $$=$2; }会与此规则产生冲突。你只需要其中一个。exprterm还是termexpr ?