10. 完整的语法规范

这是完整的Python语法,它被送入解析器生成器,以生成解析Python源文件的解析器:

  1. # Grammar for Python
  2. # NOTE WELL: You should also follow all the steps listed at
  3. # https://devguide.python.org/grammar/
  4. # Start symbols for the grammar:
  5. # single_input is a single interactive statement;
  6. # file_input is a module or sequence of commands read from an input file;
  7. # eval_input is the input for the eval() functions.
  8. # NB: compound_stmt in single_input is followed by extra NEWLINE!
  9. single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  10. file_input: (NEWLINE | stmt)* ENDMARKER
  11. eval_input: testlist NEWLINE* ENDMARKER
  12. decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  13. decorators: decorator+
  14. decorated: decorators (classdef | funcdef | async_funcdef)
  15. async_funcdef: ASYNC funcdef
  16. funcdef: 'def' NAME parameters ['->' test] ':' suite
  17. parameters: '(' [typedargslist] ')'
  18. typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
  19. '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
  20. | '**' tfpdef [',']]]
  21. | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
  22. | '**' tfpdef [','])
  23. tfpdef: NAME [':' test]
  24. varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
  25. '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
  26. | '**' vfpdef [',']]]
  27. | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
  28. | '**' vfpdef [',']
  29. )
  30. vfpdef: NAME
  31. stmt: simple_stmt | compound_stmt
  32. simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
  33. small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
  34. import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
  35. expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
  36. ('=' (yield_expr|testlist_star_expr))*)
  37. annassign: ':' test ['=' test]
  38. testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
  39. augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
  40. '<<=' | '>>=' | '**=' | '//=')
  41. # For normal and annotated assignments, additional restrictions enforced by the interpreter
  42. del_stmt: 'del' exprlist
  43. pass_stmt: 'pass'
  44. flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
  45. break_stmt: 'break'
  46. continue_stmt: 'continue'
  47. return_stmt: 'return' [testlist]
  48. yield_stmt: yield_expr
  49. raise_stmt: 'raise' [test ['from' test]]
  50. import_stmt: import_name | import_from
  51. import_name: 'import' dotted_as_names
  52. # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
  53. import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
  54. 'import' ('*' | '(' import_as_names ')' | import_as_names))
  55. import_as_name: NAME ['as' NAME]
  56. dotted_as_name: dotted_name ['as' NAME]
  57. import_as_names: import_as_name (',' import_as_name)* [',']
  58. dotted_as_names: dotted_as_name (',' dotted_as_name)*
  59. dotted_name: NAME ('.' NAME)*
  60. global_stmt: 'global' NAME (',' NAME)*
  61. nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
  62. assert_stmt: 'assert' test [',' test]
  63. compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
  64. async_stmt: ASYNC (funcdef | with_stmt | for_stmt)
  65. if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  66. while_stmt: 'while' test ':' suite ['else' ':' suite]
  67. for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
  68. try_stmt: ('try' ':' suite
  69. ((except_clause ':' suite)+
  70. ['else' ':' suite]
  71. ['finally' ':' suite] |
  72. 'finally' ':' suite))
  73. with_stmt: 'with' with_item (',' with_item)* ':' suite
  74. with_item: test ['as' expr]
  75. # NB compile.c makes sure that the default except clause is last
  76. except_clause: 'except' [test ['as' NAME]]
  77. suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
  78. test: or_test ['if' or_test 'else' test] | lambdef
  79. test_nocond: or_test | lambdef_nocond
  80. lambdef: 'lambda' [varargslist] ':' test
  81. lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
  82. or_test: and_test ('or' and_test)*
  83. and_test: not_test ('and' not_test)*
  84. not_test: 'not' not_test | comparison
  85. comparison: expr (comp_op expr)*
  86. # <> isn't actually a valid comparison operator in Python. It's here for the
  87. # sake of a __future__ import described in PEP 401 (which really works :-)
  88. comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  89. star_expr: '*' expr
  90. expr: xor_expr ('|' xor_expr)*
  91. xor_expr: and_expr ('^' and_expr)*
  92. and_expr: shift_expr ('&' shift_expr)*
  93. shift_expr: arith_expr (('<<'|'>>') arith_expr)*
  94. arith_expr: term (('+'|'-') term)*
  95. term: factor (('*'|'@'|'/'|'%'|'//') factor)*
  96. factor: ('+'|'-'|'~') factor | power
  97. power: atom_expr ['**' factor]
  98. atom_expr: [AWAIT] atom trailer*
  99. atom: ('(' [yield_expr|testlist_comp] ')' |
  100. '[' [testlist_comp] ']' |
  101. '{' [dictorsetmaker] '}' |
  102. NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
  103. testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
  104. trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
  105. subscriptlist: subscript (',' subscript)* [',']
  106. subscript: test | [test] ':' [test] [sliceop]
  107. sliceop: ':' [test]
  108. exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
  109. testlist: test (',' test)* [',']
  110. dictorsetmaker: ( ((test ':' test | '**' expr)
  111. (comp_for | (',' (test ':' test | '**' expr))* [','])) |
  112. ((test | star_expr)
  113. (comp_for | (',' (test | star_expr))* [','])) )
  114. classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
  115. arglist: argument (',' argument)* [',']
  116. # The reason that keywords are test nodes instead of NAME is that using NAME
  117. # results in an ambiguity. ast.c makes sure it's a NAME.
  118. # "test '=' test" is really "keyword '=' test", but we have no such token.
  119. # These need to be in a single rule to avoid grammar that is ambiguous
  120. # to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
  121. # we explicitly match '*' here, too, to give it proper precedence.
  122. # Illegal combinations and orderings are blocked in ast.c:
  123. # multiple (test comp_for) arguments are blocked; keyword unpackings
  124. # that precede iterable unpackings are blocked; etc.
  125. argument: ( test [comp_for] |
  126. test '=' test |
  127. '**' test |
  128. '*' test )
  129. comp_iter: comp_for | comp_if
  130. comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
  131. comp_if: 'if' test_nocond [comp_iter]
  132. # not used in grammar, but may appear in "node" passed from Parser to Compiler
  133. encoding_decl: NAME
  134. yield_expr: 'yield' [yield_arg]
  135. yield_arg: 'from' test | testlist