Class: Fop::Nodes::Match

Inherits:
Struct
  • Object
show all
Defined in:
lib/fop/nodes.rb

Constant Summary collapse

NUM =
"N".freeze
WORD =
"W".freeze
ALPHA =
"A".freeze
WILD =
"*".freeze
BLANK =
"".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#tokensObject

Returns the value of attribute tokens

Returns:

  • (Object)

    the current value of tokens



15
16
17
# File 'lib/fop/nodes.rb', line 15

def tokens
  @tokens
end

#wildcardObject

Returns the value of attribute wildcard

Returns:

  • (Object)

    the current value of wildcard



15
16
17
# File 'lib/fop/nodes.rb', line 15

def wildcard
  @wildcard
end

Instance Method Details

#consume!(input) ⇒ Object



22
23
24
25
26
# File 'lib/fop/nodes.rb', line 22

def consume!(input)
  if (val = input.slice!(@regex))
    @expression && val != BLANK ? @expression.call(val) : val
  end
end

#parse!Object

Raises:

  • (ParserError)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/fop/nodes.rb', line 33

def parse!
  match = tokens.shift || raise(ParserError, "Empty match")
  raise ParserError, "Unexpected #{match}" unless match.is_a? Tokenizer::Char

  @match = match.char
  @regex =
    case @match
    when NUM then Regexp.new((wildcard ? ".*?" : "^") + "[0-9]+")
    when WORD then Regexp.new((wildcard ? ".*?" : "^") + "\\w+")
    when ALPHA then Regexp.new((wildcard ? ".*?" : "^") + "[a-zA-Z]+")
    when WILD then /.*/
    else raise ParserError, "Unknown match type '#{@match}'"
    end

  if (op = tokens.shift)
    raise ParserError, "Unexpected #{op}" unless op.is_a? Tokenizer::Char
    arg = tokens.reduce("") { |acc, t|
      raise ParserError, "Unexpected #{t}" unless t.is_a? Tokenizer::Char
      acc + t.char
    }

    @op = op.char
    @arg = arg == BLANK ? nil : arg
    @expression =
      case @op
      when "=" then ->(_) { @arg || BLANK }
      when "+", "-", "*", "/"
        raise ParserError, "Operator #{@op} is only available for numeric matches" unless @match == NUM
        raise ParserError, "Operator #{@op} expects an argument" if @arg.nil?
        ->(x) { x.to_i.send(@op, @arg.to_i) }
      else raise ParserError, "Unknown operator #{@op}"
      end
  else
    @op, @arg, @expression = nil, nil, nil
  end
end

#to_sObject



28
29
30
31
# File 'lib/fop/nodes.rb', line 28

def to_s
  w = wildcard ? "*" : nil
  @op ? "#{w}#{@match} #{@op} #{@arg}" : "#{w}#{@match}"
end