/
memoized_instance_variable_name.rb
295 lines (268 loc) · 8.99 KB
/
memoized_instance_variable_name.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks for memoized methods whose instance variable name
# does not match the method name. Applies to both regular methods
# (defined with `def`) and dynamic methods (defined with
# `define_method` or `define_singleton_method`).
#
# This cop can be configured with the EnforcedStyleForLeadingUnderscores
# directive. It can be configured to allow for memoized instance variables
# prefixed with an underscore. Prefixing ivars with an underscore is a
# convention that is used to implicitly indicate that an ivar should not
# be set or referenced outside of the memoization method.
#
# @safety
# This cop relies on the pattern `@instance_var ||= ...`,
# but this is sometimes used for other purposes than memoization
# so this cop is considered unsafe. Also, its autocorrection is unsafe
# because it may conflict with instance variable names already in use.
#
# @example EnforcedStyleForLeadingUnderscores: disallowed (default)
# # bad
# # Method foo is memoized using an instance variable that is
# # not `@foo`. This can cause confusion and bugs.
# def foo
# @something ||= calculate_expensive_thing
# end
#
# def foo
# return @something if defined?(@something)
# @something = calculate_expensive_thing
# end
#
# # good
# def _foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= begin
# calculate_expensive_thing
# end
# end
#
# # good
# def foo
# helper_variable = something_we_need_to_calculate_foo
# @foo ||= calculate_expensive_thing(helper_variable)
# end
#
# # good
# define_method(:foo) do
# @foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# return @foo if defined?(@foo)
# @foo = calculate_expensive_thing
# end
#
# @example EnforcedStyleForLeadingUnderscores: required
# # bad
# def foo
# @something ||= calculate_expensive_thing
# end
#
# # bad
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# def foo
# return @foo if defined?(@foo)
# @foo = calculate_expensive_thing
# end
#
# # good
# def foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def _foo
# @_foo ||= calculate_expensive_thing
# end
#
# def foo
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# @example EnforcedStyleForLeadingUnderscores :optional
# # bad
# def foo
# @something ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def _foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @_foo ||= calculate_expensive_thing
# end
class MemoizedInstanceVariableName < Base
extend AutoCorrector
include ConfigurableEnforcedStyle
MSG = 'Memoized variable `%<var>s` does not match ' \
'method name `%<method>s`. Use `@%<suggested_var>s` instead.'
UNDERSCORE_REQUIRED = 'Memoized variable `%<var>s` does not start ' \
'with `_`. Use `@%<suggested_var>s` instead.'
DYNAMIC_DEFINE_METHODS = %i[define_method define_singleton_method].to_set.freeze
# @!method method_definition?(node)
def_node_matcher :method_definition?, <<~PATTERN
${
(block (send _ %DYNAMIC_DEFINE_METHODS ({sym str} $_)) ...)
(def $_ ...)
(defs _ $_ ...)
}
PATTERN
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def on_or_asgn(node)
lhs, _value = *node
return unless lhs.ivasgn_type?
method_node, method_name = find_definition(node)
return unless method_node
body = method_node.body
return unless body == node || body.children.last == node
return if matches?(method_name, lhs)
suggested_var = suggested_var(method_name)
msg = format(
message(lhs.children.first.to_s),
var: lhs.children.first.to_s,
suggested_var: suggested_var,
method: method_name
)
add_offense(lhs, message: msg) do |corrector|
corrector.replace(lhs.loc.name, "@#{suggested_var}")
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# @!method defined_memoized?(node, ivar)
def_node_matcher :defined_memoized?, <<~PATTERN
(begin
(if (defined $(ivar %1)) (return $(ivar %1)) nil?)
...
$(ivasgn %1 _))
PATTERN
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def on_defined?(node)
arg = node.first_argument
return false unless arg.ivar_type?
method_node, method_name = find_definition(node)
return false unless method_node
var_name = arg.children.first
defined_memoized?(method_node.body, var_name) do |defined_ivar, return_ivar, ivar_assign|
return false if matches?(method_name, ivar_assign)
suggested_var = suggested_var(method_name)
msg = format(
message(var_name.to_s),
var: var_name.to_s,
suggested_var: suggested_var,
method: method_name
)
add_offense(defined_ivar, message: msg) do |corrector|
corrector.replace(defined_ivar, "@#{suggested_var}")
end
add_offense(return_ivar, message: msg) do |corrector|
corrector.replace(return_ivar, "@#{suggested_var}")
end
add_offense(ivar_assign.loc.name, message: msg) do |corrector|
corrector.replace(ivar_assign.loc.name, "@#{suggested_var}")
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
private
def style_parameter_name
'EnforcedStyleForLeadingUnderscores'
end
def find_definition(node)
# Methods can be defined in a `def` or `defs`,
# or dynamically via a `block` node.
node.each_ancestor(:def, :defs, :block).each do |ancestor|
method_node, method_name = method_definition?(ancestor)
return [method_node, method_name] if method_node
end
nil
end
def matches?(method_name, ivar_assign)
return true if ivar_assign.nil? || method_name == :initialize
method_name = method_name.to_s.delete('!?')
variable = ivar_assign.children.first
variable_name = variable.to_s.sub('@', '')
variable_name_candidates(method_name).include?(variable_name)
end
def message(variable)
variable_name = variable.to_s.sub('@', '')
return UNDERSCORE_REQUIRED if style == :required && !variable_name.start_with?('_')
MSG
end
def suggested_var(method_name)
suggestion = method_name.to_s.delete('!?')
style == :required ? "_#{suggestion}" : suggestion
end
def variable_name_candidates(method_name)
no_underscore = method_name.delete_prefix('_')
with_underscore = "_#{method_name}"
case style
when :required
[with_underscore,
method_name.start_with?('_') ? method_name : nil].compact
when :disallowed
[method_name, no_underscore]
when :optional
[method_name, with_underscore, no_underscore]
else
raise 'Unreachable'
end
end
end
end
end
end