Class: Kotoshu::Documents::SourcePosition

Inherits:
Struct
  • Object
show all
Includes:
Comparable
Defined in:
lib/kotoshu/documents/source_position.rb

Overview

Immutable value object: a point in the original (markup-bearing) source.

Carries both a 0-based character offset (useful for tools that want to slice the source by range) and a 1-based line/column pair (useful for editor highlighting and human-readable messages).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(offset:, line:, column:) ⇒ SourcePosition

Returns a new instance of SourcePosition.

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
# File 'lib/kotoshu/documents/source_position.rb', line 14

def initialize(offset:, line:, column:)
  raise ArgumentError, "offset must be >= 0" if offset.negative?
  raise ArgumentError, "line must be >= 1" if line < 1
  raise ArgumentError, "column must be >= 1" if column < 1

  super
  freeze
end

Instance Attribute Details

#columnObject

Returns the value of attribute column

Returns:

  • (Object)

    the current value of column



11
12
13
# File 'lib/kotoshu/documents/source_position.rb', line 11

def column
  @column
end

#lineObject

Returns the value of attribute line

Returns:

  • (Object)

    the current value of line



11
12
13
# File 'lib/kotoshu/documents/source_position.rb', line 11

def line
  @line
end

#offsetObject

Returns the value of attribute offset

Returns:

  • (Object)

    the current value of offset



11
12
13
# File 'lib/kotoshu/documents/source_position.rb', line 11

def offset
  @offset
end

Instance Method Details

#<=>(other) ⇒ Object

Lexicographic order by (offset, line, column). Matches the natural order of positions when scanning the source left to right, top to bottom.



26
27
28
29
30
# File 'lib/kotoshu/documents/source_position.rb', line 26

def <=>(other)
  return nil unless other.is_a?(SourcePosition)

  [offset, line, column] <=> [other.offset, other.line, other.column]
end

#to_sObject



32
33
34
# File 'lib/kotoshu/documents/source_position.rb', line 32

def to_s
  "line #{line}, column #{column} (offset #{offset})"
end