运算符优先级被忽略/在Bison中不起作用

时间:2019-06-25 23:21:59

标签: bison yacc operator-precedence

我正在尝试使Bison正确地评估表达式,但是,运算符优先级不起作用,因此该表达式的计算顺序错误。

我已经尝试使用%left%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

0 个答案:

没有答案
相关问题