2 years ago

#50801

test-img

Peterlits Zo

How to make compiler parse `a[b]` with python-PLY?

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.

python

compiler-construction

ply

0 Answers

Your Answer

Accepted video resources