0

PLY's document: https://ply.readthedocs.io/_/downloads/en/latest/pdf/

I try to make it parse a[b]:

precedence = (
        # other rules...
        ('left', 'AND'),
        # other rules...
        ('nonassoc', 'GET-ITEM'),
    )

def p_expression(p):
    """
    expression : expression AND expression
               | expression '[' expression ']' %prec GET-ITEM
               | other rules...
    """

But something bad happening, when I have this token stream, it do not make thing that I want:

expression AND expression '[' expression ']'

It do not shift token '[' but reduce expresion -> expression AND expression.

It make me sad and I go to read the document. Now I know that it do not shift '[' because token '[' do not have high precedence... Wait but why? I have used %prec GET-ITEM!

To be honest, I do not know how %prec works (I only find two paragraphs in document)... Is it just change the first token's precedence? And how can I make it? Is it the only way that just make '[' have high precedence - but even '[' is not a operator?

Thx.

Peterlits Zo
  • 476
  • 1
  • 4
  • 17
  • 1
    https://stackoverflow.com/a/30339317/1566221 – rici Jan 14 '22 at 13:43
  • Hello, @rici , thanks for your kindly answer. I learn a lot. So the answer is that it is the only way that set the token `'['` as a high precedence, isn't it? – Peterlits Zo Jan 14 '22 at 17:00
  • So, the `%prec` only work for reduce, right? – Peterlits Zo Jan 14 '22 at 17:30
  • 1
    effectively. But `%prec` is only rarely necessary. It's needed for unary `-` because `-` has two meanings, but that's not the case here, for example. Also, in this case the reduction of `a[b]` is unambiguous. – rici Jan 14 '22 at 19:40
  • @rici , yes. I think I really get it. I only need to set `'['`'s precedence but not `%prec`. – Peterlits Zo Jan 16 '22 at 09:30

0 Answers0