Class: Walrat::RegexpParslet

Inherits:
Parslet
  • Object
show all
Defined in:
lib/walrat/regexp_parslet.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Parslet

#to_parseable

Methods included from Memoizing

#check_left_recursion, #memoizing_parse

Methods included from ParsletCombining

#&, #>>, #and?, #and_predicate, #choice, #memoizing_parse, #merge, #not!, #not_predicate, #omission, #one_or_more, #optional, #repeat, #repeat_with_default, #repetition, #repetition_with_default, #sequence, #skip, #zero_or_more, #zero_or_one, #|

Constructor Details

#initialize(regexp) ⇒ RegexpParslet

Returns a new instance of RegexpParslet.

Raises:

  • (ArgumentError)


29
30
31
32
# File 'lib/walrat/regexp_parslet.rb', line 29

def initialize regexp
  raise ArgumentError, 'nil regexp' if regexp.nil?
  self.expected_regexp = /\A#{regexp}/ # for efficiency, anchor all regexps
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



27
28
29
# File 'lib/walrat/regexp_parslet.rb', line 27

def hash
  @hash
end

Instance Method Details

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
60
# File 'lib/walrat/regexp_parslet.rb', line 57

def eql?(other)
  other.instance_of? RegexpParslet and
    other.expected_regexp == @expected_regexp
end

#inspectObject



62
63
64
65
# File 'lib/walrat/regexp_parslet.rb', line 62

def inspect
  '#<%s:0x%x @expected_regexp=%s>' %
    [self.class.to_s, self.object_id, @expected_regexp.inspect]
end

#parse(string, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/walrat/regexp_parslet.rb', line 34

def parse string, options = {}
  raise ArgumentError, 'nil string' if string.nil?
  if string =~ @expected_regexp
    wrapper = MatchDataWrapper.new $~
    match   = $~[0]

    if (line_count = match.scan(/\r\n|\r|\n/).length) != 0        # count number of newlines in match
      column_end    = match.jlength - match.jrindex(/\r|\n/) - 1  # calculate characters on last line
    else                                                          # no newlines in match
      column_end    = match.jlength + (options[:column_start] || 0)
    end

    wrapper.start       = [options[:line_start], options[:column_start]]
    wrapper.end         = [wrapper.line_start + line_count, column_end]
    wrapper.source_text = match.to_s.clone
    wrapper
  else
    raise ParseError.new('non-matching characters "%s" while parsing regular expression "%s"' % [string, @expected_regexp.inspect],
                         :line_end    => (options[:line_start] || 0),
                         :column_end  => (options[:column_start] || 0))
  end
end