Class: Parslet::Atoms::Alternative

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

Overview

Alternative during matching. Contains a list of parslets that is tried each one in turn. Only fails if all alternatives fail.

Example:

str('a') | str('b')   # matches either 'a' or 'b'

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(*alternatives) ⇒ Alternative

Constructs an Alternative instance using all given parslets in the order given. This is what happens if you call ‘|’ on existing parslets, like this:

str('a') | str('b')


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

def initialize(*alternatives)
  super()
  
  @alternatives = alternatives
end

Instance Attribute Details

#alternativesObject (readonly)

Returns the value of attribute alternatives.



10
11
12
# File 'lib/parslet/atoms/alternative.rb', line 10

def alternatives
  @alternatives
end

Instance Method Details

#accept(visitor) ⇒ Object

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



60
61
62
# File 'lib/parslet/atoms/visitor.rb', line 60

def accept(visitor)
  visitor.visit_alternative(alternatives)
end

#error_msgObject



32
33
34
# File 'lib/parslet/atoms/alternative.rb', line 32

def error_msg
  @error_msg ||= "Expected one of #{alternatives.inspect}"
end

#to_s_inner(prec) ⇒ Object



50
51
52
# File 'lib/parslet/atoms/alternative.rb', line 50

def to_s_inner(prec)
  alternatives.map { |a| a.to_s(prec) }.join(' / ')
end

#try(source, context, consume_all) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/parslet/atoms/alternative.rb', line 36

def try(source, context, consume_all)
  errors = alternatives.map { |a|
    success, value = result = a.apply(source, context, consume_all)
    return result if success
    
    # Aggregate all errors
    value
  }
  
  # If we reach this point, all alternatives have failed. 
  context.err(self, source, error_msg, errors)
end

#|(parslet) ⇒ Object


Don’t construct a hanging tree of Alternative parslets, instead store them all here. This reduces the number of objects created. +++



28
29
30
# File 'lib/parslet/atoms/alternative.rb', line 28

def |(parslet)
  self.class.new(*@alternatives + [parslet])
end