Class: Walrus::Grammar::SymbolParslet

Inherits:
Parslet
  • Object
show all
Defined in:
lib/walrus/grammar/symbol_parslet.rb

Overview

A SymbolParslet allows for evaluation of a parslet to be deferred until runtime (or parse time, to be more precise).

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Parslet

#to_parseable

Methods included from Memoizing

#check_left_recursion, #memoizing_parse

Methods included from ParsletCombining

#&, #>>, #and?, #and_predicate, #choice, #memoizing_parse, #merge, #not!, #not_predicate, #omission, #one_or_more, #optional, #repeat, #repeat_with_default, #repetition, #repetition_with_default, #sequence, #skip, #zero_or_more, #zero_or_one, #|

Constructor Details

#initialize(symbol) ⇒ SymbolParslet

Returns a new instance of SymbolParslet.

Raises:

  • (ArgumentError)


25
26
27
28
29
# File 'lib/walrus/grammar/symbol_parslet.rb', line 25

def initialize(symbol)
  raise ArgumentError if symbol.nil?
  @symbol = symbol
  @hash = @symbol.hash + 20 # fixed offset to avoid collisions with @parseable objects
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



23
24
25
# File 'lib/walrus/grammar/symbol_parslet.rb', line 23

def hash
  @hash
end

Instance Method Details

#==(other) ⇒ Object



52
53
54
# File 'lib/walrus/grammar/symbol_parslet.rb', line 52

def ==(other)
  eql?(other)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/walrus/grammar/symbol_parslet.rb', line 56

def eql?(other)
  other.instance_of? SymbolParslet and other.symbol == @symbol
end

#parse(string, options = {}) ⇒ Object

SymbolParslets don’t actually know what Grammar they are associated with at the time of their definition. They expect the Grammar to be passed in with the options hash under the “:grammar” key. Raises if string is nil, or if the options hash does not include a :grammar key.

Raises:

  • (ArgumentError)


33
34
35
36
37
38
39
40
41
42
# File 'lib/walrus/grammar/symbol_parslet.rb', line 33

def parse(string, options = {})
  raise ArgumentError if string.nil?
  raise ArgumentError unless options.has_key?(:grammar)
  grammar = options[:grammar]
  augmented_options = options.clone
  augmented_options[:rule_name] = @symbol
  augmented_options[:skipping_override] = grammar.skipping_overrides[@symbol] if grammar.skipping_overrides.has_key?(@symbol)
  result = grammar.rules[@symbol].memoizing_parse(string, augmented_options)
  grammar.wrap(result, @symbol)
end

#to_sObject

We override the to_s method as it can make parsing error messages more readable. Instead of messages like this:

predicate not satisfied (expected "#<Walrus::Grammar::SymbolParslet:0x10cd504>") while parsing "hello world"

We can print messages like this:

predicate not satisfied (expected "rule: end_of_input") while parsing "hello world"


48
49
50
# File 'lib/walrus/grammar/symbol_parslet.rb', line 48

def to_s
  'rule: ' + @symbol.to_s
end