我正在實現一個簡單的計算器與flex和野牛。野牛%prec不起作用
我想下面的輸入給予-4,而不是4:
-2^2
爲了達到-4,我不得不宣佈^運算符的優先級比的優先級高一元減號運算符,但它不起作用。
這是野牛代碼:
%{
#include <iostream>
#include <math.h>
using namespace std;
void yyerror(const char *s);
int yylex();
%}
%union {
int int_val;
char* string_val;
double double_val;
}
%token INTEGER
%left '+' '-'
%left '*' '/' '%'
%left UMINUS UPLUS
%right '^'
%type <int_val> expr_int INTEGER
%%
program: line '\n'
| '\n' { return 0; }
;
line: expr_int { cout<<$1<<endl; return 0; }
;
expr_int: expr_int '+' expr_int { $$ = $1 + $3; }
| expr_int '-' expr_int { $$ = $1 - $3; }
| expr_int '*' expr_int { $$ = $1 * $3; }
| expr_int '^' expr_int { $$ = pow($1,$3); }
| '-' INTEGER %prec UMINUS { $$ = -$2; }
| '+' INTEGER %prec UPLUS { $$ = $2; }
| INTEGER
;
%%
void yyerror(const char *s) {
printf("error");
}
int main(void) {
while(yyparse()==0);
return 0;
}
這是Flex代碼:
%{
#include <iostream>
#include "calc.tab.h"
using namespace std;
void yyerror(const char *s);
%}
INTEGER [1-9][0-9]*|0
UNARY [+|\-]
BINARY [+|\-|*|^|]
WS [ \t]+
%%
{INTEGER} { yylval.int_val=atoi(yytext); return INTEGER; }
{UNARY}|{BINARY}|\n { return *yytext; }
{WS} {}
. {}
%%
//////////////////////////////////////////////////
int yywrap(void) { return 1; } // Callback at end of file
爲什麼犯規野牛第一把手2^2,然後將一元減,像我定義的? 它繼續打印4,而不是...
非常感謝助手。
很高興看到你知道指數是正確聯合的。您並不需要詞法分析器中的UNARY規則。 – EJP
'[+ | \ - ]'匹配'+',''''或'-'三個字符中的任何一個。我不認爲你想接受'|'。另外,如果它是字符類中的第一個或最後一個,則不需要轉義'-'。所以你可以只寫'[+ - ]'或'[ - +]'。 – rici