Class: Rattler::Parsers::Choice

Inherits:
Parser show all
Includes:
Combining
Defined in:
lib/rattler/parsers/choice.rb

Overview

Choice combines two or more parsers and matches by trying each one in order until one succeeds and returning that result.

Author:

  • Jason Arhart

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Combining

#capturing?, #with_ws

Methods inherited from Parser

#&, #capturing?, #labeled?, #one_or_more, #optional, #skip, #variable_capture_count?, #with_ws, #zero_or_more

Methods inherited from Util::Node

#==, [], #[], #attrs, #can_equal?, #child, #children, #each, #empty?, #eql?, #initialize, #inspect, #method_missing, #name, #respond_to?, #same_contents?, #to_graphviz, #with_attrs, #with_attrs!, #with_children

Constructor Details

This class inherits a constructor from Rattler::Util::Node

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Rattler::Util::Node

Class Method Details

.parsed(results, *_) ⇒ Object



21
22
23
# File 'lib/rattler/parsers/choice.rb', line 21

def self.parsed(results, *_) #:nodoc:
  results.reduce(:|)
end

Instance Method Details

#parse(scanner, rules, scope = {}) ⇒ Object

Try each parser in order until one succeeds and return that result.

Returns:

  • the result of the first parser that matches, or false



30
31
32
33
34
35
36
37
# File 'lib/rattler/parsers/choice.rb', line 30

def parse(scanner, rules, scope = {})
  for child in children
    if r = child.parse(scanner, rules, scope)
      return r
    end
  end
  false
end

#|(other) ⇒ Object

Return a new parser that tries this parser first and if it fails tries other.

Parameters:

  • other (Parser)

    the parser to try if this parser fails.

Returns:

  • a new parser that tries this parser first and if it fails tries other



44
45
46
# File 'lib/rattler/parsers/choice.rb', line 44

def |(other)
  Choice[(children + [other])]
end