如何用pyparsing解析缩进和取消缩进?
这里是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
(你可以在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 = {
'NEWLINE': p.Literal('\n').setWhitespaceChars(' \t')
.setName('NEWLINE').setParseAction(terminal_action('NEWLINE')),
'ENDMARKER': p.stringEnd.copy().setWhitespaceChars(' \t')
.setName('ENDMARKER').setParseAction(terminal_action('ENDMARKER')),
'NAME': (p.Word(p.alphas + "_", p.alphanums + "_", asKeyword=True))
.setName('NAME').setParseAction(terminal_action('NAME')),
'NUMBER': p.Combine(
p.Word(p.nums) + p.CaselessLiteral("l") |
(p.Word(p.nums) + p.Optional("." + p.Optional(p.Word(p.nums))) | "." + p.Word(p.nums)) +
p.Optional(p.CaselessLiteral("e") + p.Optional(p.Literal("+") | "-") + p.Word(p.nums)) +
p.Optional(p.CaselessLiteral("j"))
).setName('NUMBER').setParseAction(terminal_action('NUMBER')),
'STRING': p.Combine(
p.Optional(p.CaselessLiteral('u')) +
p.Optional(p.CaselessLiteral('r')) +
string_start + p.ZeroOrMore(~string_end + string_token) + string_end
).setName('STRING').setParseAction(terminal_action('STRING')),
# I can't find a good way of parsing indents/dedents.
# The Grammar just has the tokens NEWLINE, INDENT and DEDENT scattered accross the rules.
# A single NEWLINE would be translated to NEWLINE + PEER (from pyparsing.indentedBlock()), unless followed by INDENT or DEDENT
# That NEWLINE and IN/DEDENT could be spit across rule boundaries. (see the 'suite' rule)
'INDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('INDENT'),
'DEDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('DEDENT')
}
terminal_action
是一个函数,它根据传入的参数返回相应的解析动作。
我知道有pyparsing.indentedBlock
这个辅助函数,但我不知道如何在没有PEER
标记的情况下将其应用到语法中。
(你可以查看pyparsing的源代码,了解我在说什么)
你可以在这里查看我的完整源代码:http://pastebin.ca/1609860
1 个回答
11
在pyparsing的维基上,有几个例子可以帮助你理解,具体可以去这个例子页面看看:
如果你想使用pyparsing的indentedBlock
,我觉得你可以这样定义suite
:
indentstack = [1]
suite = indentedBlock(stmt, indentstack, True)
需要注意的是,indentedGrammarExample.py
是在pyparsing加入indentedBlock
之前就存在的,所以它有自己处理缩进解析的实现。