Class: Rubocop::Cop::VariableInspector::VariableTable

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cop/variable_inspector.rb

Overview

A VariableTable manages the lifetime of all scopes and local variables in a program. This holds scopes as stack structure, and provides a way to add local variables to current scope and find local variables by considering variable visibility of the current scope.

Instance Method Summary collapse

Constructor Details

#initialize(hook_receiver = nil) ⇒ VariableTable

Returns a new instance of VariableTable.



68
69
70
# File 'lib/rubocop/cop/variable_inspector.rb', line 68

def initialize(hook_receiver = nil)
  @hook_receiver = hook_receiver
end

Instance Method Details

#add_variable_entry(variable_declaration_node, name = nil) ⇒ Object



104
105
106
107
108
109
110
# File 'lib/rubocop/cop/variable_inspector.rb', line 104

def add_variable_entry(variable_declaration_node, name = nil)
  entry = VariableEntry.new(variable_declaration_node, name)
  invoke_hook(:before_declaring_variable, entry)
  current_scope.variable_entries[entry.name] = entry
  invoke_hook(:after_declaring_variable, entry)
  entry
end

#current_scopeObject



96
97
98
# File 'lib/rubocop/cop/variable_inspector.rb', line 96

def current_scope
  scope_stack.last
end

#current_scope_levelObject



100
101
102
# File 'lib/rubocop/cop/variable_inspector.rb', line 100

def current_scope_level
  scope_stack.count
end

#find_variable_entry(variable_name) ⇒ Object



112
113
114
115
116
117
118
119
120
# File 'lib/rubocop/cop/variable_inspector.rb', line 112

def find_variable_entry(variable_name)
  scope_stack.reverse_each do |scope|
    entry = scope.variable_entries[variable_name]
    return entry if entry
    # Only block scope allows referencing outer scope variables.
    return nil unless scope.node.type == :block
  end
  nil
end

#invoke_hook(hook_name, *args) ⇒ Object



72
73
74
# File 'lib/rubocop/cop/variable_inspector.rb', line 72

def invoke_hook(hook_name, *args)
  @hook_receiver.send(hook_name, *args) if @hook_receiver
end

#pop_scopeObject



88
89
90
91
92
93
94
# File 'lib/rubocop/cop/variable_inspector.rb', line 88

def pop_scope
  scope = current_scope
  invoke_hook(:before_leaving_scope, scope)
  scope_stack.pop
  invoke_hook(:after_leaving_scope, scope)
  scope
end

#push_scope(scope_node) ⇒ Object



80
81
82
83
84
85
86
# File 'lib/rubocop/cop/variable_inspector.rb', line 80

def push_scope(scope_node)
  scope = Scope.new(scope_node)
  invoke_hook(:before_entering_scope, scope)
  scope_stack.push(scope)
  invoke_hook(:after_entering_scope, scope)
  scope
end

#scope_stackObject



76
77
78
# File 'lib/rubocop/cop/variable_inspector.rb', line 76

def scope_stack
  @scope_stack ||= []
end