ruby-changes:51396
From: yui-knk <ko1@a...>
Date: Thu, 7 Jun 2018 23:04:55 +0900 (JST)
Subject: [ruby-changes:51396] yui-knk:r63602 (trunk): ast.c: Fix to raise `SyntaxError`
yui-knk 2018-06-07 23:04:49 +0900 (Thu, 07 Jun 2018) New Revision: 63602 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=63602 Log: ast.c: Fix to raise `SyntaxError` * ast.c: Fix to raise `SyntaxError` when `RubyVM::AST.parse` or `RubyVM::AST.parse_file` fail to parse input. * test/ruby/test_ast.rb: Add test cases for invalid syntax. Modified files: trunk/ast.c trunk/test/ruby/test_ast.rb Index: ast.c =================================================================== --- ast.c (revision 63601) +++ ast.c (revision 63602) @@ -58,10 +58,13 @@ rb_ast_s_parse(VALUE module, VALUE str) https://github.com/ruby/ruby/blob/trunk/ast.c#L58 const VALUE parser = rb_parser_new(); str = rb_check_string_type(str); - rb_parser_set_context(parser, NULL, 1); + 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) return Qnil; + if (!ast->body.root) { + rb_ast_dispose(ast); + rb_exc_raise(GET_EC()->errinfo); + } obj = ast_new_internal(ast, (NODE *)ast->body.root); @@ -80,12 +83,15 @@ rb_ast_s_parse_file(VALUE module, VALUE https://github.com/ruby/ruby/blob/trunk/ast.c#L83 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, 1); + 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) return Qnil; + if (!ast->body.root) { + rb_ast_dispose(ast); + rb_exc_raise(GET_EC()->errinfo); + } obj = ast_new_internal(ast, (NODE *)ast->body.root); Index: test/ruby/test_ast.rb =================================================================== --- test/ruby/test_ast.rb (revision 63601) +++ test/ruby/test_ast.rb (revision 63602) @@ -150,4 +150,25 @@ class TestAst < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_ast.rb#L150 assert_equal(0, node.first_column) assert_equal(5, node.last_column) end + + def test_parse_raises_syntax_error + assert_raise(SyntaxError) { RubyVM::AST.parse("end") } + end + + def test_parse_file_raises_syntax_error + Tempfile.create(%w"test_ast .rb") do |f| + f.puts "end" + f.close + path = f.path + assert_in_out_err(%W[- #{path}], "#{<<-"begin;"}\n#{<<-"end;"}", /keyword_end/, [], success: true) + begin; + path = ARGV[0] + begin + RubyVM::AST.parse_file(path) + rescue SyntaxError => e + puts e.message + end + end; + end + end end -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/