不能完全弄清楚它正在处理名单列表或者设置列表或套等名单..
它不区分套或列表什么:
atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [listmaker] ']' |
'{' [dictorsetmaker] '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+)
他们处理你所描述的递归的方式是listmaker
,dictorsetmaker
等最终可能包含。例如:
listmaker: test (list_for | (',' test)* [','])
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom trailer* ['**' factor]
有很多中间体;那是因为他们需要为一堆数学运算符建立优先级。然后list_for
,它允许添加列表理解额外的东西。
一个更简单的例子可能是:
atom: ('[' [list_or_set] ']' |
'{' [list_or_set] '}' |
NAME | NUMBER | STRING+)
list_or_set: atom (',' atom)* [',']
或者,如果你想列表之间的区别,并设置在这个级别进行:
atom: list | set | NAME | NUMBER | STRING+
list: '[' atom (',' atom)* [','] ']'
set: '{' atom (',' atom)* [','] '}'
“它不区分”是错的;当然,还有单独的'listmaker'和'dictorsetmaker'产品,解析器可以依靠它来构建AST,而不必重新检查括号来找出它的含义。 – 2012-04-10 03:20:12