Class: Parslet::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/parslet/source.rb,
lib/parslet/source/line_cache.rb

Overview

Wraps the input string for parslet.

Defined Under Namespace

Modules: RangeSearch Classes: LineCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Source

Returns a new instance of Source.

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
# File 'lib/parslet/source.rb', line 10

def initialize(str)
  raise ArgumentError unless str.respond_to?(:to_str)

  @pos = 0
  @str = str
  
  @line_cache = LineCache.new
  @line_cache.scan_for_line_endings(0, @str)
end

Instance Attribute Details

#posObject

Position of the parse as a character offset into the original string. @note: Encodingsā€¦



52
53
54
# File 'lib/parslet/source.rb', line 52

def pos
  @pos
end

Instance Method Details

#chars_leftObject

Returns how many chars remain in the input.



46
47
48
# File 'lib/parslet/source.rb', line 46

def chars_left
  @str.size - @pos
end

#consume(n) ⇒ Object

Consumes n characters from the input, returning them as a slice of the input.



33
34
35
36
37
38
39
40
41
42
# File 'lib/parslet/source.rb', line 33

def consume(n)
  slice_str = @str.slice(@pos, n)
  slice = Parslet::Slice.new(
    slice_str, 
    pos,
    @line_cache)
  
  @pos += slice_str.size
  return slice
end

#line_and_column(position = nil) ⇒ Object

Returns a <line, column> tuple for the given position. If no position is given, line/column information is returned for the current position given by #pos.



58
59
60
# File 'lib/parslet/source.rb', line 58

def line_and_column(position=nil)
  @line_cache.line_and_column(position || self.pos)
end

#matches?(pattern) ⇒ Boolean Also known as: match

Checks if the given pattern matches at the current input position.

Parameters:

  • pattern (Regexp, String)

    pattern to check for

Returns:

  • (Boolean)

    true if the pattern matches at #pos



25
26
27
# File 'lib/parslet/source.rb', line 25

def matches?(pattern)
  @str.index(pattern, @pos) == @pos
end