indentedGrammarExample.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # indentedGrammarExample.py
  2. #
  3. # Copyright (c) 2006,2016 Paul McGuire
  4. #
  5. # A sample of a pyparsing grammar using indentation for
  6. # grouping (like Python does).
  7. #
  8. # Updated to use indentedBlock helper method.
  9. #
  10. from pyparsing import *
  11. data = """\
  12. def A(z):
  13. A1
  14. B = 100
  15. G = A2
  16. A2
  17. A3
  18. B
  19. def BB(a,b,c):
  20. BB1
  21. def BBA():
  22. bba1
  23. bba2
  24. bba3
  25. C
  26. D
  27. def spam(x,y):
  28. def eggs(z):
  29. pass
  30. """
  31. indentStack = [1]
  32. stmt = Forward()
  33. suite = indentedBlock(stmt, indentStack)
  34. identifier = Word(alphas, alphanums)
  35. funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
  36. funcDef = Group( funcDecl + suite )
  37. rvalue = Forward()
  38. funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
  39. rvalue << (funcCall | identifier | Word(nums))
  40. assignment = Group(identifier + "=" + rvalue)
  41. stmt << ( funcDef | assignment | identifier )
  42. module_body = OneOrMore(stmt)
  43. print(data)
  44. parseTree = module_body.parseString(data)
  45. parseTree.pprint()