2014-06-29 17:25:17 -04:00
|
|
|
module Mutant
|
|
|
|
# AST helpers
|
|
|
|
module AST
|
2014-07-14 09:38:48 -04:00
|
|
|
|
|
|
|
# Walk all ast nodes
|
|
|
|
#
|
2014-09-16 14:39:27 -04:00
|
|
|
# @param [Parser::AST::Node] root
|
|
|
|
# @param [Array<Parser::AST::Node>] stack
|
2014-07-14 09:38:48 -04:00
|
|
|
#
|
|
|
|
# @yield [Parser::AST::Node]
|
|
|
|
# all nodes recursively including root
|
|
|
|
#
|
|
|
|
# @return [self]
|
|
|
|
#
|
|
|
|
# @api private
|
|
|
|
#
|
2014-09-16 14:39:27 -04:00
|
|
|
def self.walk(node, stack, &block)
|
2014-12-21 20:28:30 -05:00
|
|
|
fail ArgumentError, 'block expected' unless block_given?
|
2014-07-14 09:38:48 -04:00
|
|
|
|
2014-09-16 14:39:27 -04:00
|
|
|
block.call(node, stack)
|
2014-07-14 09:38:48 -04:00
|
|
|
node.children.grep(Parser::AST::Node).each do |child|
|
2014-09-16 14:39:27 -04:00
|
|
|
stack.push(child)
|
|
|
|
walk(child, stack, &block)
|
|
|
|
stack.pop
|
2014-07-14 09:38:48 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
self
|
|
|
|
end
|
2014-09-16 14:39:27 -04:00
|
|
|
private_class_method :walk
|
2014-07-14 09:38:48 -04:00
|
|
|
|
2014-08-12 19:28:32 -04:00
|
|
|
# Find last node satisfying predicate (as block)
|
2014-07-14 09:38:48 -04:00
|
|
|
#
|
|
|
|
# @return [Parser::AST::Node]
|
2014-08-12 19:28:32 -04:00
|
|
|
# if satisfying node is found
|
2014-07-14 09:38:48 -04:00
|
|
|
#
|
|
|
|
# @yield [Parser::AST::Node]
|
|
|
|
#
|
|
|
|
# @yieldreturn [Boolean]
|
|
|
|
# true in case node satisfies predicate
|
|
|
|
#
|
|
|
|
# @return [nil]
|
|
|
|
# otherwise
|
|
|
|
#
|
|
|
|
# @api private
|
|
|
|
#
|
2014-09-16 14:39:27 -04:00
|
|
|
def self.find_last_path(node, &predicate)
|
2014-11-17 12:00:05 -05:00
|
|
|
fail ArgumentError, 'block expected' unless block_given?
|
2014-09-16 14:39:27 -04:00
|
|
|
path = []
|
|
|
|
walk(node, [node]) do |candidate, stack|
|
|
|
|
if predicate.call(candidate, &predicate)
|
|
|
|
path = stack.dup
|
|
|
|
end
|
2014-07-14 09:38:48 -04:00
|
|
|
end
|
2014-09-16 14:39:27 -04:00
|
|
|
path
|
2014-07-14 09:38:48 -04:00
|
|
|
end
|
|
|
|
|
2014-06-29 17:25:17 -04:00
|
|
|
end # AST
|
|
|
|
end # Mutant
|