Skip to content

Commit e77545f

Browse files
committed
Add Ripper.tokenize to translation layer
It's public API and trivial to implement.
1 parent 8f4f6db commit e77545f

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

lib/prism/translation/ripper.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,19 @@ def self.lex(src, filename = "-", lineno = 1, raise_errors: false)
7878
end
7979
end
8080

81+
# Tokenizes the Ruby program and returns an array of strings.
82+
# The +filename+ and +lineno+ arguments are mostly ignored, since the
83+
# return value is just the tokenized input.
84+
# By default, this method does not handle syntax errors in +src+,
85+
# use the +raise_errors+ keyword to raise a SyntaxError for an error in +src+.
86+
#
87+
# p Ripper.tokenize("def m(a) nil end")
88+
# # => ["def", " ", "m", "(", "a", ")", " ", "nil", " ", "end"]
89+
#
90+
def self.tokenize(...)
91+
lex(...).map(&:value)
92+
end
93+
8194
# This contains a table of all of the parser events and their
8295
# corresponding arity.
8396
PARSER_EVENT_TABLE = {

test/prism/ruby/ripper_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ class RipperTest < TestCase
8484
define_method("#{fixture.test_name}_lexer_parse") { assert_ripper_lexer_parse(fixture.read) }
8585
end
8686

87+
def test_tokenize
88+
source = "foo;1;BAZ"
89+
assert_equal(Ripper.tokenize(source), Translation::Ripper.tokenize(source))
90+
end
91+
8792
# Check that the hardcoded values don't change without us noticing.
8893
def test_internals
8994
actual = Translation::Ripper.constants.select { |name| name.start_with?("EXPR_") }.sort

0 commit comments

Comments
 (0)