识别缩进块的Lexer

时间:2011-08-01 19:28:54

标签: python compiler-construction whitespace lexer

我想为一种语言编写一个编译器,该语言表示带有空格的程序块,就像在Python中一样。我更喜欢在Python中这样做,但C ++也是一种选择。有没有一个开源词法分析器可以帮助我轻松地做到这一点,例如通过像Python词法分析器那样正确生成INDENT和DEDENT标识符?相应的解析器生成器将是一个加号。

2 个答案:

答案 0 :(得分:4)

LEPL是纯Python,支持越位解析。

答案 1 :(得分:1)

如果您使用像lex这样的东西,可以这样做:

^[ \t]+              { int new_indent = count_indent(yytext);
                       if (new_indent > current_indent) {
                          current_indent = new_indent;
                          return INDENT;
                       } else if (new_indent < current_indent) {
                          current_indent = new_indent;
                          return DEDENT;
                       }
                       /* Else do nothing, and this way
                          you can essentially treat INDENT and DEDENT
                          as opening and closing braces. */
                     }

您可能需要一些额外的逻辑,例如忽略空行,并在需要时自动在文件末尾添加DEDENT。

据推测,count_indent会考虑根据制表位值将制表符转换为空格。

我不知道Python的词法分析器/解析器生成器,但我发布的内容应该与lex / flex一起使用,你可以将它连接到yacc / bison来创建一个解析器。你可以使用C或C ++。