簡體   English   中英

python 樣式結構的 BNF 文法

[英]BNF Grammar for python style structures

我正在嘗試使用一個簡單的語法來解析 python 之類的結構,這就是我可以為列表/集合想出的

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

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

請注意,這是在 antlr 中,我想知道它的正確性和任何可以幫助我的資源

我確實看過 python 的語法http://docs.python.org/reference/grammar.html但不太明白它是在處理列表列表或列表集或列表集等。

任何幫助將不勝感激。

無法完全弄清楚它正在處理列表列表或列表集或集合列表等。

它不區分列表和集合或其他任何東西:

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

這可能更接近你所追求的:

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

element: list | set | atom;

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

注意:之前從未使用過 antlr,這可能不是正確的語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM