首页 > 解决方案 > 运算符优先级被忽略/在 Bison 中不起作用

问题描述

我试图让 Bison 正确评估表达式,但是,运算符优先级不起作用,因此表达式的评估顺序错误。

我已经尝试使用%leftand%right指令设置优先级,但都不起作用。有趣的是,他们的结果是一样的。

用于读取语法的 parser.y 文件:

// Declares the operators to use left precedence
// This somehow does not work here
%left T_PLUS T_MINUS T_ASTERISK T_SLASH

// T_IDENTIFIER is basically the well known identifier from
//  other programming languages (variable names and so on)
// The CREATE macro instantiates the class identifier_node,
//  it just stores the name of the identifier and shouldn't be
//  relevant for this question
//
// Identifiers
identifier : T_IDENTIFIER { $$ = CREATE(identifier_node, $1); }
    ;

// This is the actual operator expression, basically an expression
//  before and after an operator
operator_expression : expression operator expression { $$ = CREATE(operator_expression_node, $1, $2, $3); }
    ;

// This part is used for general expressions, everything except
//  operator_expression and identifier can be ignored for this
//  question
//
// Expressions
expression : numeric | assignment | member_access | function_call | operator_expression
    | identifier { $$ = $1; }
    | T_OPEN_PAREN expression T_CLOSE_PAREN { $$ = $2; }
    ;

我试图解析的部分是a - b - c,它应该导致 (a - b) - c,但确实导致a - (b - c). 据我了解,该%left指令应该防止这种情况,但它似乎不适用于我的情况。

如果需要进一步参考,可以在github上找到代码:

parser.y 文件: https ://github.com/Janrupf/cutelang/blob/master/parser/gen-src/parser.y

我试图解析的文件: https ://github.com/Janrupf/cutelang/blob/master/parser/test-src/resources/source.ctl

标签: bisonyaccoperator-precedence

解决方案


推荐阅读