Class: Rbr::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/rbr/node.rb

Overview

Wraps a Parser::AST::Node object and provides convenience methods

Instance Method Summary collapse

Constructor Details

#initialize(ast_node) ⇒ Node

Returns a new instance of Node.



6
7
8
# File 'lib/rbr/node.rb', line 6

def initialize(ast_node)
  @ast_node = ast_node
end

Instance Method Details

#any_descendant_matches?(match_proc, root = self) ⇒ Boolean

Call the the proc, passing in this node and all children recursively. Return true if any call evaluates to true.

Returns:

  • (Boolean)


72
73
74
75
76
77
78
# File 'lib/rbr/node.rb', line 72

def any_descendant_matches?(match_proc, root = self)
  if root.respond_to?(:children)
    root.children.any? { |c| any_descendant_matches?(match_proc, c) }
  else
    match_proc.call(root)
  end
end

#assignment?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/rbr/node.rb', line 10

def assignment?
  %i[lvasgn ivasgn cvasgn gvasgn casgn masgn].include? @ast_node.type
end

#childrenObject



52
53
54
55
56
57
58
59
60
# File 'lib/rbr/node.rb', line 52

def children
  @ast_node.children.map do |child|
    if child.is_a?(Parser::AST::Node)
      Rbr::Node.new(child)
    else
      child
    end
  end
end

#const?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/rbr/node.rb', line 14

def const?
  @ast_node.type == :const
end

#expressionObject



48
49
50
# File 'lib/rbr/node.rb', line 48

def expression
  @ast_node.loc.expression
end

#literal?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/rbr/node.rb', line 18

def literal?
  %i[int float str].include? @ast_node.type
end

#method_call?(names) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
# File 'lib/rbr/node.rb', line 26

def method_call?(names)
  %i[send csend].include?(@ast_node.type) &&
    begin
      names = [names] unless names.is_a?(Array)

      names.include?(children[1]) ||
        (children[1] == :send && names.include?(children[2].value))
    end
end

#nil?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/rbr/node.rb', line 36

def nil?
  @ast_node.nil? || !(@ast_node.is_a? Parser::AST::Node)
end

#number?Boolean

Returns:

  • (Boolean)


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

def number?
  %i[int float].include? @ast_node.type
end

#pretty_printObject



66
67
68
# File 'lib/rbr/node.rb', line 66

def pretty_print
  "#{expression.line}: #{expression.source}"
end

#str?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/rbr/node.rb', line 40

def str?
  %i[str dstr xstr].include? @ast_node.type
end

#typeObject



44
45
46
# File 'lib/rbr/node.rb', line 44

def type
  @ast_node.type
end

#valueObject



62
63
64
# File 'lib/rbr/node.rb', line 62

def value
  @ast_node.children[0]
end