Ruby 2.x 源代碼學習:語法分析 & 中間代碼生成 之 概述

前言

入口

rb_iseq_compile_with_option 函數是語法分析與中間代碼生成的入口,這裏僅列出和語法分析 & 中間代碼生成相關的代碼塊node

// iseq.c

rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE absolute_path, VALUE line,
    const struct rb_block *base_block, VALUE opt) {
    ...
    // 聲明一個函數指針 parse
    NODE *(*parse)(VALUE parser, VALUE fame, VALUE file, int start);
    // 語法分析樹根節點
    NODE *INITIALIZED node;
    if (RB_TYPE_P(src, T_FILE)) {
        parse = rb_parser_compile_file_path;
    } else {
        parse = rb_parser_compile_string_path;
    }
    // 建立語法分析器對象
    const VALUE parser = rb_parser_new();
    rb_parser_set_context(parser, base_block, FALSE);
    // 調用 parse 函數指針指向的語法分析函數,返回 AST 根節點
    node = (*parse)(parser, file, src, ln);
    iseq = rb_iseq_new_with_opt(node, label, file, absolute_path, line, parent, type, &option);
    return iseq;
}

語法分析

rb_parser_compile_file_path

rb_parser_compile_string_path

該函數用於解析一段包含 Ruby 源代碼的字符串:segmentfault

// ripper.c

NODE* rb_parser_compile_string_path(VALUE vparser, VALUE f, VALUE s, int line)
{
    must_be_ascii_compatible(s);
    return parser_compile_string(vparser, f, s, line);
}

簡單起見,咱們直接列出 parser_compile_string 的調用棧ruby

parser_compile_string @ ripper.c
    yycompile @ ripper.c
        yycompile0 @ ripper.c

yycompile0 會調用 yyparse(其實是 ruby_yyparse 的宏定義),進入 YACC 語法分析器自動生成的代碼數據結構

中間代碼生成

rb_iseq_new_with_opt

rb_iseq_new_with_opt 函數根據語法分析生成的 AST 生成中間代碼並保存在 rb_iseq_t 結構體中,詳細部分能夠參考Ruby 2.x 源代碼分析:語法分析 & 中間代碼生成 之 數據結構函數

相關文章
相關標籤/搜索