2009-10-10 68 views
9

这里是Python语法的一个子集:如何使用pyparsing解析缩进和缩进?

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中。我遇到的问题是如何将INDENTDEDENT标记表示为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 souce code,看看我说的)

你可以看到我的完整的源代码在这里:http://pastebin.ca/1609860

回答

10

有一对夫妇的例子在pyparsing维基Examples page,可以给你一些见解:

要使用pyparsing的indentedBlock,我想你会定义suite为:

indentstack = [1] 
suite = indentedBlock(stmt, indentstack, True) 

注意indentedGrammarExample.py预日期列入在pyparsing indentedBlock,她在自己的缩进解析的FPGA实现。