py-lua-parser: Bitwise precedence is wrong

Looking at parser/Lua.g4, it seems that the assumed bitwise priority is above multiplication, while it is in fact below concat reference on operator precedence. This is also the case in a small example. In a lua 5.4 console:

> 1&2+3
1
> (1&2)+3
3

The parsed tree for “1&2+3”:

AddOp: {} 3 keys
  left: {} 3 keys
    BAndOp: {} 3 keys
      left: {} 2 keys
        Number: {} 2 keys
          n: 1
      right: {} 2 keys
        Number: {} 2 keys
          n: 2
  right: {} 2 keys
    Number: {} 2 keys
      n: 3

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (3 by maintainers)

Commits related to this issue

Most upvoted comments

Note that the precedence changed between Lua 5.2 grammar and Lua 5.4… So master will be for Lua 5.4

I am not denying that the output of ast.to_lua_source is wrong. However, this issue is concerned with the source -> AST conversion being wrong for bitwise operations, so a bug in ast.parser, your issue is concerned with the AST -> source conversion, so a bug in ast.to_lua_source. That’s why you should open a new issue for this, as they are not related with each other. As for your second example: the AST looks something like this: (a + (b / c)) + d

I don’t understand, why you’d need brackets to be encoded in AST. Take your example:

_ = (a + 1) / 2 == 3

Removing the block and assign, this yields the following AST:

REqOp: {} 3 keys
  left: {} 3 keys
    FloatDivOp: {} 3 keys
      left: {} 3 keys
        AddOp: {} 3 keys
          left: {} 2 keys
            Name: {} 2 keys
              id: 'a'
          right: {} 2 keys
            Number: {} 2 keys
              n: 1
      right: {} 2 keys
        Number: {} 2 keys
          n: 2
  right: {} 2 keys
    Number: {} 2 keys
      n: 3

From this AST, you can clearly see, that the FloatDivOp is the outer operation, and that the AddOp is the inner operation. This is clearly defined and requires no Brackets type to encode the precedence. This also means, that the code formatter would need to account for the possibility, that an inner operation might have a lower precedence compared to an outer operation. I can only think of one use case that would require bracket information, and that is pretty printers, as they ideally don’t modify the semantics of your code, but only the style.