Advertisement
Guest User

PEG

a guest
Nov 6th, 2011
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. #####################
  2. # Parsing framework #
  3. #####################
  4.  
  5. lue = lambda c: lambda inp: inp[1:] if inp and inp[0] in c else None
  6. tai = lambda va,vb: lambda inp: va(inp) or vb(inp)
  7. ja  = lambda va,vb: lambda inp: (lambda x: x and vb(x))(va(inp))
  8.  
  9. class P(object):
  10.     def __init__(self, c, name=""):
  11.         self.test = c
  12.         self.desc = name
  13.     def __and__(self, o):
  14.         n = P(self.test, self.desc+"&"+o.desc)
  15.         n.test = ja(n.test, o.test)
  16.         return n
  17.     def __or__(self, o):
  18.         n = P(self.test, '('+self.desc+"|"+o.desc+')')
  19.         n.test = tai(n.test, o.test)
  20.         return n
  21.     def __call__(self, inp):
  22.         print self.desc
  23.         return self.test(inp)
  24.  
  25. ###############################
  26. # Language grammar definition #
  27. ###############################
  28.  
  29. cra    = lambda a,b: set(chr(i) for i in range(ord(a), ord(b)+1))
  30. letter = cra('a','z')|cra('A','Z')|set('_')
  31. digit  = cra('0','9')
  32.  
  33. term   = lambda a: P(lue(a), '"'+str(a)[:1]+'"')
  34. word   = term(letter) & P(lambda i: word(i)) | term(letter)
  35. digits = term(digit) & P(lambda i: digits(i)) | term(digit)
  36. number = term('-') & digits | digits
  37. ws     = term(' ') & P(lambda i: ws(i)) | term(' ')
  38. code_  = word | number | ws | P(lambda i: block(i))
  39. code   = code_ & P(lambda i: code(i)) | code_
  40. block  = term('[') & code & term(']') | (term('[') & term(']'))
  41.  
  42. ###########
  43. # Testing #
  44. ###########
  45.  
  46. print word("abSDFf_kj%")
  47. print code("-034 num %")
  48. print code("034 kd[dfd [123 dflkj -340] [] 3498]%")
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement