I'm getting a real kick out of playing with Ply. Fun stuff, very educational.
In this kind of situation:
def p_stmt_assignment(p):
'''
stmt : identifier ASSIGN expr
'''
p[0] = Node('assign', children=[p[1], p[3]])
def p_expr_term(p):
'''
expr : term
'''
p[0] = Node('expr',children=[p[1]])
The names of the functions are meaningless and kind of annoying...
they duplicate the information in the docstring, get out of sync, etc.
With a little decorator like this:
def production(s):
# create the function that the decorator returns
# which gets immediately called with the function
# containing the actual evalling/AST-generating code
def impl(f):
# p_impl is the parser function that just calls to the decorated
# function
def p_impl(p):
s
return f(p)
# up in the namespace containing the decorator, assign our
# p_impl function to a generated name where ply will find it.
# It checks that name __name__ attribute of the function
# starts with p_... we need to set that.
fnname = 'p_' + s.replace(':','').replace(' ', '_')
p_impl.__name__ = fnname
frameup = sys._getframe(1)
frameup.f_locals[fnname] = p_impl
return impl
You can get rid of a bit of that redundancy and do this:
@production('stmt : identifier ASSIGN expr')
def f(p):
p[0] = Node('assign', children=[p[1], p[3]])
@production('expr : term')
def f(p):
p[0] = Node('expr',children=[p[1]])
... just in case that appeals to anybody ...
-t
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"ply-hack" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/ply-hack?hl=en
-~----------~----~----~----~------~----~------~--~---