python - python 样式结构的 BNF 语法

标签 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但不能完全弄清楚它正在处理列表列表或列表集或列表集等。

如有任何帮助,我们将不胜感激。

最佳答案

couldn't quite figure out it was handling list of lists or set of lists or list of sets etc..

它不区分列表和集合或其他任何东西:

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

关于python - python 样式结构的 BNF 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081767/

相关文章:

python - 如何查找 Python 包的依赖项

parsing - ANTLR4:TokenStreamRewriter输出的格式不正确(删除了空格)

antlr - 您可以有条件地更改 ANTLR 词法分析器模式吗?

python - 使用 pyparsing Forward() 和多个规则来查找回文序列

regex - 将上下文无关的语法转换为正则表达式

Python - 发生意外导入

python - 从 azure blob 并行读取多个文件

python - Matplotlib 类似于 matlab trisurf

java - ANTLR:错误恢复和报告

context-free-grammar - 确定给定的语言是否为常规/上下文无关/非上下文无关