-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathinternal_api.rb
More file actions
305 lines (283 loc) · 9.91 KB
/
internal_api.rb
File metadata and controls
305 lines (283 loc) · 9.91 KB
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
296
297
298
299
300
301
302
303
304
305
# frozen_string_literal: true
module MemoWise
class InternalAPI
# Create initial mutable state to store memoized values if it doesn't
# already exist
#
# @param [Object] obj
# Object in which to create mutable state to store future memoized values
#
# @return [Object] the passed-in obj
def self.create_memo_wise_state!(obj)
# `@_memo_wise` stores memoized results of method calls. For performance
# reasons, the structure differs for different types of methods. It looks
# like:
# {
# no_args_method_name: :memoized_result,
# single_arg_method_name: { arg1 => :memoized_result, ... },
# [:multi_arg_method_name, arg1, arg2].hash => :memoized_result
# }
unless obj.instance_variables.include?(:@_memo_wise)
obj.instance_variable_set(:@_memo_wise, {})
end
# `@_memo_wise_hashes` stores the `Array#hash` values for each key in
# `@_memo_wise` that represents a multi-argument method call. We only use
# this data structure when resetting memoization for an entire method. It
# looks like:
# {
# multi_arg_method_name: Set[
# [:multi_arg_method_name, arg1, arg2].hash,
# [:multi_arg_method_name, arg1, arg3].hash,
# ...
# ],
# ...
# }
unless obj.instance_variables.include?(:@_memo_wise_hashes)
obj.instance_variable_set(:@_memo_wise_hashes, {})
end
obj
end
# Determine whether `method` takes any *positional* args.
#
# These are the types of positional args:
#
# * *Required* -- ex: `def foo(a)`
# * *Optional* -- ex: `def foo(b=1)`
# * *Splatted* -- ex: `def foo(*c)`
#
# @param method [Method, UnboundMethod]
# Arguments of this method will be checked
#
# @return [Boolean]
# Return `true` if `method` accepts one or more positional arguments
#
# @example
# class Example
# def no_args
# end
#
# def position_arg(a)
# end
# end
#
# MemoWise::InternalAPI.
# has_arg?(Example.instance_method(:no_args)) #=> false
#
# MemoWise::InternalAPI.
# has_arg?(Example.instance_method(:position_arg)) #=> true
#
def self.has_arg?(method) # rubocop:disable Naming/PredicateName
method.parameters.any? do |param, _|
param == :req || param == :opt || param == :rest # rubocop:disable Style/MultipleComparison
end
end
# Determine whether `method` takes any *keyword* args.
#
# These are the types of keyword args:
#
# * *Keyword Required* -- ex: `def foo(a:)`
# * *Keyword Optional* -- ex: `def foo(b: 1)`
# * *Keyword Splatted* -- ex: `def foo(**c)`
#
# @param method [Method, UnboundMethod]
# Arguments of this method will be checked
#
# @return [Boolean]
# Return `true` if `method` accepts one or more keyword arguments
#
# @example
# class Example
# def position_args(a, b=1)
# end
#
# def keyword_args(a:, b: 1)
# end
# end
#
# MemoWise::InternalAPI.
# has_kwarg?(Example.instance_method(:position_args)) #=> false
#
# MemoWise::InternalAPI.
# has_kwarg?(Example.instance_method(:keyword_args)) #=> true
#
def self.has_kwarg?(method) # rubocop:disable Naming/PredicateName
method.parameters.any? do |param, _|
param == :keyreq || param == :key || param == :keyrest # rubocop:disable Style/MultipleComparison
end
end
# Determine whether `method` takes only *required* args.
#
# These are the types of required args:
#
# * *Required* -- ex: `def foo(a)`
# * *Keyword Required* -- ex: `def foo(a:)`
#
# @param method [Method, UnboundMethod]
# Arguments of this method will be checked
#
# @return [Boolean]
# Return `true` if `method` accepts only required arguments
#
# @example
# class Ex
# def optional_args(a=1, b: 1)
# end
#
# def required_args(a, b:)
# end
# end
#
# MemoWise::InternalAPI.
# has_only_required_args?(Ex.instance_method(:optional_args))
# #=> false
#
# MemoWise::InternalAPI.
# has_only_required_args?(Ex.instance_method(:required_args))
# #=> true
def self.has_only_required_args?(method) # rubocop:disable Naming/PredicateName
method.parameters.all? { |type, _| type == :req || type == :keyreq } # rubocop:disable Style/MultipleComparison
end
# Find the original class for which the given class is the corresponding
# "singleton class".
#
# See https://stackoverflow.com/questions/54531270/retrieve-a-ruby-object-from-its-singleton-class
#
# @param klass [Class]
# Singleton class to find the original class of
#
# @return Class
# Original class for which `klass` is the singleton class.
#
# @raise ArgumentError
# Raises if `klass` is not a singleton class.
#
def self.original_class_from_singleton(klass)
unless klass.singleton_class?
raise ArgumentError, "Must be a singleton class: #{klass.inspect}"
end
# Search ObjectSpace
# * 1:1 relationship of singleton class to original class is documented
# * Performance concern: searches all Class objects
# But, only runs at load time
ObjectSpace.each_object(Class).find { |cls| cls.singleton_class == klass }
end
# Convention we use for renaming the original method when we replace with
# the memoized version in {MemoWise.memo_wise}.
#
# @param method_name [Symbol]
# Name for which to return the renaming for the original method
#
# @return [Symbol]
# Renamed method to use for the original method with name `method_name`
#
def self.original_memo_wised_name(method_name)
:"_memo_wise_original_#{method_name}"
end
# @param target [Class, Module]
# The class to which we are prepending MemoWise to provide memoization;
# the `InternalAPI` *instance* methods will refer to this `target` class.
def initialize(target)
@target = target
end
# @return [Class, Module]
attr_reader :target
# Returns the "fetch key" for the given `method_name` and parameters, to be
# used to lookup the memoized results specifically for this method and these
# parameters.
#
# @param method_name [Symbol]
# Name of method to derive the "fetch key" for, with given parameters.
# @param args [Array]
# Zero or more positional parameters
# @param kwargs [Hash]
# Zero or more keyword parameters
#
# @return [Array, Hash, Object]
# Returns one of:
# - An `Array` if only positional parameters.
# - A nested `Array<Array, Hash>` if *both* positional and keyword.
# - A `Hash` if only keyword parameters.
# - A single object if there is only a single parameter.
def fetch_key(method_name, *args, **kwargs)
method = target_class.instance_method(method_name)
if MemoWise::InternalAPI.has_only_required_args?(method)
key = method.parameters.map.with_index do |(type, name), index|
type == :req ? args[index] : kwargs[name]
end
key.size == 1 ? key.first : [method_name, *key].hash
else
has_arg = MemoWise::InternalAPI.has_arg?(method)
if has_arg && MemoWise::InternalAPI.has_kwarg?(method)
[method_name, args, kwargs].hash
elsif has_arg
args.hash
else
kwargs.hash
end
end
end
# Returns whether the given method should use an array's hash value as the
# cache lookup key. See the comments in `.create_memo_wise_state!` for an
# example.
#
# @param method_name [Symbol]
# Name of memoized method we're checking the implementation of
#
# @return [Boolean] true iff the method uses a hashed cache key; false
# otherwise
def use_hashed_key?(method_name)
method = target_class.instance_method(method_name)
if MemoWise::InternalAPI.has_arg?(method) &&
MemoWise::InternalAPI.has_kwarg?(method)
return true
end
MemoWise::InternalAPI.has_only_required_args?(method) &&
method.parameters.size > 1
end
# Returns visibility of an instance method defined on class `target`.
#
# @param method_name [Symbol]
# Name of existing *instance* method find the visibility of.
#
# @return [:private, :protected, :public]
# Visibility of existing instance method of the class.
#
# @raise ArgumentError
# Raises `ArgumentError` unless `method_name` is a `Symbol` corresponding
# to an existing **instance** method defined on `klass`.
#
def method_visibility(method_name)
if target.private_method_defined?(method_name)
:private
elsif target.protected_method_defined?(method_name)
:protected
elsif target.public_method_defined?(method_name)
:public
else
raise ArgumentError,
"#{method_name.inspect} must be a method on #{target}"
end
end
# Validates that {.memo_wise} has already been called on `method_name`.
#
# @param method_name [Symbol]
# Name of method to validate has already been setup with {.memo_wise}
def validate_memo_wised!(method_name)
original_name = self.class.original_memo_wised_name(method_name)
unless target_class.private_method_defined?(original_name)
raise ArgumentError, "#{method_name} is not a memo_wised method"
end
end
private
# @return [Class] where we look for method definitions
def target_class
if target.instance_of?(Class)
# A class's methods are defined in its singleton class
target.singleton_class
else
# An object's methods are defined in its class
target.class
end
end
end
end