MRI Ruby 1.9.2中的词法分析

时间:2010-10-25 16:22:19

标签: ruby compiler-construction lexer

我正在学习一些编译器理论和实践。 Ruby是我每天选择的语言,所以我去看看它的词法分析器和解析语法。红宝石有没有单独的词法分析器?如果是这样,它在哪个文件中描述?

1 个答案:

答案 0 :(得分:1)

在ruby源中有parse.y文件,其中包含语法。我相对肯定ruby使用单独的词法分析器(像大多数LR解析器一样)。似乎词法分析者也是有状态的:

enum lex_state_e {
EXPR_BEG,           /* ignore newline, +/- is a sign. */
EXPR_END,           /* newline significant, +/- is an operator. */
EXPR_ENDARG,        /* ditto, and unbound braces. */
EXPR_ARG,           /* newline significant, +/- is an operator. */
EXPR_CMDARG,        /* newline significant, +/- is an operator. */
EXPR_MID,           /* newline significant, +/- is an operator. */
EXPR_FNAME,         /* ignore newline, no reserved words. */
EXPR_DOT,           /* right after `.' or `::', no reserved words. */
EXPR_CLASS,         /* immediate after `class', no here document. */
EXPR_VALUE          /* alike EXPR_BEG but label is disallowed. */
};

我认为这是必要的,因为在某些情况下会忽略换行符,而在其他情况下,它会终止表达式等。“class”也不总是像在'x.class'中。

但我不是专家。

编辑:在parse.y文件中深入查看词法分析器并不完全独立于解析器:

superclass  : //[...]
    | '<'
        {
        lex_state = EXPR_BEG;
        }