AST provides methods to parse Ruby code into abstract syntax trees. The nodes in the tree are instances of RubyVM::AST::Node.
Parses the given string into an abstract syntax tree, returning the root node of that tree.
Returns nil 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;
}
Reads the file from pathname, then parses it like ::parse, returning the root node of the
abstract syntax tree.
Returns nil 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;
}