Class: Walrus::Grammar::RegexpParslet

Inherits:
Parslet
  • Object
show all
Defined in:
lib/walrus/grammar/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)


24
25
26
27
# File 'lib/walrus/grammar/regexp_parslet.rb', line 24

def initialize(regexp)
  raise ArgumentError if regexp.nil?
  self.expected_regexp = /\A#{regexp}/ # for efficiency, anchor all regexps to the start of the string
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



22
23
24
# File 'lib/walrus/grammar/regexp_parslet.rb', line 22

def hash
  @hash
end

Instance Method Details

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/walrus/grammar/regexp_parslet.rb', line 51

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

#inspectObject



55
56
57
# File 'lib/walrus/grammar/regexp_parslet.rb', line 55

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)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/walrus/grammar/regexp_parslet.rb', line 29

def parse(string, options = {})
  raise ArgumentError 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