pythonGrammarParser.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # pythonGrammarParser.py
  2. #
  3. # Copyright, 2006, by Paul McGuire
  4. #
  5. from pyparsing import *
  6. # should probably read this from the Grammar file provided with the Python source, but
  7. # this just skips that step and inlines the bnf text directly - this grammar was taken from
  8. # Python 2.4.1
  9. #
  10. grammar = r"""
  11. # Grammar for Python
  12. # Note: Changing the grammar specified in this file will most likely
  13. # require corresponding changes in the parser module
  14. # (../Modules/parsermodule.c). If you can't make the changes to
  15. # that module yourself, please co-ordinate the required changes
  16. # with someone who can; ask around on python-dev for help. Fred
  17. # Drake <fdrake@acm.org> will probably be listening there.
  18. # Commands for Kees Blom's railroad program
  19. #diagram:token NAME
  20. #diagram:token NUMBER
  21. #diagram:token STRING
  22. #diagram:token NEWLINE
  23. #diagram:token ENDMARKER
  24. #diagram:token INDENT
  25. #diagram:output\input python.bla
  26. #diagram:token DEDENT
  27. #diagram:output\textwidth 20.04cm\oddsidemargin 0.0cm\evensidemargin 0.0cm
  28. #diagram:rules
  29. # Start symbols for the grammar:
  30. # single_input is a single interactive statement;
  31. # file_input is a module or sequence of commands read from an input file;
  32. # eval_input is the input for the eval() and input() functions.
  33. # NB: compound_stmt in single_input is followed by extra NEWLINE!
  34. single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  35. file_input: (NEWLINE | stmt)* ENDMARKER
  36. eval_input: testlist NEWLINE* ENDMARKER
  37. decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  38. decorators: decorator+
  39. funcdef: [decorators] 'def' NAME parameters ':' suite
  40. parameters: '(' [varargslist] ')'
  41. varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) | fpdef ['=' test] (',' fpdef ['=' test])* [',']
  42. fpdef: NAME | '(' fplist ')'
  43. fplist: fpdef (',' fpdef)* [',']
  44. stmt: simple_stmt | compound_stmt
  45. simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
  46. small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | exec_stmt | assert_stmt
  47. expr_stmt: testlist (augassign testlist | ('=' testlist)*)
  48. augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//='
  49. # For normal assignments, additional restrictions enforced by the interpreter
  50. print_stmt: 'print' ( [ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ] )
  51. del_stmt: 'del' exprlist
  52. pass_stmt: 'pass'
  53. flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
  54. break_stmt: 'break'
  55. continue_stmt: 'continue'
  56. return_stmt: 'return' [testlist]
  57. yield_stmt: 'yield' testlist
  58. raise_stmt: 'raise' [test [',' test [',' test]]]
  59. import_stmt: import_name | import_from
  60. import_name: 'import' dotted_as_names
  61. import_from: 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
  62. import_as_name: NAME [NAME NAME]
  63. dotted_as_name: dotted_name [NAME NAME]
  64. import_as_names: import_as_name (',' import_as_name)* [',']
  65. dotted_as_names: dotted_as_name (',' dotted_as_name)*
  66. dotted_name: NAME ('.' NAME)*
  67. global_stmt: 'global' NAME (',' NAME)*
  68. exec_stmt: 'exec' expr ['in' test [',' test]]
  69. assert_stmt: 'assert' test [',' test]
  70. #35
  71. compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  72. if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  73. while_stmt: 'while' test ':' suite ['else' ':' suite]
  74. for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
  75. try_stmt: ('try' ':' suite (except_clause ':' suite)+ #diagram:break
  76. ['else' ':' suite] | 'try' ':' suite 'finally' ':' suite)
  77. # NB compile.c makes sure that the default except clause is last
  78. except_clause: 'except' [test [',' test]]
  79. suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
  80. test: and_test ('or' and_test)* | lambdef
  81. and_test: not_test ('and' not_test)*
  82. not_test: 'not' not_test | comparison
  83. comparison: expr (comp_op expr)*
  84. comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  85. expr: xor_expr ('|' xor_expr)*
  86. xor_expr: and_expr ('^' and_expr)*
  87. and_expr: shift_expr ('&' shift_expr)*
  88. shift_expr: arith_expr (('<<'|'>>') arith_expr)*
  89. arith_expr: term (('+'|'-') term)*
  90. term: factor (('*'|'/'|'%'|'//') factor)*
  91. factor: ('+'|'-'|'~') factor | power
  92. power: atom trailer* ['**' factor]
  93. atom: '(' [testlist_gexp] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+
  94. listmaker: test ( list_for | (',' test)* [','] )
  95. testlist_gexp: test ( gen_for | (',' test)* [','] )
  96. lambdef: 'lambda' [varargslist] ':' test
  97. trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
  98. subscriptlist: subscript (',' subscript)* [',']
  99. subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
  100. sliceop: ':' [test]
  101. exprlist: expr (',' expr)* [',']
  102. testlist: test (',' test)* [',']
  103. testlist_safe: test [(',' test)+ [',']]
  104. dictmaker: test ':' test (',' test ':' test)* [',']
  105. classdef: 'class' NAME ['(' testlist ')'] ':' suite
  106. arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
  107. argument: [test '='] test [gen_for] # Really [keyword '='] test
  108. list_iter: list_for | list_if
  109. list_for: 'for' exprlist 'in' testlist_safe [list_iter]
  110. list_if: 'if' test [list_iter]
  111. gen_iter: gen_for | gen_if
  112. gen_for: 'for' exprlist 'in' test [gen_iter]
  113. gen_if: 'if' test [gen_iter]
  114. testlist1: test (',' test)*
  115. # not used in grammar, but may appear in "node" passed from Parser to Compiler
  116. encoding_decl: NAME
  117. """
  118. class SemanticGroup(object):
  119. def __init__(self,contents):
  120. self.contents = contents
  121. while self.contents[-1].__class__ == self.__class__:
  122. self.contents = self.contents[:-1] + self.contents[-1].contents
  123. def __str__(self):
  124. return "{0}({1})".format(self.label,
  125. " ".join([isinstance(c,str) and c or str(c) for c in self.contents]) )
  126. class OrList(SemanticGroup):
  127. label = "OR"
  128. pass
  129. class AndList(SemanticGroup):
  130. label = "AND"
  131. pass
  132. class OptionalGroup(SemanticGroup):
  133. label = "OPT"
  134. pass
  135. class Atom(SemanticGroup):
  136. def __init__(self,contents):
  137. if len(contents) > 1:
  138. self.rep = contents[1]
  139. else:
  140. self.rep = ""
  141. if isinstance(contents,str):
  142. self.contents = contents
  143. else:
  144. self.contents = contents[0]
  145. def __str__(self):
  146. return "{0}{1}".format(self.rep, self.contents)
  147. def makeGroupObject(cls):
  148. def groupAction(s,l,t):
  149. try:
  150. return cls(t[0].asList())
  151. except Exception:
  152. return cls(t)
  153. return groupAction
  154. # bnf punctuation
  155. LPAREN = Suppress("(")
  156. RPAREN = Suppress(")")
  157. LBRACK = Suppress("[")
  158. RBRACK = Suppress("]")
  159. COLON = Suppress(":")
  160. ALT_OP = Suppress("|")
  161. # bnf grammar
  162. ident = Word(alphanums+"_")
  163. bnfToken = Word(alphanums+"_") + ~FollowedBy(":")
  164. repSymbol = oneOf("* +")
  165. bnfExpr = Forward()
  166. optionalTerm = Group(LBRACK + bnfExpr + RBRACK).setParseAction(makeGroupObject(OptionalGroup))
  167. bnfTerm = ( (bnfToken | quotedString | optionalTerm | ( LPAREN + bnfExpr + RPAREN )) + Optional(repSymbol) ).setParseAction(makeGroupObject(Atom))
  168. andList = Group(bnfTerm + OneOrMore(bnfTerm)).setParseAction(makeGroupObject(AndList))
  169. bnfFactor = andList | bnfTerm
  170. orList = Group( bnfFactor + OneOrMore( ALT_OP + bnfFactor ) ).setParseAction(makeGroupObject(OrList))
  171. bnfExpr << ( orList | bnfFactor )
  172. bnfLine = ident + COLON + bnfExpr
  173. bnfComment = "#" + restOfLine
  174. # build return tokens as a dictionary
  175. bnf = Dict(OneOrMore(Group(bnfLine)))
  176. bnf.ignore(bnfComment)
  177. # bnf is defined, parse the grammar text
  178. bnfDefs = bnf.parseString(grammar)
  179. # correct answer is 78
  180. expected = 78
  181. assert len(bnfDefs) == expected, \
  182. "Error, found %d BNF defns, expected %d" % (len(bnfDefs), expected)
  183. # list out defns in order they were parsed (to verify accuracy of parsing)
  184. for k,v in bnfDefs:
  185. print(k,"=",v)
  186. print()
  187. # list out parsed grammar defns (demonstrates dictionary access to parsed tokens)
  188. for k in list(bnfDefs.keys()):
  189. print(k,"=",bnfDefs[k])