1

I'm trying to make Bison correctly evaluate expressions, however, operator precedence isn't working and thus the expression gets evaluated in the wrong order.

I already tried setting the precedence with the %left and %right directives, neither worked. Interestingly enough, they resulted in the same.

The parser.y files which is used to read the syntax:

// 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; }
    ;

The part I'm trying to parse is a - b - c, which should result in (a - b) - c, but does result in a - (b - c). As far as I understood the %left directive should prevent this, but it doesn't seem to work for my case.

If further reference is needed, the code can be found on github:

The parser.y file: https://github.com/Janrupf/cutelang/blob/master/parser/gen-src/parser.y

The file which I'm trying to parse: https://github.com/Janrupf/cutelang/blob/master/parser/test-src/resources/source.ctl

Janrupf
  • 55
  • 1
  • 7
  • 2
    Precedence rules apply only to terminals. Once you reduce the terminal to a non-terminal (eg. `operator: '+'`), the precedence is gone. If you were wondering why most examples write out expression productions one per operator, this is (one of) the reasons. – rici Jun 26 '19 at 00:56

0 Answers0