class Rule

Rewriting rule

Constants

Arg
Arg1
Placeholder

Attributes

from[R]

@return [AST::Node]

to[R]

@return [Proc]

Public Class Methods

new(from:, to:) click to toggle source
# File lib/zombie_killer/rule.rb, line 23
def initialize(from:, to:)
  @from = from
  @to = to
end

Public Instance Methods

match(node) click to toggle source
# 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) click to toggle source

@return an array of captured values or nil

# 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