Method: Musa::GenerativeGrammar::Implementation::Node#repeat

Defined in:
lib/musa-dsl/generative/generative-grammar.rb

#repeat(exactly = nil, min: nil, max: nil) ⇒ Node

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Repeats this node with optional min/max bounds.

Generates options with different repetition counts of this node. Without bounds, generates infinite options (use with limit).

Examples:

Fixed repetition

a = N('a')
aaa = a.repeat(3)         # exactly 3 times
aaa = a.repeat(exactly: 3)  # same

Bounded repetition

a_range = a.repeat(min: 2, max: 4)  # 2, 3, or 4 times

Unbounded (use with limit)

a_any = a.repeat.limit { |o| o.size <= 5 }

Raises:

  • (ArgumentError)

    if both exactly and min/max are specified



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/musa-dsl/generative/generative-grammar.rb', line 224

def repeat(exactly = nil, min: nil, max: nil)
  raise ArgumentError, 'Only exactly value or min/max values are allowed' if exactly && (min || max)

  min = max = exactly if exactly

  if min && min > 0
    pre = self

    (min - 1).times do
      pre += self
    end
  end

  if pre && max == min
    pre
  elsif pre && max > min
    pre + RepeatNode.new(self, max - min)
  else
    RepeatNode.new(self, max)
  end
end