module RuboCop::NodePattern::Macros

Helpers for defining methods based on a pattern string

Public Instance Methods

def_node_matcher(method_name, pattern_str) click to toggle source

Define a method which applies a pattern to an AST node

The new method will return nil if the node does not match If the node matches, and a block is provided, the new method will yield to the block (passing any captures as block arguments). If the node matches, and no block is provided, the new method will return the captures, or `true` if there were none.

# File lib/rubocop/node_pattern.rb, line 701
def def_node_matcher(method_name, pattern_str)
  compiler = Compiler.new(pattern_str, 'node')
  src = "def #{method_name}(node = self" \
        "#{compiler.emit_trailing_params});" \
        "#{compiler.emit_method_code};end"

  location = caller_locations(1, 1).first
  class_eval(src, location.path, location.lineno)
end
node_search_all(method_name, compiler, called_from) click to toggle source
# File lib/rubocop/node_pattern.rb, line 732
def node_search_all(method_name, compiler, called_from)
  yield_code = compiler.emit_yield_capture('node')
  prelude = "return enum_for(:#{method_name}, node0" \
            "#{compiler.emit_trailing_params}) unless block_given?"

  node_search(method_name, compiler, yield_code, prelude, called_from)
end
node_search_body(method_name, trailing_params, prelude, match_code, on_match) click to toggle source
# File lib/rubocop/node_pattern.rb, line 747
      def node_search_body(method_name, trailing_params, prelude, match_code,
                           on_match)
        <<-RUBY
          def #{method_name}(node0#{trailing_params})
            #{prelude}
            node0.each_node do |node|
              if #{match_code}
                #{on_match}
              end
            end
            nil
          end
        RUBY
      end
node_search_first(method_name, compiler, called_from) click to toggle source
# File lib/rubocop/node_pattern.rb, line 728
def node_search_first(method_name, compiler, called_from)
  node_search(method_name, compiler, 'return true', '', called_from)
end