yacc 中的一元运算符优先级
Unary operator precedence in yacc
我的 YACC 解析器出现奇怪的错误。这是一个简单的布尔代数表达式求值器。
除以下情况外一切正常:
> True and False
False
> (True and False)
False
> not (True and False) <--- interpreted as (not True and False)
False
example.y:
%{
#include <stdio.h>
int yylex();
void yyerror(const char *err);
%}
%token NEWLINE EQUIV IMPL OR AND NOT CONST
%union {
bool value;
}
%type <value> CONST value not and or impl equiv expr
%%
program:
|
program expr NEWLINE
;
expr:
equiv { printf("%s\n", ?"True":"False"); }
;
equiv:
impl { $$ = ; }
|
equiv EQUIV impl { $$ = == ; }
;
impl:
or { $$ = ; }
|
impl IMPL or { $$ = ! || ; }
;
or:
and { $$ = ; }
|
or OR and { $$ = || ; }
;
and:
not { $$ = ; }
|
and AND not { $$ = && ; }
;
not:
value { $$ = ; }
|
NOT not { $$ = !; }
;
value:
CONST { $$ = ; }
|
'(' expr ')' { $$ = ; }
;
%%
void yyerror(const char *err) {
fprintf(stderr, "%s\n", err);
}
int main() {
yyparse();
}
example.l:
%{
#include "y.tab.h"
extern "C" int yywrap();
%}
%%
True yylval.value = true; return CONST;
False yylval.value = false; return CONST;
"<=>" return EQUIV;
=> return IMPL;
or return OR;
and return AND;
not return NOT;
[ \t] ;
\n return NEWLINE;
. ;
%%
int yywrap() {
return 1;
}
编译为
bison -dy example.y
flex -l example.l
g++ y.tab.c lex.yy.c
词法分析器中唯一匹配括号的规则是 .
规则,它不 return 任何东西(或给出任何字符已被忽略的指示,这完全是个坏主意因为它使像这样的问题更容易被遗漏)。因此,您输入中的括号将被完全忽略,语法中的 '('
和 ')'
永远无法匹配,解析器看到的输入只是 not True and False
.
我的 YACC 解析器出现奇怪的错误。这是一个简单的布尔代数表达式求值器。
除以下情况外一切正常:
> True and False
False
> (True and False)
False
> not (True and False) <--- interpreted as (not True and False)
False
example.y:
%{
#include <stdio.h>
int yylex();
void yyerror(const char *err);
%}
%token NEWLINE EQUIV IMPL OR AND NOT CONST
%union {
bool value;
}
%type <value> CONST value not and or impl equiv expr
%%
program:
|
program expr NEWLINE
;
expr:
equiv { printf("%s\n", ?"True":"False"); }
;
equiv:
impl { $$ = ; }
|
equiv EQUIV impl { $$ = == ; }
;
impl:
or { $$ = ; }
|
impl IMPL or { $$ = ! || ; }
;
or:
and { $$ = ; }
|
or OR and { $$ = || ; }
;
and:
not { $$ = ; }
|
and AND not { $$ = && ; }
;
not:
value { $$ = ; }
|
NOT not { $$ = !; }
;
value:
CONST { $$ = ; }
|
'(' expr ')' { $$ = ; }
;
%%
void yyerror(const char *err) {
fprintf(stderr, "%s\n", err);
}
int main() {
yyparse();
}
example.l:
%{
#include "y.tab.h"
extern "C" int yywrap();
%}
%%
True yylval.value = true; return CONST;
False yylval.value = false; return CONST;
"<=>" return EQUIV;
=> return IMPL;
or return OR;
and return AND;
not return NOT;
[ \t] ;
\n return NEWLINE;
. ;
%%
int yywrap() {
return 1;
}
编译为
bison -dy example.y
flex -l example.l
g++ y.tab.c lex.yy.c
词法分析器中唯一匹配括号的规则是 .
规则,它不 return 任何东西(或给出任何字符已被忽略的指示,这完全是个坏主意因为它使像这样的问题更容易被遗漏)。因此,您输入中的括号将被完全忽略,语法中的 '('
和 ')'
永远无法匹配,解析器看到的输入只是 not True and False
.