Class: Steep::AST::Buffer

Inherits:
Object
  • Object
show all
Defined in:
lib/steep/ast/buffer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, content:) ⇒ Buffer

Returns a new instance of Buffer.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/steep/ast/buffer.rb', line 9

def initialize(name:, content:)
  @name = name
  @content = content

  @lines = content.split(/\n/, -1)

  @ranges = []
  offset = 0
  lines.each.with_index do |line, index|
    if index == lines.size - 1
      ranges << (offset..offset)
    else
      size = line.size
      range = offset..(offset+size)
      ranges << range
      offset += size+1
    end
  end
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



5
6
7
# File 'lib/steep/ast/buffer.rb', line 5

def content
  @content
end

#linesObject (readonly)

Returns the value of attribute lines.



6
7
8
# File 'lib/steep/ast/buffer.rb', line 6

def lines
  @lines
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/steep/ast/buffer.rb', line 4

def name
  @name
end

#rangesObject (readonly)

Returns the value of attribute ranges.



7
8
9
# File 'lib/steep/ast/buffer.rb', line 7

def ranges
  @ranges
end

Instance Method Details

#loc_to_pos(loc) ⇒ Object



41
42
43
44
# File 'lib/steep/ast/buffer.rb', line 41

def loc_to_pos(loc)
  line, column = loc
  ranges[line - 1].begin + column
end

#pos_to_loc(pos) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/steep/ast/buffer.rb', line 29

def pos_to_loc(pos)
  index = ranges.bsearch_index do |range|
    pos <= range.end
  end

  if index
    [index + 1, pos - ranges[index].begin]
  else
    [1, pos]
  end
end

#source(range) ⇒ Object



46
47
48
# File 'lib/steep/ast/buffer.rb', line 46

def source(range)
  content[range]
end