Class: RubyLint::Analysis::UselessEqualityChecks
- Defined in:
- lib/ruby-lint/analysis/useless_equality_checks.rb
Overview
Analysis class that checks for equality checks and adds warnings when
these always evaluate to false. An example of such a check is
:hello == 'hello'
.
This analysis class was added after a co-worker banged their head against a wall after finding the following code:
if some_value.to_sym == "overall"
# ...
end
This code would never evaluate to true. In the particular case this would result in it never caching certain data.
Constant Summary
Constants inherited from Base
Instance Attribute Summary
Attributes inherited from Base
Attributes inherited from Iterator
#arity_cache, #arity_cache Hash containing the amount of arguments for
Instance Method Summary collapse
-
#definition_type(object) ⇒ String
Returns the type name of the given definition.
-
#node_type(node) ⇒ String
Returns the type name for a given AST node.
-
#on_send(node) ⇒ Object
-
#skip_type?(type) ⇒ Boolean
Methods inherited from Base
#add_message, #after_initialize, analyze?, #current_scope, #error, #info, #previous_scope, register, #set_current_scope, #set_previous_scope, #warning
Methods included from MethodEvaluation
Methods inherited from Iterator
#execute_callback, #initialize, #iterate, #skip_child_nodes!
Constructor Details
This class inherits a constructor from RubyLint::Iterator
Instance Method Details
#definition_type(object) ⇒ String
Returns the type name of the given definition.
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/ruby-lint/analysis/useless_equality_checks.rb', line 67 def definition_type(object) name = nil # Built-in types such as Array. if object.ruby_class name = object.ruby_class # Variables elsif object.variable? and object.value name = definition_type(object.value) # Constants. elsif object.constant? and !object.name.empty? name = object.name end return name end |
#node_type(node) ⇒ String
Returns the type name for a given AST node.
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/ruby-lint/analysis/useless_equality_checks.rb', line 50 def node_type(node) definition = vm.associations[node] type = nil if definition type = definition_type(definition) end return type end |
#on_send(node) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/ruby-lint/analysis/useless_equality_checks.rb', line 24 def on_send(node) receiver, name, arg = *node return unless name == :== left_type = node_type(receiver) right_type = node_type(arg) if skip_type?(left_type) or skip_type?(right_type) return end if left_type != right_type warning( "Comparing #{left_type} with #{right_type} evaluates to false", node ) end end |
#skip_type?(type) ⇒ Boolean
89 90 91 |
# File 'lib/ruby-lint/analysis/useless_equality_checks.rb', line 89 def skip_type?(type) return !type || type == 'unknown' end |