文法基于 Python 3.6 做了一些简化。
Python 3.6 语法官方文档:Python语言参考
literal ::= str | int | float | true | false | none
atom ::= identifier | literal | "(" expression ")"
primary ::= attributeref | subscription | call | atom
attributeref ::= primary "." identifier
subscription ::= primary "[" expr_list "]"
call ::= primary "(" [expr_list] ")"
expr_list ::= expr {"," expr}
消除左递归:
primary ::= atom {"." identifier | "[" expr_list "]" | "(" [expr_list] ")"}
expr_list ::= expr {"," expr}
power ::= primary ["**" u_expr]
u_expr ::= "-" u_expr | "+" u_expr | "~" u_expr | power
m_expr ::= m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr | m_expr "%" u_expr | u_expr
a_expr ::= a_expr "+" m_expr | a_expr "-" m_expr | m_expr
消除左递归:
m_expr ::= u_expr {"*" u_expr | "//" u_expr | "/" u_expr |"%" u_expr}
a_expr ::= m_expr {"+" m_expr | "-" m_expr}
shift_expr ::= shift_expr "<<" a_expr | shift_expr ">>" a_expr | a_expr
and_expr ::= and_expr "&" shift_expr | shift_expr
xor_expr ::= xor_expr "^" and_expr | and_expr
or_expr ::= or_expr "|" xor_expr | xor_expr
消除左递归:
shift_expr ::= a_expr {"<<" a_expr | ">>" a_expr}
and_expr ::= shift_expr {"&" shift_expr}
xor_expr ::= and_expr {"^" and_expr}
or_expr ::= xor_expr {"|" xor_expr}
comparison ::= comparison comp_operator or_expr | or_expr
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!=" | "is"
消除左递归:
comparison ::= or_expr {comp_operator or_expr}
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!=" | "is"
not_test ::= "not" not_test | comparison
and_test ::= and_test "and" not_test | not_test
or_test ::= or_test "or" and_test | and_test
expression ::= or_test
消除左递归:
not_test ::= "not" not_test | comparison
and_test ::= not_test {"and" not_test}
or_test ::= and_test {"or" and_test}
expression ::= expression
自上而下,优先级从高到低。
运算符 | 描述 |
---|---|
x[index] , x(args...) , x.attr |
索引、调用、属性引用 |
** |
幂运算 |
+x , -x , ~x |
正、负、按位取反 |
* , // , / , % |
乘、整除、除、取余 |
+ , - |
加、减 |
<< , >> |
左移、右移 |
& |
按位与 |
^ |
按位异或 |
| |
按位或 |
< , <= , > , >= , != , == , is |
各种比较运算 |
not x |
逻辑非 |
and |
逻辑与 |
or |
逻辑或 |
simple_stmt ::= expression_stmt | assign_stmt | pass_stmt | return_stmt | break_stmt | continue_stmt | global_stmt
expression_stmt ::= expression newline
assign_stmt ::= target "=" expression newline
target ::= identifier | attributeref | subscription
pass_stmt ::= "pass" newline
return_stmt ::= "return" [expression] newline
break_stmt ::= "break" newline
continue_stmt ::= "continue" newline
global_stmt ::= "global" identifier_list
identifier_list ::= identifier {"," identifier}
compound_stmt ::= if_stmt | while_stmt | funcdef
suite ::= indent_inc statement {statement} indent_dec
statement ::= compound_stmt | simple_stmt
if_stmt ::= "if" expression ":" newline suite
{"elif" expression ":" newline suite}
["else" ":" newline suite]
while_stmt ::= "while" expression ":" newline suite
funcdef ::= "def" identifier "(" [parameter_list] ")" ":" newline suite
parameter_list ::= identifier {"," identifier}
program ::= {statement}