class RuboCop::AST::NodePattern
a pattern.
‘#prefix_type?` to the AST node class, then ’prefix’ will become usable as
and so on. Therefore, if you add methods which are named like
the node being matched, ‘const’ by ‘#const_type?`, ’int’ by ‘#int_type?`,
Note that patterns like ’send’ are implemented by calling ‘#send_type?` on
’(if (send _ :== _) _ nil?)‘
# and no ’else’ branch:
# matches a node parsed from an ‘if’, with a ‘==’ comparison,
‘(casgn nil? :Const (send (const nil? {:Class :Module}) :new))’
# matches node parsed from ‘Const = Class.new’ or ‘Const = Module.new’:
You can nest arbitrarily deep:
# passed.
# which case a matcher responding to === will be
# These arguments can be patterns themselves, in
’#method(%0, 1)‘ # funcalls can also be given 1 or more extra args
’equal?(%1)‘ # predicates can be given 1 or more extra args
# if that returns a truthy value, the match succeeds
# context where a pattern-matching method is defined
’#method’ # we call this a ‘funcall’; it calls a method in the
# so this matches against any descendant node
’‘send’ # descends any number of level in the AST
# so this matches against the grandparent node
’^^send’ # each ^ ascends one level in the AST
’(send _ %CONST)‘ # the named constant will act like `%1` and `%named`.
# `def_node_search` accept default values for these.
# Note that the macros `def_node_matcher` and
# parameters (see `%1`)
’(send _ %named)‘ # arguments can also be passed as named
# matching process starts
# passed as the 1st argument to #match, where the
# for consistency, %0 is the ’root node’ which is
# must equal the highest % value in the pattern
# the number of extra parameters passed to #match
# a bare ‘%’ is the same as ‘%1’
# many possible literals / Nodes.
# only), and so can be very useful to match within
# ‘Set#===` is an alias to `Set#include?` (Ruby 2.5+
# `Array#===` will never match a node element, but
# etc. in addition to Nodes or literals.
# the AST using #=== so you can pass Procs, Regexp,
# it will be compared to the corresponding value in
# #match at matching time
’(send %1 _)‘ # % stands for a parameter which must be supplied to
# OR), [] is intersection (logical AND)
# in other words, while {} is pattern union (logical
# match in that position
’(int [!1 !2])‘ # [] contains multiple patterns, ALL of which must
# if a truthy value is returned, the match succeeds
# can be used
# any Ruby method which the matched object supports
# are are called on the target to see if it matches
’(int odd?)‘ # words which end with a ? are predicate methods,
# (#== is used to see if values unify)
# (like Prolog variables…)
’(send _x :+ _x)‘ # unification is performed on named wildcards
’(send $… int)‘ # capture all children but the last as an array
’(send $…)‘ # capture all the children as an array
’(array (int $_)+)‘ # as above and will capture the numbers in an array
’(array int+)‘ # will match an array of 1 or more integers
# Note: Space needed to distinguish from int?
’(array int ?)‘ # will match 0 or 1 integer.
’(array int*)‘ # will match an array of 0 or more integers
# irrespective of the actual order of the children
’(array <$str $_>)‘ # captures are in the order of the pattern,
# a `sym` node, but can have more.
’(_ <str sym …>)‘ # will match if arguments have at least a `str` and
# would match `[’x’, :y]‘ as well as `[:y, ’x’]
‘(array <str sym>)’ # you can match children in any order. This
’(send … :new)‘ # you can match against the last children
’(send _recv _msg)‘ # wildcards can be named (for readability)
’$(send const …)‘ # arbitrary matching can be performed on a capture
’(send !const …)‘ # ! negates the next part of the pattern
’(send $_ $_)‘ # you can use as many captures as you want
’(send $_ :new)‘ # as above, but whatever matches the $_ is captured
’(send _ :new)‘ # matches (send <anything> :new)
’(send const)‘ # matches (send (const …))
’({send class})‘ # matches (send) or (class)
’{send class}‘ # matches (send …) or (class …)
’(op-asgn)‘ # node types with hyphenated names also work
’(send …)‘ # matches (send …)
’(send)‘ # matches (send)
’send’ # matches (send …)
‘nil’ # matches a literal nil
’1’ # matches a literal integer
’:sym’ # matches a literal symbol
## Pattern string format examples
- With no block and no captures: #match returns ‘true`.
- With no block, but multiple captures: captures are returned as an array.
- With no block, but one capture: the capture is returned.
value of the block through.
- With block: #match yields the captures (if any) and passes the return
from a matching AST.)
whether the pattern contained any “captures” (values which are extracted
return value depends on whether a block was provided to `#match`, and
If the match fails, `nil` will be returned. If the match succeeds, the
macros in `NodePattern::Macros` to define your own pattern-matching method.
pass an AST node to `NodePattern#match`. Alternatively, use one of the class
Initialize a new `NodePattern` with `NodePattern.new(pattern_string)`, then
This class performs a pattern-matching operation on an AST node.
def self.descend(element, &block)
Yields its argument and any descendants, depth-first.
def self.descend(element, &block) return to_enum(__method__, element) unless block_given? yield element if element.is_a?(::RuboCop::AST::Node) element.children.each do |child| descend(child, &block) end end nil end
def ==(other)
def ==(other) other.is_a?(NodePattern) && Compiler.tokens(other.pattern) == Compiler.tokens(pattern) end
def initialize(str)
def initialize(str) @pattern = str compiler = Compiler.new(str, 'node0') src = "def match(#{compiler.emit_params('node0')});" \ "#{compiler.emit_method_code}end" instance_eval(src, __FILE__, __LINE__ + 1) end
def marshal_dump
def marshal_dump pattern end
def marshal_load(pattern)
def marshal_load(pattern) initialize pattern end
def match(*args, **rest)
def match(*args, **rest) # If we're here, it's because the singleton method has not been defined, # either because we've been dup'ed or serialized through YAML initialize(pattern) if rest.empty? match(*args) else match(*args, **rest) end end
def to_s
def to_s "#<#{self.class} #{pattern}>" end