BNF语法为python样式结构

时间:2012-04-10 01:01:34

标签: python antlr context-free-grammar bnf

我正在尝试使用简单的语法来解析类似python的结构,这就是我能为列表/集合提出的

list : '[' atom ( ',' atom)* ']'
set : '(' atom ( ',' atom)* ']'

atom : 'a'..'z' | 'A'..'Z'
     | '[' list ']'
     | '(' set ')'

请注意,这是在antlr,我想知道它的正确性和任何可以帮助我的资源

我确实看过python'语法http://docs.python.org/reference/grammar.html,但无法弄清楚它是处理列表列表或列表集还是列表等等。

任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

  

无法弄清楚它是处理列表或列表集或集合列表等。

它不区分列表与集合或其他:

atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [listmaker] ']' |
       '{' [dictorsetmaker] '}' |
       '`' testlist1 '`' |
       NAME | NUMBER | STRING+)

他们处理您所描述的排序递归的方式是listmakerdictorsetmaker等最终可能包含atom。例如:

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)* [','] '}'

答案 1 :(得分:1)

这可能更接近您的目标:

list : '[' element ( ',' element )* ']';
set : '(' element ( ',' element )* ')';

element: list | set | atom;

alpha:  'a'..'z' | 'A'..'Z' | '_' ;
alphanum: alpha | '0'..'9';
atom : alpha alphanum*;

注意:以前从未使用过antlr,这可能不是正确的语法。