Skip to content

Commit

Permalink
[Fix #10962] Fix a false positive for `Lint/ShadowingOuterLocalVariab…
Browse files Browse the repository at this point in the history
…le` when conditional with if/elsif/else branches

Fix: #10962
  • Loading branch information
ydah committed Aug 26, 2022
1 parent eb3acca commit 26c0ff1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10962](https://github.com/rubocop/rubocop/pull/10962): Fix a false positive for `Lint/ShadowingOuterLocalVariable` when conditional with if/elsif/else branches. ([@ydah][])
16 changes: 14 additions & 2 deletions lib/rubocop/cop/lint/shadowing_outer_local_variable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,26 @@ def before_declaring_variable(variable, variable_table)
end

def same_conditions_node_different_branch?(variable, outer_local_variable)
variable_node = variable.scope.node.parent
variable_node = variable_node(variable)
return false unless variable_node.conditional?

outer_local_variable_node =
find_conditional_node_from_ascendant(outer_local_variable.declaration_node)
return true unless outer_local_variable_node

outer_local_variable_node.conditional? && variable_node == outer_local_variable_node
outer_local_variable_node.conditional? &&
(variable_node == outer_local_variable_node ||
variable_node == outer_local_variable_node.else_branch)
end

def variable_node(variable)
parent_node = variable.scope.node.parent

if parent_node.when_type?
parent_node.parent
else
parent_node
end
end

def find_conditional_node_from_ascendant(node)
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/lint/shadowing_outer_local_variable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ def some_method
^^^ Shadowing outer local variable - `foo`.
end
end
elsif other_condition?
bar.each do |foo|
end
else
bar.each do |foo|
end
Expand Down Expand Up @@ -152,6 +155,9 @@ def some_method
bar.each do |foo|
^^^ Shadowing outer local variable - `foo`.
end
when bar then
bar.each do |foo|
end
else
bar.each do |foo|
end
Expand All @@ -168,6 +174,9 @@ def some_method
def some_method
if condition?
foo = 1
elsif other_condition?
bar.each do |foo|
end
else
bar.each do |foo|
end
Expand Down

0 comments on commit 26c0ff1

Please sign in to comment.