Class: Hegel::Generators::FromRegexGenerator

Inherits:
Hegel::Generator show all
Defined in:
lib/hegel/generators.rb,
sig/hegel.rbs

Overview

Hegel::Syntax::Methods#from_regex. A String matching pattern, which the header documents as Python re syntax -- a different grammar from Ruby's own Regexp, even though the two agree on simple patterns (character classes, quantifiers, alternation). fullmatch defaults to false, matching hegel_string_generator_regex's own documented default: the drawn string only has to contain a match, not equal one.

pattern must be a String, checked at draw time like every other validation in this file. A Ruby Regexp is rejected rather than accepted and translated: Regexp#source drops modifiers such as /i, /m, and /x silently, and the two grammars give the same characters different meanings in places -- Ruby's ^ and $ are always line anchors, where Python re's are string anchors unless re.MULTILINE is set, and Ruby's [[:alpha:]] POSIX bracket syntax has no Python re counterpart at all. Accepting a Regexp here would build a generator whose output quietly stopped matching the flags or anchors its caller wrote, with nothing to signal the mismatch. A caller who has confirmed a pattern needs no flags and uses only syntax the two grammars share can still pass my_regexp.source explicitly.

alphabet is not exposed here: the header's third argument accepts a text generator to constrain the wildcard/padding characters this regex can produce. nil, the header's documented "no particular alphabet" default, is passed in its place: exposing it means deciding how a Ruby caller writes an alphabet that constrains a Python regex, and that question is worth answering on its own rather than in passing here.

Instance Method Summary collapse

Methods inherited from Hegel::Generator

#filter, #map

Constructor Details

#initialize(pattern, fullmatch:) ⇒ FromRegexGenerator

Returns a new instance of FromRegexGenerator.

Parameters:

  • pattern (Object)
  • fullmatch: (Boolean)


475
476
477
478
479
# File 'lib/hegel/generators.rb', line 475

def initialize(pattern, fullmatch:)
  super()
  @pattern = pattern
  @fullmatch = fullmatch
end

Instance Method Details

#do_draw(tc) ⇒ String

Parameters:

  • tc (Object)

Returns:

  • (String)


481
482
483
484
485
486
487
# File 'lib/hegel/generators.rb', line 481

def do_draw(tc)
  unless @pattern.is_a?(String)
    raise Hegel::Error, "from_regex: pattern must be a String in Python re syntax, not a #{@pattern.class}"
  end

  tc.with_regex_generator(@pattern, fullmatch: @fullmatch) { |generator| tc.generate_string(generator) }
end