wren-lang / wren

The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.
http://wren.io
MIT License
6.9k stars 552 forks source link

Operators and precedence #175

Closed MarcoLizza closed 9 years ago

MarcoLizza commented 9 years ago

Currently the precedence is not so detailed as one could expect. This is especially true when coming from C/C++/Java/whatever and working with the logical operators and bitwise (they left-associate only).

Should we dismiss this as "work-as-designed", or fix it by adding more precedence levels?

kmarekspartz commented 9 years ago

Python resolves the association issue in an odd way by having a separate method for right association which it falls back on if there is a TypeError on the left association. But at least it allows for right associations!

Not sure what a good way to do this in Wren would be.

MarcoLizza commented 9 years ago

Left-associativity is fine for bitwise operands. Adding some other precedence levels is quite easy and would solve the issue.

My only concern is whether we should stick and reproduce (let's say) C++ precedence or adopt and document our custom one (and suggest the proper use of brackets).

munificent commented 9 years ago

My intent is to have the same precedence levels as C except fix the "bug" in C's grammar the bitwise operators are lower precedence than the comparison and equality operators.

As far as I know, the grammar now does that. What changes did you have in mind?

MarcoLizza commented 9 years ago

But the bitwise operators relative precedence does not conform to C's.

I put a little precedence test as follows

IO.print(2 | 1 << 1) // expect: 2
IO.print(1 << 1 | 2) // expect: 2
IO.print(2 & 1 << 1) // expect: 2
IO.print(1 << 1 & 2) // expect: 2
IO.print(2 ^ 1 << 1) // expect: 0
IO.print(1 << 1 ^ 2) // expect: 0
IO.print(1 & 1 | 2) // expect: 3
IO.print(2 | 1 & 1) // expect: 3
IO.print(1 & 1 ^ 2) // expect: 3
IO.print(2 ^ 1 & 1) // expect: 3
IO.print(1 ^ 1 | 1) // expect: 1
IO.print(1 | 1 ^ 1) // expect: 1

The current Wren grammar fails in preserving the precedence of << and >> over the others, and & over ^.

munificent commented 9 years ago

Ah, yes. We should definitely fix those. :)

hachibu commented 9 years ago

It would also be fantastic to have a table outlining operators, precedence and associativity in the documentation! Most languages have something like this, and it was the first thing I tried to find for Wren.

munificent commented 9 years ago

@hachibu Great idea! If you'd like to add that to the syntax.md file, I'd be happy to merge it in. Otherwise, I'll try to do it when I get a chance.

hachibu commented 9 years ago

I would love to take a stab at it!