这是Python语法的一个子集:
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: pass_stmt
pass_stmt: 'pass'
compound_stmt: if_stmt
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
Run Code Online (Sandbox Code Playgroud)
(您可以在Python SVN存储库中阅读完整语法:http://svn.python.org/.../Grammar)
我试图用这个语法在Python中生成Python的解析器.我遇到的问题是如何将这些INDENT和DEDENT令牌表达为pyparsing对象.
以下是我实现其他终端的方法:
import pyparsing as p
string_start = (p.Literal('"""') | "'''" | '"' | "'")
string_token = ('\\' + p.CharsNotIn("",exact=1) | p.CharsNotIn('\\',exact=1))
string_end = p.matchPreviousExpr(string_start)
terminals = …Run Code Online (Sandbox Code Playgroud)