Class: Hone::Patterns::CharsToVariable

Inherits:
Base
  • Object
show all
Defined in:
lib/hone/patterns/chars_to_variable.rb

Overview

Approach 1: Simple scope-limited variable tracking

Detects when .chars is assigned to a variable and then used in ways that could be done directly on the string.

Examples:

Bad - allocates array just for indexing

chars = str.chars
chars[0]
chars.length
chars.each { |c| ... }

Good - direct string operations

str[0]
str.length
str.each_char { |c| ... }

Instance Attribute Summary

Attributes inherited from Base

#findings

Instance Method Summary collapse

Methods inherited from Base

#add_finding, inherited, scan_file

Constructor Details

#initialize(file_path) ⇒ CharsToVariable

Returns a new instance of CharsToVariable.



25
26
27
28
# File 'lib/hone/patterns/chars_to_variable.rb', line 25

def initialize(file_path)
  super
  @scope_stack = []
end

Instance Method Details

#visit_block_node(node) ⇒ Object

Track block scope



36
37
38
# File 'lib/hone/patterns/chars_to_variable.rb', line 36

def visit_block_node(node)
  with_scope { super }
end

#visit_call_node(node) ⇒ Object

Check for inefficient usage of tracked variables



52
53
54
55
# File 'lib/hone/patterns/chars_to_variable.rb', line 52

def visit_call_node(node)
  super
  check_inefficient_usage(node)
end

#visit_def_node(node) ⇒ Object

Track method scope



31
32
33
# File 'lib/hone/patterns/chars_to_variable.rb', line 31

def visit_def_node(node)
  with_scope { super }
end

#visit_lambda_node(node) ⇒ Object

Track lambda scope



41
42
43
# File 'lib/hone/patterns/chars_to_variable.rb', line 41

def visit_lambda_node(node)
  with_scope { super }
end

#visit_local_variable_write_node(node) ⇒ Object

Track .chars assignments



46
47
48
49
# File 'lib/hone/patterns/chars_to_variable.rb', line 46

def visit_local_variable_write_node(node)
  super
  track_chars_assignment(node)
end