Class: Language::Atom::Repeat

Inherits:
Language::Atom show all
Defined in:
lib/language/atom.rb

Instance Method Summary collapse

Methods inherited from Language::Atom

#<<, #>>, #absent, #aka, #any, #ignore, #inspect, #maybe, #repeat, #rule, #str, #then, #|

Constructor Details

#initialize(parent: nil, min: 0, max: nil) ⇒ Repeat

Returns a new instance of Repeat.



44
45
46
47
48
# File 'lib/language/atom.rb', line 44

def initialize(parent: nil, min: 0, max: nil)
  @parent = parent
  @min = min
  @max = max
end

Instance Method Details

#parse(parser) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/language/atom.rb', line 50

def parse(parser)
  return unless @parent

  if @max.nil?
    @min.times { match(parser) }

    begin
      loop { match(parser) }
    rescue Parser::Interuption
    end
  else
    @min.times { match(parser) }

    begin
      (@max - @min).times { match(parser) }
    rescue Parser::Interuption
    end
  end
end

#to_sObject



70
71
72
73
74
75
76
# File 'lib/language/atom.rb', line 70

def to_s
  min = @min.zero? ? "" : @min.to_s
  max = @max.nil? ? "" : ", #{@max}"
  parenthesis = min.empty? && max.empty? ? "" : "(#{min}#{max})"

  @parent ? "(#{@parent}).repeat#{parenthesis}" : "repeat#{parenthesis}"
end