Class: RedQuilt::SourceMap

Inherits:
Object
  • Object
show all
Defined in:
lib/red_quilt/source_map.rb,
sig/red_quilt.rbs

Overview

Positions follow the unist Point convention: line and column are 1-based and counted in characters, while char_offset is 0-based.

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ SourceMap

Returns a new instance of SourceMap.

Parameters:

  • source (String)


11
12
13
14
15
# File 'lib/red_quilt/source_map.rb', line 11

def initialize(source)
  @source = source
  @line_starts = build_line_starts(source)
  @line_char_starts = build_line_char_starts(source, @line_starts)
end

Instance Method Details

#char_offset(byte_offset) ⇒ Integer

Returns the 0-based character offset, as unist Point#offset requires. Byte offsets are what SourceSpan carries, and the two differ as soon as the source contains a multibyte character.

Parameters:

  • byte_offset (Integer)

Returns:

  • (Integer)


26
27
28
29
# File 'lib/red_quilt/source_map.rb', line 26

def char_offset(byte_offset)
  line = line_index(byte_offset)
  @line_char_starts[line] + chars_from_line_start(line, byte_offset)
end

#line_column(byte_offset) ⇒ { line: Integer, column: Integer }

Returns { line:, column: }, both 1-based.

Parameters:

  • byte_offset (Integer)

Returns:

  • ({ line: Integer, column: Integer })


18
19
20
21
# File 'lib/red_quilt/source_map.rb', line 18

def line_column(byte_offset)
  line = line_index(byte_offset)
  { line: line + 1, column: chars_from_line_start(line, byte_offset) + 1 }
end