File: str.rb

package info (click to toggle)
ruby-parslet 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,260 kB
  • sloc: ruby: 6,157; sh: 8; javascript: 3; makefile: 3
file content (42 lines) | stat: -rw-r--r-- 916 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Matches a string of characters. 
#
# Example: 
# 
#   str('foo') # matches 'foo'
#
class Parslet::Atoms::Str < Parslet::Atoms::Base
  attr_reader :str
  def initialize(str)
    super()

    @str = str.to_s
    @pat = Regexp.new(Regexp.escape(str))
    @len = str.size
  end

  def error_msgs
    @error_msgs ||= {
      premature: 'Premature end of input',
      failed: "Expected #{str.inspect}, but got "
    }
  end
  
  def try(source, context, consume_all)
    return succ(source.consume(@len)) if source.matches?(@pat)
    
    # Input ending early:
    return context.err(self, source, error_msgs[:premature]) \
      if source.chars_left<@len
    
    # Expected something, but got something else instead:  
    error_pos = source.pos  
    return context.err_at(
      self, source, 
      [error_msgs[:failed], source.consume(@len)], error_pos) 
  end
  
  def to_s_inner(prec)
    "'#{str}'"
  end
end