Module: RubyVM::AbstractSyntaxTree
Overview
AbstractSyntaxTree
provides methods to parse Ruby code into abstract syntax trees. The nodes in the tree are instances of Node
.
Class Method Summary
-
.of(proc) ⇒ AbstractSyntaxTree
Returns AST nodes of the given proc or method.
-
.parse(string) ⇒ AbstractSyntaxTree
Parses the given string into an abstract syntax tree, returning the root node of that tree.
-
.parse_file(pathname) ⇒ AbstractSyntaxTree
Reads the file from
pathname
, then parses it like .parse, returning the root node of the abstract syntax tree.
Class Method Details
.of(proc) ⇒ AbstractSyntaxTree
.of(method) ⇒ AbstractSyntaxTree
AbstractSyntaxTree
.of(method) ⇒ AbstractSyntaxTree
Returns AST nodes of the given proc or method.
RubyVM::AbstractSyntaxTree.of(proc {1 + 2})
# => #<RubyVM::AbstractSyntaxTree::Node(NODE_SCOPE(0) 1:35, 1:42): >
def hello
puts "hello, world"
end
RubyVM::AbstractSyntaxTree.of(method(:hello))
# => #<RubyVM::AbstractSyntaxTree::Node(NODE_SCOPE(0) 1:0, 3:3): >
# File 'ast.c', line 220
static VALUE rb_ast_s_of(VALUE module, VALUE body) { VALUE path, node, lines; 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; if (!NIL_P(lines = script_lines(path))) { node = rb_ast_parse_array(lines); } else if (RSTRING_LEN(path) == 2 && memcmp(RSTRING_PTR(path), "-e", 2) == 0) { node = rb_ast_parse_str(rb_e_script); } else { node = rb_ast_parse_file(path); } return node_find(node, node_id); }
.parse(string) ⇒ AbstractSyntaxTree
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::AbstractSyntaxTree.parse("x = 1 + 2")
# => #<RubyVM::AbstractSyntaxTree::Node(NODE_SCOPE(0) 1:0, 1:9): >
# File 'ast.c', line 88
static VALUE rb_ast_s_parse(VALUE module, VALUE str) { return rb_ast_parse_str(str); }
.parse_file(pathname) ⇒ AbstractSyntaxTree
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::AbstractSyntaxTree.parse_file("my-app/app.rb")
# => #<RubyVM::AbstractSyntaxTree::Node(NODE_SCOPE(0) 1:0, 31:3): >
# File 'ast.c', line 117
static VALUE rb_ast_s_parse_file(VALUE module, VALUE path) { return rb_ast_parse_file(path); }