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.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Combining

#capturing?, #semantic?, #with_ws

Methods inherited from Parser

#&, #>>, #capturing?, #labeled?, #list, #one_or_more, #optional, #repeat, #semantic?, #sequence?, #skip, #variable_capture_count?, #with_ws, #zero_or_more

Methods included from Runtime::ParserHelper

#select_captures

Methods inherited from Util::Node

#==, [], #[], #attrs, #can_equal?, #child, #children, #each, #empty?, #eql?, #initialize, #inspect, #method_missing, #name, #pretty_print, #pretty_print_cycle, #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



12
13
14
# File 'lib/rattler/parsers/choice.rb', line 12

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

Instance Method Details

#capturing_decidable?Object

true if it can be determined statically whether the parser returns parse results on success

Returns:

  • true if it can be determined statically whether the parser returns parse results on success



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

def capturing_decidable?
  @capturing_decidable ||=
    children.all? {|_| _.capturing_decidable? } and
    ( children.all? {|_| _.capturing? } or
      children.none? {|_| _.capturing? } )
end

#parse(scanner, rules, scope = ParserScope.empty) ⇒ Object

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

Parameters:

  • scanner (StringScanner)

    the scanner for the current parse

  • rules (RuleSet)

    the grammar rules being used for the current parse

  • scope (ParserScope) (defaults to: ParserScope.empty)

    the scope of captured results

Returns:

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



21
22
23
24
25
26
27
28
# File 'lib/rattler/parsers/choice.rb', line 21

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

#|(other) ⇒ Choice

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:

  • (Choice)

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



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

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