Class: Trenni::Location

Inherits:
Object
  • Object
show all
Defined in:
lib/trenni/parse_error.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, offset) ⇒ Location

Returns a new instance of Location.

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/trenni/parse_error.rb', line 45

def initialize(input, offset)
	raise ArgumentError.new("Offset #{index} is past end of input #{input.bytesize}") if offset > input.bytesize
	
	@offset = offset
	@line_index = 0
	line_offset = next_line_offset = 0
	
	input.each_line do |line|
		line_offset = next_line_offset
		next_line_offset += line.bytesize
		
		# Is our input offset within this line?
		if next_line_offset >= offset
			@line_text = line.chomp
			@line_range = line_offset...next_line_offset
			break
		else
			@line_index += 1
		end
	end
end

Instance Attribute Details

#line_indexObject (readonly)

The line that contains the @offset (base 0 indexing).



76
77
78
# File 'lib/trenni/parse_error.rb', line 76

def line_index
  @line_index
end

#line_rangeObject (readonly)

The byte offset to the start of that line.



84
85
86
# File 'lib/trenni/parse_error.rb', line 84

def line_range
  @line_range
end

#line_textObject (readonly)

Returns the value of attribute line_text.



91
92
93
# File 'lib/trenni/parse_error.rb', line 91

def line_text
  @line_text
end

Instance Method Details

#line_numberObject

The line index, but base-1.



79
80
81
# File 'lib/trenni/parse_error.rb', line 79

def line_number
	@line_index + 1
end

#line_offsetObject

The number of bytes from the start of the line to the given offset in the input.



87
88
89
# File 'lib/trenni/parse_error.rb', line 87

def line_offset
	@offset - @line_range.min
end

#to_iObject



67
68
69
# File 'lib/trenni/parse_error.rb', line 67

def to_i
	@offset
end

#to_sObject



71
72
73
# File 'lib/trenni/parse_error.rb', line 71

def to_s
	"[#{self.line_number}:#{self.line_offset}]"
end