Advertisement
Guest User

Eike Welk

a guest
Sep 23rd, 2008
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. #try the indentedBlock helper function
  2.  
  3. from pyparsing import *
  4.  
  5. #-------------------------------------------------------
  6. #enable packrat parsing and the parser won't work
  7. #ParserElement.enablePackrat()
  8. #-------------------------------------------------------
  9.  
  10. stack = [1]
  11. ParserElement.setDefaultWhitespaceChars('\t ')
  12. newline = LineEnd().suppress()
  13. #need to forward declare block of statements
  14. suite = Forward()
  15.  
  16. #simple statements
  17. print_stmt = Group(Keyword('print') - ZeroOrMore(Word(alphas)))
  18. foo_stmt = Group(Keyword('foo') - ZeroOrMore(Word(alphas)))
  19. #compound statements
  20. if_stmt = Group(Keyword('if') - Word(alphas) + ':' + suite )
  21.  
  22. simple_stmt = print_stmt | foo_stmt
  23. compound_stmt = if_stmt
  24. #simple statements are terminated by newline
  25. #while the indented block eats all newlines after the compound statement
  26. statement = simple_stmt + newline | compound_stmt
  27. #a suite is an indented block of statements
  28. suite << indentedBlock(statement, stack)
  29.  
  30.  
  31. program = indentedBlock(statement, stack, False) + stringEnd
  32.  
  33.  
  34. prog1 = \
  35. '''
  36. foo aaa
  37. print bar ooo
  38. '''
  39. print program.parseString(prog1)
  40.  
  41. prog2 = \
  42. '''
  43. print start
  44. if test:
  45.    print aaa
  46. if test:
  47.    print bbb
  48. print end
  49. '''
  50. print program.parseString(prog2)
  51.  
  52. prog2 = \
  53. '''
  54. print start
  55. if test:
  56.    print aaa
  57.    if test:
  58.        print bbb
  59.    print ccc
  60. print end
  61. '''
  62. print program.parseString(prog2)
  63.  
  64.  
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement