-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
redundant_assignment.rb
115 lines (100 loc) · 2.62 KB
/
redundant_assignment.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for redundant assignment before returning.
#
# @example
# # bad
# def test
# x = foo
# x
# end
#
# # bad
# def test
# if x
# z = foo
# z
# elsif y
# z = bar
# z
# end
# end
#
# # good
# def test
# foo
# end
#
# # good
# def test
# if x
# foo
# elsif y
# bar
# end
# end
#
class RedundantAssignment < Base
extend AutoCorrector
MSG = 'Redundant assignment before returning detected.'
def_node_matcher :redundant_assignment?, <<~PATTERN
(... $(lvasgn _name _expression) (lvar _name))
PATTERN
def on_def(node)
check_branch(node.body)
end
alias on_defs on_def
private
def check_branch(node)
return unless node
case node.type
when :case then check_case_node(node)
when :if then check_if_node(node)
when :rescue, :resbody
check_rescue_node(node)
when :ensure then check_ensure_node(node)
when :begin, :kwbegin
check_begin_node(node)
end
end
def check_case_node(node)
node.when_branches.each { |when_node| check_branch(when_node.body) }
check_branch(node.else_branch)
end
def check_if_node(node)
return if node.modifier_form? || node.ternary?
check_branch(node.if_branch)
check_branch(node.else_branch)
end
def check_rescue_node(node)
node.child_nodes.each do |child_node|
check_branch(child_node)
end
end
def check_ensure_node(node)
check_branch(node.body)
end
def check_begin_node(node)
if (assignment = redundant_assignment?(node))
add_offense(assignment) do |corrector|
expression = assignment.children[1]
corrector.replace(assignment, expression.source)
corrector.remove(right_sibling_of(assignment))
end
else
last_expr = node.children.last
check_branch(last_expr)
end
end
def right_sibling_of(node)
siblings_of(node)[node.sibling_index + 1]
end
def siblings_of(node)
node.parent.children
end
end
end
end
end