Module: Machete

Defined in:
lib/machete.rb,
lib/machete/parser.rb,
lib/machete/version.rb,
lib/machete/matchers.rb

Defined Under Namespace

Modules: Matchers Classes: Parser

Constant Summary collapse

VERSION =
File.read(File.dirname(__FILE__) + "/../../VERSION").strip

Class Method Summary collapse

Class Method Details

.find(ast, pattern) ⇒ Array

Finds all nodes in a Rubinius AST matching a pattern.

Examples:

Search using a string pattern

Machete.find('42 + 43 + 44'.to_ast, 'FixnumLiteral')
# => [
#      #<Rubinius::AST::FixnumLiteral:0x10b0 @value=44 @line=1>,
#      #<Rubinius::AST::FixnumLiteral:0x10b8 @value=43 @line=1>,
#      #<Rubinius::AST::FixnumLiteral:0x10c0 @value=42 @line=1>
#    ]

Search using a compiled pattern

Machete.find(
  '42 + 43 + 44'.to_ast,
  Machete::Matchers::NodeMatcher.new("FixnumLiteral")
)
# => [
#      #<Rubinius::AST::FixnumLiteral:0x10b0 @value=44 @line=1>,
#      #<Rubinius::AST::FixnumLiteral:0x10b8 @value=43 @line=1>,
#      #<Rubinius::AST::FixnumLiteral:0x10c0 @value=42 @line=1>
#    ]

Parameters:

  • ast (Rubinius::AST::Node)

    tree to search

  • pattern (String, Machete::Matchers::Matcher)

    pattern to match the nodes against, either as a string (see README for syntax description) or in compiled form

Returns:

  • (Array)

    list of matching nodes (in unspecified order)

Raises:

  • (Matchete::Parser::SyntaxError)

    if the pattern is invalid



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/machete.rb', line 75

def find(ast, pattern)
  matcher = compiled_pattern(pattern)

  result = []
  result << ast if matcher.matches?(ast)

  ast.walk(true) do |dummy, node|
    result << node if matcher.matches?(node)
    true
  end

  result
end

.matches?(node, pattern) ⇒ Boolean

Matches a Rubinius AST node against a pattern.

Examples:

Test using a string pattern

Machete.matches?('foo.bar'.to_ast, 'Send<name = :bar>')
# => true

Machete.matches?('42'.to_ast, 'Send<name = :bar>')
# => false

Test using a compiled pattern

Machete.matches?(
  'foo.bar'.to_ast,
  Machete::Matchers::NodeMatcher.new("Send",
    :name => Machete::Matchers::LiteralMatcher.new(:bar)
  )
)
# => true

Machete.matches?(
  '42'.to_ast,
  Machete::Matchers::NodeMatcher.new("Send",
    :name => Machete::Matchers::LiteralMatcher.new(:bar)
  )
)
# => false

Parameters:

  • node (Rubinius::AST::Node)

    node to match

  • pattern (String, Machete::Matchers::Matcher)

    pattern to match the node against, either as a string (see README for syntax description) or in compiled form

Returns:

  • (Boolean)

    true if the node matches the pattern, false otherwise

Raises:

  • (Matchete::Parser::SyntaxError)

    if the pattern is invalid



42
43
44
# File 'lib/machete.rb', line 42

def matches?(node, pattern)
  compiled_pattern(pattern).matches?(node)
end