Class: Parslet::Atoms::Str

Inherits:
Base
  • Object
show all
Defined in:
lib/parslet/atoms/str.rb,
lib/parslet/atoms/visitor.rb

Overview

Matches a string of characters.

Example:

str('foo') # matches 'foo'

Constant Summary

Constants included from Precedence

Precedence::ALTERNATE, Precedence::BASE, Precedence::LOOKAHEAD, Precedence::OUTER, Precedence::REPETITION, Precedence::SEQUENCE

Instance Attribute Summary collapse

Attributes inherited from Base

#label

Instance Method Summary collapse

Methods inherited from Base

#apply, #cached?, #inspect, #parse, #parse_with_debug, precedence, #setup_and_apply, #to_s

Methods included from CanFlatten

#flatten, #flatten_repetition, #flatten_sequence, #foldl, #merge_fold, #warn_about_duplicate_keys

Methods included from DSL

#>>, #absent?, #as, #capture, #ignore, #maybe, #present?, #repeat, #|

Constructor Details

#initialize(str) ⇒ Str

Returns a new instance of Str.


9
10
11
12
13
14
15
# File 'lib/parslet/atoms/str.rb', line 9

def initialize(str)
  super()

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

Instance Attribute Details

#strObject (readonly)

Returns the value of attribute str


8
9
10
# File 'lib/parslet/atoms/str.rb', line 8

def str
  @str
end

Instance Method Details

#accept(visitor) ⇒ Object

Call back visitors #visit_str method. See parslet/export for an example.


15
16
17
# File 'lib/parslet/atoms/visitor.rb', line 15

def accept(visitor)
  visitor.visit_str(str)
end

#error_msgsObject


17
18
19
20
21
22
# File 'lib/parslet/atoms/str.rb', line 17

def error_msgs
  @error_msgs ||= {
    premature: 'Premature end of input',
    failed: "Expected #{str.inspect}, but got "
  }
end

#to_s_inner(prec) ⇒ Object


38
39
40
# File 'lib/parslet/atoms/str.rb', line 38

def to_s_inner(prec)
  "'#{str}'"
end

#try(source, context, consume_all) ⇒ Object


24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/parslet/atoms/str.rb', line 24

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