Class: Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/rdparse.rb

Defined Under Namespace

Classes: Match

Instance Method Summary collapse

Constructor Details

#initialize(name, parser, debug_bool) ⇒ Rule

Returns a new instance of Rule.



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rdparse.rb', line 23

def initialize(name, parser, debug_bool)
  @logger = parser.logger
  @debug_mode = debug_bool
  # The name of the expressions this rule matches
  @name = name
  # We need the parser to recursively parse sub-expressions occurring
  # within the pattern of the match objects associated with this rule
  @parser = parser
  @matches = []
  # Left-recursive matches
  @lrmatches = []
end

Instance Method Details

#match(*pattern, &block) ⇒ Object

Add a matching expression to this rule, as in this example:

match(:term, '*', :dice) {|a, _, b| a * b }

The arguments to ‘match’ describe the constituents of this expression.



39
40
41
42
43
44
45
46
47
48
# File 'lib/rdparse.rb', line 39

def match(*pattern, &block)
  match = Match.new(pattern, block)
  # If the pattern is left-recursive, then add it to the left-recursive set
  if pattern[0] == @name
    pattern.shift
    @lrmatches << match
  else
    @matches << match
  end
end

#parseObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/rdparse.rb', line 50

def parse
  # Try non-left-recursive matches first, to avoid infinite recursion
  match_result = try_matches(@matches)
  return nil if match_result.nil?
  loop do
    result = try_matches(@lrmatches, match_result)
    return match_result if result.nil?
    match_result = result
  end
end