alex / rply

An attempt to port David Beazley's PLY to RPython, and give it a cooler API.
BSD 3-Clause "New" or "Revised" License
381 stars 60 forks source link

Equivalent of `nonassoc` precedence #109

Open Zelatrix opened 3 years ago

Zelatrix commented 3 years ago

I want to be able to parse expressions like -5 and -(2 + 3 * 4). At the moment, I'm doing this with two separate rules, but since -5 is the same as -(5) I want to be able to use the same rule for both situations as the parentheses in -5 are implicit. In PLY, there is the nonassoc precedence, so I was wondering if such a thing also existed in RPLY?

nobodxbodon commented 3 years ago

Here's a test case with nonassoc:

https://github.com/alex/rply/blob/19a9e08c486b2723a2e2378df6edb6a26e2df4a5/tests/test_parser.py#L245

Zelatrix commented 3 years ago

I did this in my parser, and it sees the integer token 5 and complains because it was expecting a parenthesis. Have I missed something?

         precedence = [
                     ('left', ['PLUS', 'STAR', 'SLASH']),
                     ('nonassoc', ['MINUS'])
                     ]

        @self.pg.production('expr : MINUS LEFT_PAR expr RIGHT_PAR')
        def uneg_expr(p):
            return UNeg(self.builder, self.module, p[2])

If the code I compile is

print(-(5))

instead of

print(-5)

it works

nobodxbodon commented 3 years ago

I'm afraid I don't see how nonassoc would help making -(5) equivalent with -5. Have you achieved this using PLY?

Zelatrix commented 3 years ago

I've not achieved it yet, I'm trying to achieve it at the moment.