Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented decorator that executes a delegate function to map a parse term to a parsed result #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion easyply/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def wrapper(p):
# named parameters extraction
for i, term in enumerate(rule.terms):
if isinstance(term, NamedTerm):
kwargs[term.name] = p[i+1]
kwargs[term.name] = p[i+1] if not hasattr(fn, 'easyply_delegate') else fn.easyply_delegate(term.name, p, i+1)
p[0] = fn(**kwargs)

wrapper.__doc__ = rule.format(pure_ply = True)
Expand Down Expand Up @@ -157,3 +157,24 @@ def process_all(globals, prefix = 'px_'):
setattr(globals, name, wrapper)


def delegate(delegator):
"""
function decorator for easyply parse function.
Take a callable to delegate assigning parse token to a named term.
Delegate should have a call signature of func(term_name : str, p : parse_token, index : int)->result
"""
# check delegator
if delegator is None:
raise ValueError('please provide a delagator function')
elif not hasattr(delegator, '__call__'):
raise NotImplementedError('delegate must be callable e.g func(term_name : str, p : parse_tokens, index : int)->result')

# wrapper function consumes easlyply parse function
def make_wrapper(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args,**kwargs)
# assign delegator as attribute on wrapper
setattr(wrapper, 'easyply_delegate', delegator)
return wrapper
return make_wrapper
39 changes: 39 additions & 0 deletions test/test_delegator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

import easyply
import ply.lex as lex
import ply.yacc as yacc


class Lexer(object):
tokens = ('A', )

t_A = r'\w+'

lexer = lex.lex()

def Location(term_name, p, i):
loc = {
'line' : p.lineno(i),
'pos' : p.lexpos(i),
}
return (p[i], loc, term_name)

class Parser(Lexer):
@easyply.delegate(Location)
def px_test(self, a):
'''production: {A}'''
global _parser
assert self is _parser
return a

def parse(self, text):
easyply.process_all(self)
self.parser = yacc.yacc(module=self)
return self.parser.parse(text, tracking=True)

def test_delegate():
global _parser
_parser = Parser()
result = _parser.parse('Hello')
assert result == ('Hello', {'line': 1, 'pos': 0}, 'a')