summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorKevin Newton <kddnewton@gmail.com>2023-10-24 12:28:53 -0400
committerKevin Newton <kddnewton@gmail.com>2023-10-26 15:19:43 -0400
commitd1bb858d476446ab82e6caa29c061a0da734c8eb (patch)
treecfc59d3f7e38c7295243a9bc29f9973f9d8d4896 /lib
parente9aa2398b9d8eb04a0013fa5420214382ea3457a (diff)
[ruby/prism] Match existing Ruby prettyprint
https://github.com/ruby/prism/commit/6d8358c083
Diffstat (limited to 'lib')
-rw-r--r--lib/prism/parse_result.rb26
1 files changed, 21 insertions, 5 deletions
diff --git a/lib/prism/parse_result.rb b/lib/prism/parse_result.rb
index fd2737b20c..00ae3aaa1a 100644
--- a/lib/prism/parse_result.rb
+++ b/lib/prism/parse_result.rb
@@ -16,16 +16,32 @@ module Prism
source.byteslice(offset, length)
end
+ # Binary search through the offsets to find the line number for the given
+ # offset.
def line(value)
- offsets.bsearch_index { |offset| offset > value } || offsets.length
+ left = 0
+ right = offsets.length - 1
+
+ while left <= right
+ mid = left + (right - left) / 2
+ return mid if offsets[mid] == value
+
+ if offsets[mid] < value
+ left = mid + 1
+ else
+ right = mid - 1
+ end
+ end
+
+ left - 1
end
def line_offset(value)
- offsets[line(value) - 1]
+ offsets[line(value)]
end
def column(value)
- value - offsets[line(value) - 1]
+ value - offsets[line(value)]
end
private
@@ -86,7 +102,7 @@ module Prism
# The line number where this location starts.
def start_line
- source.line(start_offset)
+ source.line(start_offset) + 1
end
# The content of the line where this location starts before this location.
@@ -97,7 +113,7 @@ module Prism
# The line number where this location ends.
def end_line
- source.line(end_offset - 1)
+ source.line(end_offset) + 1
end
# The column number in bytes where this location starts from the start of