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) ⇒ Rule

Returns a new instance of Rule.



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

def initialize(name, parser)
  @logger = parser.logger
  # 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.



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

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



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

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