2012-04-10 91 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,這可能不是正確的語法。