Skip to content

Commit e2d26f2

Browse files
authored
Merge pull request #4050 from Earlopain/ripper-lex-coerce
Also handle string conversion in `Ripper.lex`
2 parents ffe142c + 510258a commit e2d26f2

2 files changed

Lines changed: 25 additions & 12 deletions

File tree

lib/prism/translation/ripper.rb

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def self.parse(src, filename = "(ripper)", lineno = 1)
6666
# [[1, 13], :on_kw, "end", END ]]
6767
#
6868
def self.lex(src, filename = "-", lineno = 1, raise_errors: false)
69-
result = Prism.lex_compat(src, filepath: filename, line: lineno, version: "current")
69+
result = Prism.lex_compat(coerce_source(src), filepath: filename, line: lineno, version: "current")
7070

7171
if result.failure? && raise_errors
7272
raise SyntaxError, result.errors.first.message
@@ -88,6 +88,21 @@ def self.tokenize(...)
8888
lex(...).map { |token| token[2] }
8989
end
9090

91+
# Mirros the various lex_types that ripper supports
92+
def self.coerce_source(source) # :nodoc:
93+
if source.is_a?(IO)
94+
source.read
95+
elsif source.respond_to?(:gets)
96+
src = +""
97+
while line = source.gets
98+
src << line
99+
end
100+
src
101+
else
102+
source.to_str
103+
end
104+
end
105+
91106
# This contains a table of all of the parser events and their
92107
# corresponding arity.
93108
PARSER_EVENT_TABLE = {
@@ -477,17 +492,7 @@ def self.lex_state_name(state)
477492

478493
# Create a new Translation::Ripper object with the given source.
479494
def initialize(source, filename = "(ripper)", lineno = 1)
480-
if source.is_a?(IO)
481-
@source = source.read
482-
elsif source.respond_to?(:gets)
483-
@source = +""
484-
while line = source.gets
485-
@source << line
486-
end
487-
else
488-
@source = source.to_str
489-
end
490-
495+
@source = Ripper.coerce_source(source)
491496
@filename = filename
492497
@lineno = lineno
493498
@column = 0

test/prism/ruby/ripper_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,14 @@ def string_like.to_str
244244
end
245245
end
246246

247+
def test_lex_coersion
248+
string_like = Object.new
249+
def string_like.to_str
250+
"a"
251+
end
252+
assert_equal Ripper.lex(string_like), Translation::Ripper.lex(string_like)
253+
end
254+
247255
# Check that the hardcoded values don't change without us noticing.
248256
def test_internals
249257
actual = Translation::Ripper.constants.select { |name| name.start_with?("EXPR_") }.sort

0 commit comments

Comments
 (0)