Lots of Python PLY rules

In order, how can we distinguish which rule was used -

Example: - '' 'p: ab | c | d "" so suppose we need to write different code for different rules. Then is there an elegant way to do this. One way given in the guide is to use a combination of rules and tokens, but I don't always click.

+3


source to share


2 answers


Just split the expression into multiple rules, with one rule for every other code.

eg. (from http://www.dabeaz.com/ply/ply.html#ply_nn25 )

def p_expression(p):
    '''expression : expression PLUS term
              | expression MINUS term'''
    if p[2] == '+':
        p[0] = p[1] + p[3]
    elif p[2] == '-':
        p[0] = p[1] - p[3]

      



can also be written as

def p_expression_plus(p):
    'expression : expression PLUS term'
    p[0] = p[1] + p[3]

def p_expression_minus(t):
    'expression : expression MINUS term'
    p[0] = p[1] - p[3]

      

-1


source


To have multiple parsers this is not a problem, check the PLY documentation (here http://www.dabeaz.com/ply/ply.html#ply_nn37 )

lexer  = lex.lex()       # Return lexer object
parser = yacc.yacc()     # Return parser object

      

Then, when parsing, make sure you provide the parse () function with a reference to the lexer that it should use. For example:

parser.parse(text,lexer=lexer)

      

If you forget to do this, the parser will use the last lexer generated - which is not always what you want.



so you can include some attributes

In a parser, the "lexer" and "parser" attributes refer to the lexer and parser objects, respectively.

def p_expr_plus(p):
   'expr : expr PLUS expr'
   ...
   print p.parser          # Show parser object
   print p.lexer           # Show lexer object

      

More detailed information can be found here

http://www.dabeaz.com/ply/ply.html#ply_nn37

-1


source







All Articles