class Prism::Source
ranges.
conjunction with locations to allow them to resolve line numbers and source
This represents a source of Ruby code that has been parsed. It is used in
def character_column(byte_offset)
def character_column(byte_offset) character_offset(byte_offset) - character_offset(line_start(byte_offset)) end
def character_offset(byte_offset)
def character_offset(byte_offset) source.byteslice(0, byte_offset).length end
def column(byte_offset)
def column(byte_offset) byte_offset - line_start(byte_offset) end
def compute_offsets(code)
Find all of the newlines in the source code and return their byte offsets
def compute_offsets(code) offsets = [0] code.b.scan("\n") { offsets << $~.end(0) } offsets end
def find_line(byte_offset)
Binary search through the offsets to find the line number for the given
def find_line(byte_offset) left = 0 right = offsets.length - 1 while left <= right mid = left + (right - left) / 2 return mid if offsets[mid] == byte_offset if offsets[mid] < byte_offset left = mid + 1 else right = mid - 1 end end left - 1 end
def initialize(source, start_line = 1, offsets = compute_offsets(source))
offsets. If no newline byte offsets are given, they will be computed from
Create a new source object with the given source code and newline byte
def initialize(source, start_line = 1, offsets = compute_offsets(source)) @source = source @start_line = start_line @offsets = offsets end
def line(byte_offset)
Binary search through the offsets to find the line number for the given
def line(byte_offset) start_line + find_line(byte_offset) end
def line_start(byte_offset)
Return the byte offset of the start of the line corresponding to the given
def line_start(byte_offset) offsets[find_line(byte_offset)] end
def slice(byte_offset, length)
Perform a byteslice on the source code using the given byte offset and
def slice(byte_offset, length) source.byteslice(byte_offset, length) end