Debian Codegraph @

rpython/rlib/rstrategies/rstrategies.py

raw symbols SCIP
1
2 import weakref, sys
3 from rpython.rlib.rstrategies import logger
4 from rpython.rlib import jit, objectmodel, rerased, rarithmetic
5 from rpython.rlib.objectmodel import specialize, not_rpython
6
7 def make_accessors(strategy='strategy', storage='storage'):
8 """
9 Instead of using this generator, the methods can be implemented manually.
10 A third way is to overwrite the getter/setter methods in StrategyFactory.
11 """
12 def make_getter(attr):
13 def getter(self): return getattr(self, attr)
14 return getter
15 def make_setter(attr):
16 def setter(self, val): setattr(self, attr, val)
17 return setter
18 classdef = sys._getframe(1).f_locals
19 classdef['_get_strategy'] = make_getter(strategy)
20 classdef['_set_strategy'] = make_setter(strategy)
21 classdef['_get_storage'] = make_getter(storage)
22 classdef['_set_storage'] = make_setter(storage)
23
24 class StrategyMetaclass(type):
25 """
26 A metaclass is required, because we need certain attributes to be special
27 for every single strategy class.
28 """
29 def __new__(self, name, bases, attrs):
30 attrs['_is_strategy'] = False
31 attrs['_is_singleton'] = False
32 attrs['_specializations'] = []
33 # Not every strategy uses rerased-pairs, but they won't hurt
34 erase, unerase = rerased.new_erasing_pair(name)
35 def get_storage(self, w_self):
36 erased = self.strategy_factory().get_storage(w_self)
37 return unerase(erased)
38 def set_storage(self, w_self, storage):
39 erased = erase(storage)
40 self.strategy_factory().set_storage(w_self, erased)
41 attrs['get_storage'] = get_storage
42 attrs['set_storage'] = set_storage
43 return type.__new__(self, name, bases, attrs)
44
45 def strategy(generalize=None, singleton=True):
46 """
47 Strategy classes must be decorated with this.
48 generalize is a list of other strategies, that can be switched to from the decorated strategy.
49 If the singleton flag is set to False, new strategy instances will be created,
50 instead of always reusing the singleton object.
51 """
52 def decorator(strategy_class):
53 # Patch strategy class: Add generalized_strategy_for and mark as strategy class.
54 if generalize:
55 @jit.unroll_safe
56 def generalized_strategy_for(self, value):
57 # TODO - optimize this method
58 for strategy in generalize:
59 if self.strategy_factory().strategy_singleton_instance(strategy)._check_can_handle(value):
60 return strategy
61 raise Exception("Could not find generalized strategy for %s coming from %s" % (value, self))
62 strategy_class.generalized_strategy_for = generalized_strategy_for
63 for generalized in generalize:
64 generalized._specializations.append(strategy_class)
65 strategy_class._is_strategy = True
66 strategy_class._generalizations = generalize
67 strategy_class._is_singleton = singleton
68 return strategy_class
69 return decorator
70
71 class StrategyFactory(object):
72 _immutable_fields_ = ["strategies[*]", "logger", "strategy_singleton_field"]
73 factory_instance_counter = 0
74
75 def __init__(self, root_class, all_strategy_classes=None):
76 if all_strategy_classes is None:
77 all_strategy_classes = self._collect_subclasses(root_class)
78 self.strategies = []
79 self.logger = logger.Logger()
80
81 # This is to avoid confusion between multiple factories existing simultaneously (e.g. in tests)
82 self.strategy_singleton_field = "__singleton_%i" % StrategyFactory.factory_instance_counter
83 StrategyFactory.factory_instance_counter += 1
84
85 self._create_strategy_instances(root_class, all_strategy_classes)
86
87 def _create_strategy_instances(self, root_class, all_strategy_classes):
88 for strategy_class in all_strategy_classes:
89 if strategy_class._is_strategy:
90 setattr(strategy_class, self.strategy_singleton_field, self.instantiate_strategy(strategy_class))
91 self.strategies.append(strategy_class)
92 self._patch_strategy_class(strategy_class, root_class)
93 self._order_strategies()
94
95 # =============================
96 # API methods
97 # =============================
98
99 def switch_strategy(self, w_self, new_strategy_type, new_element=None):
100 """
101 Switch the strategy of w_self to the new type.
102 new_element can be given as as hint, purely for logging purposes.
103 It should be the object that was added to w_self, causing the strategy switch.
104 """
105 old_strategy = self.get_strategy(w_self)
106 if new_strategy_type._is_singleton:
107 new_strategy = self.strategy_singleton_instance(new_strategy_type)
108 else:
109 size = old_strategy.size(w_self)
110 new_strategy = self.instantiate_strategy(new_strategy_type, w_self, size)
111 self.set_strategy(w_self, new_strategy)
112 old_strategy._convert_storage_to(w_self, new_strategy)
113 new_strategy.strategy_switched(w_self)
114 self.log(w_self, new_strategy, old_strategy, new_element)
115 return new_strategy
116
117 def set_initial_strategy(self, w_self, strategy_type, size, elements=None):
118 """
119 Initialize the strategy and storage fields of w_self.
120 This must be called before switch_strategy or any strategy method can be used.
121 elements is an optional list of values initially stored in w_self.
122 If given, then len(elements) == size must hold.
123 """
124 assert self.get_strategy(w_self) is None, "Strategy should not be initialized yet!"
125 if strategy_type._is_singleton:
126 strategy = self.strategy_singleton_instance(strategy_type)
127 else:
128 strategy = self.instantiate_strategy(strategy_type, w_self, size)
129 self.set_strategy(w_self, strategy)
130 strategy._initialize_storage(w_self, size)
131 element = None
132 if elements:
133 strategy.store_all(w_self, elements)
134 if len(elements) > 0: element = elements[0]
135 strategy.strategy_switched(w_self)
136 self.log(w_self, strategy, None, element)
137 return strategy
138
139 @jit.unroll_safe
140 def strategy_type_for(self, objects):
141 """
142 Return the best-fitting strategy to hold all given objects.
143 """
144 specialized_strategies = len(self.strategies)
145 can_handle = [True] * specialized_strategies
146 for obj in objects:
147 if specialized_strategies <= 1:
148 break
149 for i, strategy in enumerate(self.strategies):
150 if can_handle[i] and not self.strategy_singleton_instance(strategy)._check_can_handle(obj):
151 can_handle[i] = False
152 specialized_strategies -= 1
153 for i, strategy_type in enumerate(self.strategies):
154 if can_handle[i]:
155 return strategy_type
156 raise ValueError("Could not find strategy to handle: %s" % objects)
157
158 @not_rpython
159 def decorate_strategies(self, transitions):
160 """
161 As an alternative to decorating all strategies with @strategy,
162 invoke this in the constructor of your StrategyFactory subclass, before
163 calling __init__. transitions is a dict mapping all strategy classes to
164 their 'generalize' list parameter (see @strategy decorator).
165 """
166 for strategy_class, generalized in transitions.items():
167 strategy(generalized)(strategy_class)
168
169 # =============================
170 # The following methods can be overwritten to customize certain aspects of the factory.
171 # =============================
172
173 def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0):
174 """
175 Return a functional instance of strategy_type.
176 Overwrite this if you need a non-default constructor.
177 The two additional parameters should be ignored for singleton-strategies.
178 """
179 return strategy_type()
180
181 def log(self, w_self, new_strategy, old_strategy=None, new_element=None):
182 """
183 This can be overwritten into a more appropriate call to self.logger.log
184 """
185 if not self.logger.active: return
186 new_strategy_str = self.log_string_for_object(new_strategy)
187 old_strategy_str = self.log_string_for_object(old_strategy)
188 element_typename = self.log_string_for_object(new_element)
189 size = new_strategy.size(w_self)
190 typename = ""
191 cause = "Switched" if old_strategy else "Created"
192 self.logger.log(new_strategy_str, size, cause, old_strategy_str, typename, element_typename)
193
194 @specialize.call_location()
195 def log_string_for_object(self, obj):
196 """
197 This can be overwritten instead of the entire log() method.
198 Keep the specialize-annotation in order to handle different kinds of objects here.
199 """
200 return obj.__class__.__name__ if obj else ""
201
202 # These storage accessors are specialized because the storage field is
203 # populated by erased-objects which seem to be incompatible sometimes.
204 @specialize.call_location()
205 def get_storage(self, obj):
206 return obj._get_storage()
207 @specialize.call_location()
208 def set_storage(self, obj, val):
209 return obj._set_storage(val)
210
211 def get_strategy(self, obj):
212 return obj._get_strategy()
213 def set_strategy(self, obj, val):
214 return obj._set_strategy(val)
215
216 # =============================
217 # Internal methods
218 # =============================
219
220 @not_rpython
221 def _patch_strategy_class(self, strategy_class, root_class):
222 # Patch root class: Add default handler for visitor
223 def _convert_storage_from_OTHER(self, w_self, previous_strategy):
224 self._convert_storage_from(w_self, previous_strategy)
225 funcname = "_convert_storage_from_" + strategy_class.__name__
226 _convert_storage_from_OTHER.__name__ = funcname
227 setattr(root_class, funcname, _convert_storage_from_OTHER)
228
229 # Patch strategy class: Add polymorphic visitor function
230 def _convert_storage_to(self, w_self, new_strategy):
231 getattr(new_strategy, funcname)(w_self, self)
232 strategy_class._convert_storage_to = _convert_storage_to
233
234 @not_rpython
235 def _collect_subclasses(self, cls):
236 subclasses = []
237 for subcls in cls.__subclasses__():
238 subclasses.append(subcls)
239 subclasses.extend(self._collect_subclasses(subcls))
240 return subclasses
241
242 @not_rpython
243 def _order_strategies(self):
244 def get_generalization_depth(strategy, visited=None):
245 if visited is None:
246 visited = set()
247 if strategy._generalizations:
248 if strategy in visited:
249 raise Exception("Cycle in generalization-tree of %s" % strategy)
250 visited.add(strategy)
251 depth = 0
252 for generalization in strategy._generalizations:
253 other_depth = get_generalization_depth(generalization, set(visited))
254 depth = max(depth, other_depth)
255 return depth + 1
256 else:
257 return 0
258 self.strategies.sort(key=get_generalization_depth, reverse=True)
259
260 @jit.elidable
261 def strategy_singleton_instance(self, strategy_class):
262 return getattr(strategy_class, self.strategy_singleton_field)
263
264 def _freeze_(self):
265 # Instance will be frozen at compile time, making accesses constant.
266 # The constructor does meta stuff which is not possible after translation.
267 return True
268
269 class AbstractStrategy(object):
270 """
271 == Required:
272 strategy_factory(self) - Access to StorageFactory
273 """
274
275 def strategy_switched(self, w_self):
276 # Overwrite this method for a hook whenever the strategy
277 # of w_self was switched to self.
278 pass
279
280 # Main Fixedsize API
281
282 def store(self, w_self, index0, value):
283 raise NotImplementedError("Abstract method")
284
285 def fetch(self, w_self, index0):
286 raise NotImplementedError("Abstract method")
287
288 def size(self, w_self):
289 raise NotImplementedError("Abstract method")
290
291 # Fixedsize utility methods
292
293 def slice(self, w_self, start, end):
294 return [ self.fetch(w_self, i) for i in range(start, end)]
295
296 def fetch_all(self, w_self):
297 return self.slice(w_self, 0, self.size(w_self))
298
299 def store_all(self, w_self, elements):
300 for i, e in enumerate(elements):
301 self.store(w_self, i, e)
302
303 # Main Varsize API
304
305 def insert(self, w_self, index0, list_w):
306 raise NotImplementedError("Abstract method")
307
308 def delete(self, w_self, start, end):
309 raise NotImplementedError("Abstract method")
310
311 # Varsize utility methods
312
313 def append(self, w_self, list_w):
314 self.insert(w_self, self.size(w_self), list_w)
315
316 def pop(self, w_self, index0):
317 e = self.fetch(w_self, index0)
318 self.delete(w_self, index0, index0+1)
319 return e
320
321 # Internal methods
322
323 def _initialize_storage(self, w_self, initial_size):
324 raise NotImplementedError("Abstract method")
325
326 def _check_can_handle(self, value):
327 raise NotImplementedError("Abstract method")
328
329 def _convert_storage_to(self, w_self, new_strategy):
330 # This will be overwritten in _patch_strategy_class
331 new_strategy._convert_storage_from(w_self, self)
332
333 @jit.unroll_safe
334 def _convert_storage_from(self, w_self, previous_strategy):
335 # This is a very unefficient (but most generic) way to do this.
336 # Subclasses should specialize.
337 storage = previous_strategy.fetch_all(w_self)
338 self._initialize_storage(w_self, previous_strategy.size(w_self))
339 for i, field in enumerate(storage):
340 self.store(w_self, i, field)
341
342 def _generalize_for_value(self, w_self, value):
343 strategy_type = self.generalized_strategy_for(value)
344 new_instance = self.strategy_factory().switch_strategy(w_self, strategy_type, new_element=value)
345 return new_instance
346
347 def _cannot_handle_store(self, w_self, index0, value):
348 new_instance = self._generalize_for_value(w_self, value)
349 new_instance.store(w_self, index0, value)
350
351 def _cannot_handle_insert(self, w_self, index0, list_w):
352 # TODO - optimize. Prevent multiple generalizations and slicing done by callers.
353 new_strategy = self._generalize_for_value(w_self, list_w[0])
354 new_strategy.insert(w_self, index0, list_w)
355
356 # ============== Special Strategies with no storage array ==============
357
358 class EmptyStrategy(AbstractStrategy):
359 # == Required:
360 # See AbstractStrategy
361
362 def _initialize_storage(self, w_self, initial_size):
363 assert initial_size == 0
364 self.set_storage(w_self, None)
365 def _convert_storage_from(self, w_self, previous_strategy):
366 self.set_storage(w_self, None)
367 def _check_can_handle(self, value):
368 return False
369
370 def fetch(self, w_self, index0):
371 raise IndexError
372 def store(self, w_self, index0, value):
373 self._cannot_handle_store(w_self, index0, [value])
374 def insert(self, w_self, index0, list_w):
375 self._cannot_handle_insert(w_self, index0, list_w)
376 def delete(self, w_self, start, end):
377 self.check_index_range(w_self, start, end)
378 def size(self, w_self):
379 return 0
380
381 class SingleValueStrategyStorage(object):
382 """Small container object for a size value."""
383 _attrs_ = ['size']
384 def __init__(self, size=0):
385 self.size = size
386
387 class SingleValueStrategy(AbstractStrategy):
388 # == Required:
389 # See AbstractStrategy
390 # check_index_*(...) - use mixin SafeIndexingMixin or UnsafeIndexingMixin
391 # value(self) - the single value contained in this strategy. Should be constant.
392
393 def _initialize_storage(self, w_self, initial_size):
394 storage_obj = SingleValueStrategyStorage(initial_size)
395 self.set_storage(w_self, storage_obj)
396 def _convert_storage_from(self, w_self, previous_strategy):
397 self._initialize_storage(w_self, previous_strategy.size(w_self))
398 def _check_can_handle(self, value):
399 return value is self.value()
400
401 def fetch(self, w_self, index0):
402 self.check_index_fetch(w_self, index0)
403 return self.value()
404 def store(self, w_self, index0, value):
405 self.check_index_store(w_self, index0)
406 if self._check_can_handle(value):
407 return
408 self._cannot_handle_store(w_self, index0, value)
409 def delete(self, w_self, start, end):
410 self.check_index_range(w_self, start, end)
411 self.get_storage(w_self).size -= (end - start)
412 def size(self, w_self):
413 return self.get_storage(w_self).size
414
415 @jit.unroll_safe
416 def insert(self, w_self, index0, list_w):
417 storage_obj = self.get_storage(w_self)
418 for i in range(len(list_w)):
419 if self._check_can_handle(list_w[i]):
420 storage_obj.size += 1
421 else:
422 self._cannot_handle_insert(w_self, index0 + i, list_w[i:])
423 return
424
425 # ============== Basic strategies with storage ==============
426
427 class StrategyWithStorage(AbstractStrategy):
428 # == Required:
429 # See AbstractStrategy
430 # check_index_*(...) - use mixin SafeIndexingMixin or UnsafeIndexingMixin
431 # default_value(self) - The value to be initially contained in this strategy
432
433 def _initialize_storage(self, w_self, initial_size):
434 default = self._unwrap(self.default_value())
435 self.set_storage(w_self, [default] * initial_size)
436
437 @jit.unroll_safe
438 def _convert_storage_from(self, w_self, previous_strategy):
439 size = previous_strategy.size(w_self)
440 new_storage = [ self._unwrap(previous_strategy.fetch(w_self, i))
441 for i in range(size) ]
442 self.set_storage(w_self, new_storage)
443
444 def store(self, w_self, index0, wrapped_value):
445 self.check_index_store(w_self, index0)
446 assert index0 >= 0
447 if self._check_can_handle(wrapped_value):
448 unwrapped = self._unwrap(wrapped_value)
449 self.get_storage(w_self)[index0] = unwrapped
450 else:
451 self._cannot_handle_store(w_self, index0, wrapped_value)
452
453 def fetch(self, w_self, index0):
454 self.check_index_fetch(w_self, index0)
455 assert index0 >= 0
456 unwrapped = self.get_storage(w_self)[index0]
457 return self._wrap(unwrapped)
458
459 def _wrap(self, value):
460 raise NotImplementedError("Abstract method")
461
462 def _unwrap(self, value):
463 raise NotImplementedError("Abstract method")
464
465 def size(self, w_self):
466 return len(self.get_storage(w_self))
467
468 @jit.unroll_safe
469 def insert(self, w_self, start, list_w):
470 # This is following Python's behaviour - insert automatically
471 # happens at the beginning of an array, even if index is larger
472 if start > self.size(w_self):
473 start = self.size(w_self)
474 for i in range(len(list_w)):
475 if self._check_can_handle(list_w[i]):
476 self.get_storage(w_self).insert(start + i, self._unwrap(list_w[i]))
477 else:
478 self._cannot_handle_insert(w_self, start + i, list_w[i:])
479 return
480
481 def delete(self, w_self, start, end):
482 self.check_index_range(w_self, start, end)
483 assert start >= 0 and end >= 0
484 del self.get_storage(w_self)[start : end]
485
486 class GenericStrategy(StrategyWithStorage):
487 # == Required:
488 # See StrategyWithStorage
489
490 def _wrap(self, value):
491 return value
492 def _unwrap(self, value):
493 return value
494 def _check_can_handle(self, wrapped_value):
495 return True
496
497 class WeakGenericStrategy(StrategyWithStorage):
498 # == Required:
499 # See StrategyWithStorage
500
501 def _wrap(self, value):
502 return value() or self.default_value()
503 def _unwrap(self, value):
504 assert value is not None
505 return weakref.ref(value)
506 def _check_can_handle(self, wrapped_value):
507 return True
508
509 # ============== Mixins for index checking operations ==============
510
511 class SafeIndexingMixin(object):
512 def check_index_store(self, w_self, index0):
513 self.check_index(w_self, index0)
514 def check_index_fetch(self, w_self, index0):
515 self.check_index(w_self, index0)
516 def check_index_range(self, w_self, start, end):
517 if end < start:
518 raise IndexError
519 self.check_index(w_self, start)
520 self.check_index(w_self, end)
521 def check_index(self, w_self, index0):
522 if not rarithmetic.int_between(0, index0, self.size(w_self)):
523 raise IndexError
524
525 class UnsafeIndexingMixin(object):
526 def check_index_store(self, w_self, index0):
527 pass
528 def check_index_fetch(self, w_self, index0):
529 pass
530 def check_index_range(self, w_self, start, end):
531 pass
532
533 # ============== Specialized Storage Strategies ==============
534
535 class SpecializedStrategy(StrategyWithStorage):
536 # == Required:
537 # See StrategyWithStorage
538 # wrap(self, value) - Return a boxed object for the primitive value
539 # unwrap(self, value) - Return the unboxed primitive value of value
540
541 def _unwrap(self, value):
542 return self.unwrap(value)
543 def _wrap(self, value):
544 return self.wrap(value)
545
546 class SingleTypeStrategy(SpecializedStrategy):
547 # == Required Functions:
548 # See SpecializedStrategy
549 # contained_type - The wrapped type that can be stored in this strategy
550
551 def _check_can_handle(self, value):
552 return isinstance(value, self.contained_type)
553
554 class TaggingStrategy(SingleTypeStrategy):
555 """This strategy uses a special tag value to represent a single additional object."""
556 # == Required:
557 # See SingleTypeStrategy
558 # wrapped_tagged_value(self) - The tagged object
559 # unwrapped_tagged_value(self) - The unwrapped tag value representing the tagged object
560
561 def _check_can_handle(self, value):
562 return value is self.wrapped_tagged_value() or \
563 (isinstance(value, self.contained_type) and \
564 self.unwrap(value) != self.unwrapped_tagged_value())
565
566 def _unwrap(self, value):
567 if value is self.wrapped_tagged_value():
568 return self.unwrapped_tagged_value()
569 return self.unwrap(value)
570
571 def _wrap(self, value):
572 if value == self.unwrapped_tagged_value():
573 return self.wrapped_tagged_value()
574 return self.wrap(value)