Module: Machete

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

Defined Under Namespace

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:

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>
#    ]

Parameters:

  • ast (Rubinius::AST::Node)

    tree to search

  • pattern (String)

    pattern to match the nodes against (see README for syntax description)

Returns:

  • (Array)

    list of matching nodes (in unspecified order)

Raises:

  • (Matchete::Parser::SyntaxError)

    if the pattern is invalid



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/machete.rb', line 42

def self.find(ast, pattern)
  matcher = Parser.new.parse(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:

Succesfull match

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

Failed match

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

Parameters:

  • node (Rubinius::AST::Node)

    node to match

  • pattern (String)

    pattern to match the node against (see README for syntax description)

Returns:

  • (Boolean)

    true if the node matches the pattern, false otherwise

Raises:

  • (Matchete::Parser::SyntaxError)

    if the pattern is invalid



22
23
24
# File 'lib/machete.rb', line 22

def self.matches?(node, pattern)
  Parser.new.parse(pattern).matches?(node)
end