首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >yacc中的一元运算符优先级

yacc中的一元运算符优先级
EN

Stack Overflow用户
提问于 2019-05-28 06:45:34
回答 1查看 382关注 0票数 0

我的YACC解析器中出现了一个奇怪的错误。这是一个简单的布尔代数表达式求值器。

除了以下类型的情况外,一切都可以正常工作:

代码语言:javascript
复制
> True and False
False
> (True and False)
False
> not (True and False)     <--- interpreted as (not True and False)
False

example.y:

代码语言:javascript
复制
%{
#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", $1?"True":"False"); }             
    ;

equiv:
    impl                { $$ = $1; }                   
    |
    equiv EQUIV impl    { $$ = $1 == $3; }     
    ;

impl:
    or              { $$ = $1; }               
    |
    impl IMPL or    { $$ = !$1 || $3; }
    ;

or:
    and             { $$ = $1; }   
    |
    or OR and       { $$ = $1 || $3; } 
    ;

and:
    not             { $$ = $1; }           
    |
    and AND not     { $$ = $1 && $3; }     
    ;

not:
    value           { $$ = $1; }           
    |
    NOT not         { $$ = !$2; }
    ;

value:
    CONST           { $$ = $1; }           
    |
    '(' expr ')'    { $$ = $2; }
    ;

%%

void yyerror(const char *err) {
    fprintf(stderr, "%s\n", err);
}

int main() {
    yyparse();
}

example.l:

代码语言:javascript
复制
%{
#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;
}

使用编译

代码语言:javascript
复制
bison -dy example.y
flex -l example.l
g++ y.tab.c lex.yy.c
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-28 07:47:16

词法分析器中唯一匹配圆括号的规则是.规则,该规则不返回任何内容(或给出任何字符被忽略的指示,这正是一个糟糕的想法,因为它使得这样的问题更容易被忽略)。因此,输入中的括号被完全忽略,语法中的'('')'永远不会匹配,解析器看到的输入只是not True and False

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56333159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档