Skip to content

Commit

Permalink
[ruby/prism] Location#slice_lines, Node#slice_lines
Browse files Browse the repository at this point in the history
  • Loading branch information
kddnewton authored and matzbot committed Apr 26, 2024
1 parent 0599184 commit 9688093
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/prism/parse_result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ def line_start(byte_offset)
offsets[find_line(byte_offset)]
end

# Returns the byte offset of the end of the line corresponding to the given
# byte offset.
def line_end(byte_offset)
offsets[find_line(byte_offset) + 1] || source.bytesize
end

# Return the column number for the given byte offset.
def column(byte_offset)
byte_offset - line_start(byte_offset)
Expand Down Expand Up @@ -176,6 +182,15 @@ def slice
source.slice(start_offset, length)
end

# The source code that this location represents starting from the beginning
# of the line that this location starts on to the end of the line that this
# location ends on.
def slice_lines
line_start = source.line_start(start_offset)
line_end = source.line_end(end_offset)
source.slice(line_start, line_end - line_start)
end

# The character offset from the beginning of the source where this location
# starts.
def start_character_offset
Expand Down
7 changes: 7 additions & 0 deletions prism/templates/lib/prism/node.rb.erb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ module Prism
location.slice
end

# Slice the location of the node from the source, starting at the beginning
# of the line that the location starts on, ending at the end of the line
# that the location ends on.
def slice_lines
location.slice_lines
end

# Similar to inspect, but respects the current level of indentation given by
# the pretty print object.
def pretty_print(q)
Expand Down
7 changes: 7 additions & 0 deletions test/prism/ruby_api_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,13 @@ def test_location_chop
assert_equal "", location.slice
end

def test_location_slice_lines
result = Prism.parse("\nprivate def foo\nend\n")
method = result.value.statements.body.first.arguments.arguments.first

assert_equal "private def foo\nend\n", method.slice_lines
end

def test_heredoc?
refute parse_expression("\"foo\"").heredoc?
refute parse_expression("\"foo \#{1}\"").heredoc?
Expand Down

0 comments on commit 9688093

Please sign in to comment.