Class: Fabulator::Grammar::Actions::Rule

Inherits:
Structural
  • Object
show all
Defined in:
lib/fabulator/grammar/actions/rule.rb

Instance Method Summary collapse

Constructor Details

#initialize(g = nil) ⇒ Rule

Returns a new instance of Rule.



15
16
17
18
# File 'lib/fabulator/grammar/actions/rule.rb', line 15

def initialize(g = nil)
  @grammar = g
  @choices = [ ]
end

Instance Method Details

#parse(cursor) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fabulator/grammar/actions/rule.rb', line 20

def parse(cursor)
  # try each when...
  best_attempt = nil
  @choices.each do |choice|
    ret = cursor.attempt { |c| choice.parse(c) }
    if !ret.nil?
      score = choice.score(cursor.context, ret)
      if best_attempt.nil? || best_attempt[:score] < score
        best_attempt = {
          :score => score,
          :choice => choice,
          :ret => ret
        }
      end
    end
  end
  raise Fabulator::Grammar::RejectParse if best_attempt.nil?
  choice = best_attempt[:choice]
  ret = best_attempt[:ret]
  if choice.has_actions?
    cursor.context.root.roots['result'] = cursor.context.root.roots['result'].anon_node(nil)
    new_ret = cursor.context.root.roots['result']
    choice.run(cursor.context.with_root(ret))
    cursor.set_result(new_ret)
  else
    cursor.set_result(ret)
  end
end