Skip to content

Commit

Permalink
Don't raise ArgumentError in when detecting encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Earlopain committed Mar 10, 2024
1 parent 531974f commit ce9f99a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
6 changes: 5 additions & 1 deletion lib/parser/source/buffer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ def self.recognize_encoding(string)
return nil if encoding_line.nil? || encoding_line[0] != '#'

if (result = ENCODING_RE.match(encoding_line))
Encoding.find(result[3] || result[4] || result[6])
begin
Encoding.find(result[3] || result[4] || result[6])
rescue ArgumentError
nil
end
else
nil
end
Expand Down
22 changes: 15 additions & 7 deletions test/test_encoding.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,28 @@ def test_suffix
assert_equal Encoding::UTF_8, recognize('# coding: utf-8-unix')
assert_equal Encoding::UTF_8, recognize('# coding: utf-8-mac')

assert_raises(ArgumentError) do
assert_nil recognize('# coding: utf-8-dicks')
end
assert_nil recognize('# coding: utf-8-dicks')
end

def test_parse_18_invalid_enc
# Ruby 1.8. did not have this magic comment
ast = Parser::Ruby18.parse("# encoding:feynman-diagram\n1")
assert_equal ast, s(:int, 1)
encoding = ast.location.expression.source_buffer.source.encoding
assert_equal(Encoding::BINARY, encoding)
end

def test_parse_19_invalid_enc
assert_raises(ArgumentError) do
Parser::Ruby19.parse("# encoding:feynman-diagram\n1")
end
# The default encoding for Ruby 1.9 is BINARY
ast = Parser::Ruby19.parse("# encoding:feynman-diagram\n1")
encoding = ast.location.expression.source_buffer.source.encoding
assert_equal(Encoding::BINARY, encoding)
end

def test_parse_20_invalid_enc
# Ruby 2.0 changed the default encoding to UTF-8
ast = Parser::Ruby20.parse("# encoding:feynman-diagram\n1")
encoding = ast.location.expression.source_buffer.source.encoding
assert_equal(Encoding::UTF_8, encoding)
end

def test_ending_comment
Expand Down

0 comments on commit ce9f99a

Please sign in to comment.