Skip to content

Commit

Permalink
+ Raise a more specific error when encountering an unknown magic comm…
Browse files Browse the repository at this point in the history
…ent encoding (#999)

Closes #998
  • Loading branch information
Earlopain committed Mar 10, 2024
1 parent 531974f commit b920c87
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/parser.rb
Expand Up @@ -59,6 +59,7 @@ module Source

require 'parser/syntax_error'
require 'parser/clobbering_error'
require 'parser/unknown_encoding_in_magic_comment_error'
require 'parser/diagnostic'
require 'parser/diagnostic/engine'

Expand Down
7 changes: 6 additions & 1 deletion lib/parser/source/buffer.rb
Expand Up @@ -46,6 +46,7 @@ class Buffer
# magic encoding comment or UTF-8 BOM. `string` can be in any encoding.
#
# @param [String] string
# @raise [Parser::UnknownEncodingInMagicComment] if the encoding is not recognized
# @return [String, nil] encoding name, if recognized
#
def self.recognize_encoding(string)
Expand All @@ -66,7 +67,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 => e
raise Parser::UnknownEncodingInMagicComment, e.message
end
else
nil
end
Expand Down
15 changes: 15 additions & 0 deletions lib/parser/unknown_encoding_in_magic_comment_error.rb
@@ -0,0 +1,15 @@
# frozen_string_literal: true

module Parser
##
# {Parser::UnknownEncodingInMagicComment} is raised when a magic encoding
# comment is encountered that the currently running Ruby version doesn't
# recognize. It inherits from {ArgumentError} since that is the exception
# Ruby itself raises when trying to execute a file with an unknown encoding.
# As such, it is also not a {Parser::SyntaxError}.
#
# @api public
#
class UnknownEncodingInMagicComment < ArgumentError
end
end
3 changes: 2 additions & 1 deletion test/test_encoding.rb
Expand Up @@ -60,9 +60,10 @@ 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
e = assert_raises(ArgumentError) do
assert_nil recognize('# coding: utf-8-dicks')
end
assert(e.is_a?(Parser::UnknownEncodingInMagicComment))
end

def test_parse_18_invalid_enc
Expand Down

0 comments on commit b920c87

Please sign in to comment.