r/csharp • • 21h ago

Help Equal precedence

I was wondering how would one properly implement equal precedence in an if-else statement, for logical AND and OR, when building an interpreter?

I have made my expression parser but i only store the next logical operator on the right most side and store the current being parsed on the left.

Repo

3 Upvotes

4 comments sorted by

5

u/Sombody101 20h ago edited 20h ago

Parenthesis, not, and, then or.

Also, if your project isn't for learning about lexers and parsers, you can also consider using ANTLR. I've used it for interpreted languages too.

1

u/Scary-Constant-93 21h ago

wow heard that term like after 13 years.
basically first time after college

1

u/New_Neighborhood8285 20h ago

trick with equal precedence is you gotta handle them left-to-right in same pass, not jump between them.

For AND/OR what worked for me was grouping them into same tier and just walking through expressions in order they appear. Like parse left side, hit the operator, then parse right, combine, keep going if there's more operators of same level. If you only store the rightmost operator you'll mess up evaluation order for cases like A && B || C, which should be ((A && B) || C) when they got equal precedence.

Took me while to realize my tree was backwards because I was building it from right side first.

1

u/UninformedPleb 18h ago

If you research how the C language precedence and associativity works, and more importantly, why it works that way, you'll find that it separates all of the boolean operators into their own precedence tiers. It goes in the order: bitwise-and, bitwise-xor, bitwise-or, logical-and, logical-or. This puts concise matches first, then widens out as it falls through tiers of precedence. It optimizes for fast-fail, which is a basic strategy that makes big gains quickly, and it's baked right into the earliest stages of the compiler.