Class: Parse::MapPosition

Inherits:
Object show all
Defined in:
lib/parse/map_position.rb

Overview

Examples:


def pos(line, column, file)
  Parse::Position.new(line, column, file)
end

m = Parse::MapPosition.new
m.map_from(pos(5, 10, "src.c"), pos(3, 2, "src.y"))
m.map_from(pos(30, 5, "src.c"), pos(0, 0, "extra.y"))
p m[pos(1,12,"src.c")]  # src.c:1:12
p m[pos(5,12,"src.c")]  # src.y:3:4
p m[pos(6,10,"src.c")]  # src.y:4:10
p m[pos(30,5,"src.c")]  # extra.y:0:0
p m[pos(40,0,"src.c")]  # extra.y:10:0

Instance Method Summary collapse

Constructor Details

#initializeMapPosition

Returns a new instance of MapPosition.



24
25
26
# File 'lib/parse/map_position.rb', line 24

def initialize()
  @mappings = []
end

Instance Method Details

#[](pos1) ⇒ Position Also known as: call

See also #map_from.

Parameters:

  • pos1 (Position)

Returns:

  • (Position)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/parse/map_position.rb', line 61

def [](pos1)
  # 
  return pos1 if @mappings.empty? or @mappings.first.pos_b.file != pos1.file
  # 
  mapping = find_mapping_for pos1
  # 
  return pos1 if mapping.nil?
  # 
  pos_b, new_pos_b = mapping.pos_b, mapping.new_pos_b
  # new_pos_b.advance(pos1 |-| pos_b)
  if pos1.line == pos_b.line
  then Parse::Position.new(new_pos_b.line, new_pos_b.column + (pos1.column - pos_b.column), new_pos_b.file)
  else Parse::Position.new(new_pos_b.line + (pos1.line - pos_b.line), pos1.column, new_pos_b.file)
  end
end

#map_from(pos_b, new_pos_b) ⇒ self

Before:

  • m[pos1] == pos2

After:

  • m[pos1] == new_pos_b.advance(pos1 |-| pos_b) if pos1 >= pos_b

  • m[pos1] == pos2 otherwise

Here pos_m |-| pos_n is the number of characters between pos_m and pos_n; p.advance(n) is p advanced by n characters.

This method can not be called with pos_b with different Position#files!

Parameters:

  • pos_b (Position)
  • new_pos_b (Position)

Returns:

  • (self)


50
51
52
53
54
# File 'lib/parse/map_position.rb', line 50

def map_from(pos_b, new_pos_b)
  raise "can not call this method with different Position#file (was `#{@mappings.first.pos_b.file}' but `#{pos_b.file}' specified)" if not @mappings.empty? and @mappings.first.pos_b.file != pos_b.file
  pos_b_idx = @mappings.bsearch_index { |mapping| mapping.pos_b >= pos_b } || @mappings.size
  @mappings[pos_b_idx..-1] = [Mapping[pos_b, new_pos_b]]
end