Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #####################
- # Parsing framework #
- #####################
- lue = lambda c: lambda inp: inp[1:] if inp and inp[0] in c else None
- tai = lambda va,vb: lambda inp: va(inp) or vb(inp)
- ja = lambda va,vb: lambda inp: (lambda x: x and vb(x))(va(inp))
- class P(object):
- def __init__(self, c, name=""):
- self.test = c
- self.desc = name
- def __and__(self, o):
- n = P(self.test, self.desc+"&"+o.desc)
- n.test = ja(n.test, o.test)
- return n
- def __or__(self, o):
- n = P(self.test, '('+self.desc+"|"+o.desc+')')
- n.test = tai(n.test, o.test)
- return n
- def __call__(self, inp):
- print self.desc
- return self.test(inp)
- ###############################
- # Language grammar definition #
- ###############################
- cra = lambda a,b: set(chr(i) for i in range(ord(a), ord(b)+1))
- letter = cra('a','z')|cra('A','Z')|set('_')
- digit = cra('0','9')
- term = lambda a: P(lue(a), '"'+str(a)[:1]+'"')
- word = term(letter) & P(lambda i: word(i)) | term(letter)
- digits = term(digit) & P(lambda i: digits(i)) | term(digit)
- number = term('-') & digits | digits
- ws = term(' ') & P(lambda i: ws(i)) | term(' ')
- code_ = word | number | ws | P(lambda i: block(i))
- code = code_ & P(lambda i: code(i)) | code_
- block = term('[') & code & term(']') | (term('[') & term(']'))
- ###########
- # Testing #
- ###########
- print word("abSDFf_kj%")
- print code("-034 num %")
- print code("034 kd[dfd [123 dflkj -340] [] 3498]%")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement