In Files

  • ast.c

Namespace

Class/Module Index [+]

Quicksearch

RubyVM::AST

AST provides methods to parse Ruby code into abstract syntax trees. The nodes in the tree are instances of RubyVM::AST::Node.

Public Class Methods

of(p1) click to toggle source
 
               static VALUE
rb_ast_s_of(VALUE module, VALUE body)
{
    VALUE path, node;
    int node_id;
    const rb_iseq_t *iseq = NULL;

    if (rb_obj_is_proc(body)) {
        iseq = vm_proc_iseq(body);

        if (!rb_obj_is_iseq((VALUE)iseq)) {
            iseq = NULL;
        }
    }
    else {
        iseq = rb_method_iseq(body);
    }

    if (!iseq) return Qnil;

    path = rb_iseq_path(iseq);
    node_id = iseq->body->location.node_id;
    node = rb_ast_s_parse_file(module, path);

    return node_find(node, node_id);
}
            
RubyVM::AST.parse(string) → RubyVM::AST::Node click to toggle source

Parses the given string into an abstract syntax tree, returning the root node of that tree.

SyntaxError is raised if the given string is invalid syntax.

RubyVM::AST.parse("x = 1 + 2")
# => #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 1:9): >
 
               static VALUE
rb_ast_s_parse(VALUE module, VALUE str)
{
    VALUE obj;
    rb_ast_t *ast = 0;

    const VALUE parser = rb_parser_new();

    str = rb_check_string_type(str);
    rb_parser_set_context(parser, NULL, 0);
    ast = rb_parser_compile_string_path(parser, rb_str_new_cstr("no file name"), str, 1);

    if (!ast->body.root) {
        rb_ast_dispose(ast);
        rb_exc_raise(GET_EC()->errinfo);
    }

    obj = ast_new_internal(ast, (NODE *)ast->body.root);

    return obj;
}
            
RubyVM::AST.parse_file(pathname) → RubyVM::AST::Node click to toggle source

Reads the file from pathname, then parses it like ::parse, returning the root node of the abstract syntax tree.

SyntaxError is raised if pathname's contents are not valid Ruby syntax.

RubyVM::AST.parse_file("my-app/app.rb")
# => #<RubyVM::AST::Node(NODE_SCOPE(0) 1:0, 31:3): >
 
               static VALUE
rb_ast_s_parse_file(VALUE module, VALUE path)
{
    VALUE obj, f;
    rb_ast_t *ast = 0;
    rb_encoding *enc = rb_utf8_encoding();

    const VALUE parser = rb_parser_new();

    FilePathValue(path);
    f = rb_file_open_str(path, "r");
    rb_funcall(f, rb_intern("set_encoding"), 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-"));
    rb_parser_set_context(parser, NULL, 0);
    ast = rb_parser_compile_file_path(parser, path, f, 1);

    rb_io_close(f);

    if (!ast->body.root) {
        rb_ast_dispose(ast);
        rb_exc_raise(GET_EC()->errinfo);
    }

    obj = ast_new_internal(ast, (NODE *)ast->body.root);

    return obj;
}