gpt4 book ai didi

c - Lex/Yacc Flex/Bison : Precedence on reusing tokens for multiple production rules

转载 作者:行者123 更新时间:2023-12-03 23:25:16 25 4
gpt4 key购买 nike

我正在为表达式制作一个简单的编译器,但是我一直在弄清楚如何使用 Bison 的优先级关键字

在我的词法分析器中,我定义了以下检查:

'-'     {ECHO;return(MINUS);}

但是,我注意到在评估表达式时,“-”可以有两种含义,1) 表示减法和 2) 表示对数字取反,并且两者具有不同的优先级。

在我的解析器文件中,我将如何通过使用 %left 和 %right 来定义关联性来解决这个问题?

我知道我能做到
%left PLUS
%left MINUS
... and so on

对于每个这样的标记,但由于否定具有正确的结合性和更高的优先级,我将如何将其包含在此处,因为我认为我无法做到
%left PLUS
%left MINUS
%right MINUS /* This is the negation one */

谢谢你的帮助!

最佳答案

引自 http://dinosaur.compilertools.net/yacc/ :

[...] unary operators must, in general, be given a precedence. Sometimes a unary operator and a binary operator have the same symbolic representation, but different precedences. An example is unary and binary '-'; unary minus may be given the same strength as multiplication, or even higher, while binary minus has a lower strength than multiplication. The keyword, %prec, changes the precedence level associated with a particular grammar rule. %prec appears immediately after the body of the grammar rule, before the action or closing semicolon, and is followed by a token name or literal. It causes the precedence of the grammar rule to become that of the following token name or literal. For example, to make unary minus have the same precedence as multiplication the rules might resemble:


    %left  '+'  '-'
%left '*' '/'

%%

expr : expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| '-' expr %prec '*'
| NAME
;

关于c - Lex/Yacc Flex/Bison : Precedence on reusing tokens for multiple production rules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26540555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com