Class: Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/zombie_killer/rule.rb

Overview

Rewriting rule

Defined Under Namespace

Classes: Placeholder

Constant Summary collapse

Arg =
Placeholder.new("Arg")
Arg1 =
Placeholder.new("Arg1")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(from:, to:) ⇒ Rule

Returns a new instance of Rule.



23
24
25
26
# File 'lib/zombie_killer/rule.rb', line 23

def initialize(from:, to:)
  @from = from
  @to = to
end

Instance Attribute Details

#fromAST::Node (readonly)

Returns:

  • (AST::Node)


19
20
21
# File 'lib/zombie_killer/rule.rb', line 19

def from
  @from
end

#toProc (readonly)

Returns:

  • (Proc)


21
22
23
# File 'lib/zombie_killer/rule.rb', line 21

def to
  @to
end

Instance Method Details

#match(node) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/zombie_killer/rule.rb', line 28

def match(node)
  captures = match2(from, node)
  return unless captures
  if to.respond_to? :call
    to.call(*captures)
  else
    to
  end
end

#match2(expected, actual) ⇒ Object

Returns an array of captured values or nil.

Returns:

  • an array of captured values or nil



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
# File 'lib/zombie_killer/rule.rb', line 39

def match2(expected, actual)
  # puts "M2 #{expected.inspect} #{actual.inspect}"
  # p expected.class
  # p actual.class
  return [] if expected.nil? && actual.nil?
  return nil if expected.nil? || actual.nil?

  # if we're a node
  case expected
  when AST::Node
    return nil if expected.type != actual.type
    return nil if expected.children.size != actual.children.size

    results = expected.children.zip(actual.children).map do |ec, ac|
      match2(ec, ac)
    end
    # puts "#{results.inspect} for #{expected.inspect}"
    results.flatten(1) if results.all?
  when Rule::Arg
    # puts "ARG #{actual.inspect}"
    [actual]
  else
    expected == actual ? [] : nil
  end
end