class MigemoRegex::RegexRenderer

Attributes

with_paren[RW]

Public Class Methods

new(regex, insertion) click to toggle source
# File lib/migemo-regex.rb, line 174
def initialize (regex, insertion)
  raise if regex == nil
  @regex = regex
  @meta = RegexMetachars.new
  @insertion = insertion
  @with_paren = false
end

Public Instance Methods

join_regexes(string, regexes) click to toggle source
# File lib/migemo-regex.rb, line 193
def join_regexes (string, regexes)
  ([string] + regexes).join @meta.bar
end
render() click to toggle source
# File lib/migemo-regex.rb, line 183
def render
  if @with_paren  # e.g. "(a|b|c)"
    render0(@regex)
  else            # e.g. "a|b|c"
    @regex.map do |x|
      render0(x)
    end.join @meta.bar
  end
end

Private Instance Methods

escape_charclass(string) click to toggle source
# File lib/migemo-regex.rb, line 220
def escape_charclass (string)
  string.gsub(/\\/, '\\\\\\')
end
escape_string(string) click to toggle source

We don't use Regexp.quote because the following regex is more general (not ruby-specific) and safe to use.

# File lib/migemo-regex.rb, line 216
def escape_string (string)
  string.gsub(/([\x00-\x1f\x21-\x2f\x3a-\x40\x5b-\x5e\x60\x7b-\x7f])/, '\\\\\\1')
end
insert(string) click to toggle source
# File lib/migemo-regex.rb, line 234
def insert (string)
  if @insertion != ""
    tmp = string.gsub(/(\\.|.)/, "\\1#{@insertion}")
    tmp = tmp.sub(/#{Regexp.quote(@insertion)}$/, "")
  else
    string
  end
end
render0(x) click to toggle source
# File lib/migemo-regex.rb, line 247
def render0 (x)
  if x.instance_of?(RegexAlternation)
    render_alternation(x)
  elsif x.instance_of?(RegexConcatnation)
    render_concatnation(x)
  elsif x.instance_of?(RegexCharClass)
    render_charclass(x)
  elsif x.instance_of?(String)
    render_string(x)
  else
    raise "unexpected type: #{x} of #{x.class}"
  end
end
render_alternation(regex) click to toggle source
# File lib/migemo-regex.rb, line 198
def render_alternation (regex)
  if regex.length == 0
    raise
  elsif regex.length == 1
    render0(regex[0])
  else
    @meta.lparen + 
      regex.map {|x| render0(x) }.join(@meta.bar) + 
      @meta.rparen
  end
end
render_charclass(regex) click to toggle source
# File lib/migemo-regex.rb, line 224
def render_charclass (regex)
  if regex.delete("-")
    regex.push("-")  # move "-" to the end of Array.
  end
  if regex.delete("]")
    regex.unshift("]")  # move "]" to the beginning of Array.
  end
  escape_charclass("[" + regex.join + "]")
end
render_concatnation(regex) click to toggle source
# File lib/migemo-regex.rb, line 210
def render_concatnation (regex)
  regex.map {|x| render0(x) }.join(@insertion)
end
render_string(regex) click to toggle source
# File lib/migemo-regex.rb, line 243
def render_string (regex)
  insert(escape_string(regex))
end