lib/preval/node.rb in preval-0.2.0 vs lib/preval/node.rb in preval-0.3.0
- old
+ new
@@ -1,19 +1,45 @@
# frozen_string_literal: true
module Preval
class Node
+ class TypeMatch
+ attr_reader :types
+
+ def initialize(types)
+ @types = types
+ end
+
+ def match?(node)
+ node.body.size == types.size &&
+ node.body.zip(types).all? do |(left, right)|
+ left.is_a?(Node) && Array(right).include?(left.type)
+ end
+ end
+
+ def self.match?(types, node)
+ new(types).match?(node)
+ end
+ end
+
include Format
attr_reader :type, :body, :literal
def initialize(type, body, literal = false)
@type = type
@body = body
@literal = literal
end
+ def dig(index, *args)
+ node = body[index]
+ return nil unless node
+
+ args.any? ? node.dig(*args) : node
+ end
+
def join(delim = '')
body.map(&:to_source).join(delim)
end
def is?(other)
@@ -40,9 +66,13 @@
begin
public_send(:"to_#{type}")
rescue NoMethodError
raise NotImplementedError, "#{type} has not yet been implemented"
end
+ end
+
+ def type_match?(*types)
+ TypeMatch.new(types).match?(self)
end
def update(type, body)
@type = type
@body = body