2012-04-10 87 views
1

我想一个简单的语法解析蟒状结构,这是我能想出了一个列表/套BNF语法为Python风格结构

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

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

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

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

任何帮助将不胜感激。

回答

3

不能完全弄清楚它正在处理名单列表或者设置列表或套等名单..

它不区分套或列表什么:

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

“它不区分”是错的;当然,还有单独的'listmaker'和'dictorsetmaker'产品,解析器可以依靠它来构建AST,而不必重新检查括号来找出它的含义。 – 2012-04-10 03:20:12

1

这可能是更接近你所追求的:

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

element: list | set | atom; 

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

注:从来没有使用过ANTLR,这可能不是正确的语法。