Debian Codegraph @

rpython/annotator/bookkeeper.py

raw symbols SCIP
1 """
2 The Bookkeeper class.
3 """
4
5 from __future__ import absolute_import
6
7 import sys, types, inspect, weakref
8 from contextlib import contextmanager
9 from collections import OrderedDict
10
11 from rpython.flowspace.model import Constant
12 from rpython.flowspace.bytecode import cpython_code_signature
13 from rpython.annotator.model import (
14 SomeOrderedDict, SomeString, SomeChar, SomeFloat, unionof, SomeInstance,
15 SomeDict, SomeBuiltin, SomePBC, SomeInteger, TLS, SomeUnicodeCodePoint,
16 s_None, s_ImpossibleValue, SomeBool, SomeTuple, SomeException,
17 SomeImpossibleValue, SomeUnicodeString, SomeList, HarmlesslyBlocked,
18 SomeWeakRef, SomeByteArray, SomeConstantType, SomeProperty,
19 AnnotatorError)
20 from rpython.annotator.classdesc import ClassDef, ClassDesc
21 from rpython.annotator.listdef import ListDef, ListItem
22 from rpython.annotator.dictdef import DictDef
23 from rpython.annotator import description
24 from rpython.annotator.signature import annotationoftype
25 from rpython.annotator.argument import simple_args
26 from rpython.annotator.specialize import memo
27 from rpython.rlib.objectmodel import r_dict, r_ordereddict, Symbolic
28 from rpython.tool.algo.unionfind import UnionFind
29 from rpython.rtyper import extregistry
30
31
32 BUILTIN_ANALYZERS = {}
33
34 def analyzer_for(func):
35 def wrapped(ann_func):
36 BUILTIN_ANALYZERS[func] = ann_func
37 return ann_func
38 return wrapped
39
40 class Bookkeeper(object):
41 """The log of choices that have been made while analysing the operations.
42 It ensures that the same 'choice objects' will be returned if we ask
43 again during reflowing. Like ExecutionContext, there is an implicit
44 Bookkeeper that can be obtained from a thread-local variable.
45
46 Currently used for factories and user-defined classes."""
47
48 def __setstate__(self, dic):
49 self.__dict__.update(dic) # normal action
50 self.register_builtins()
51
52 def __init__(self, annotator):
53 self.annotator = annotator
54 self.policy = annotator.policy
55 self.descs = {} # map Python objects to their XxxDesc wrappers
56 self.methoddescs = {} # map (funcdesc, classdef) to the MethodDesc
57 self.classdefs = [] # list of all ClassDefs
58 self.seen_mutable = {}
59 self.listdefs = {} # map position_keys to ListDefs
60 self.dictdefs = {} # map position_keys to DictDefs
61 self.immutable_cache = {}
62
63 self.classpbc_attr_families = {} # {'attr': UnionFind(ClassAttrFamily)}
64 self.frozenpbc_attr_families = UnionFind(description.FrozenAttrFamily)
65 self.pbc_maximal_call_families = UnionFind(description.CallFamily)
66
67 self.emulated_pbc_calls = {}
68 self.all_specializations = {} # {FuncDesc: specialization-info}
69 self.pending_specializations = [] # list of callbacks
70 self.external_class_cache = {} # cache of ExternalType classes
71
72 self.needs_generic_instantiate = {}
73 self.thread_local_fields = set()
74 self.memory_pressure_types = set()
75
76 self.register_builtins()
77
78 def register_builtins(self):
79 import rpython.annotator.builtin # for side-effects
80 from rpython.annotator.exception import standardexceptions
81 for cls in standardexceptions:
82 self.getuniqueclassdef(cls)
83
84 def enter(self, position_key):
85 """Start of an operation.
86 The operation is uniquely identified by the given key."""
87 assert not hasattr(self, 'position_key'), "don't call enter() nestedly"
88 self.position_key = position_key
89 TLS.bookkeeper = self
90
91 def leave(self):
92 """End of an operation."""
93 del TLS.bookkeeper
94 del self.position_key
95
96 @contextmanager
97 def at_position(self, pos):
98 """A context manager calling `self.enter()` and `self.leave()`"""
99 if hasattr(self, 'position_key') and pos is None:
100 yield
101 return
102 self.enter(pos)
103 try:
104 yield
105 finally:
106 self.leave()
107
108 def compute_at_fixpoint(self):
109 # getbookkeeper() needs to work during this function, so provide
110 # one with a dummy position
111 with self.at_position(None):
112 for call_op in self.annotator.call_sites():
113 self.consider_call_site(call_op)
114
115 for pbc, args_s in self.emulated_pbc_calls.itervalues():
116 args = simple_args(args_s)
117 pbc.consider_call_site(args, s_ImpossibleValue, None)
118 self.emulated_pbc_calls = {}
119
120 def check_no_flags_on_instances(self):
121 # sanity check: no flags attached to heap stored instances
122 seen = set()
123
124 def check_no_flags(s_value_or_def):
125 if isinstance(s_value_or_def, SomeInstance):
126 assert not s_value_or_def.flags, "instance annotation with flags escaped to the heap"
127 check_no_flags(s_value_or_def.classdef)
128 elif isinstance(s_value_or_def, SomeList):
129 check_no_flags(s_value_or_def.listdef.listitem)
130 elif isinstance(s_value_or_def, SomeDict):
131 check_no_flags(s_value_or_def.dictdef.dictkey)
132 check_no_flags(s_value_or_def.dictdef.dictvalue)
133 elif isinstance(s_value_or_def, SomeTuple):
134 for s_item in s_value_or_def.items:
135 check_no_flags(s_item)
136 elif isinstance(s_value_or_def, ClassDef):
137 if s_value_or_def in seen:
138 return
139 seen.add(s_value_or_def)
140 for attr in s_value_or_def.attrs.itervalues():
141 s_attr = attr.s_value
142 check_no_flags(s_attr)
143 elif isinstance(s_value_or_def, ListItem):
144 if s_value_or_def in seen:
145 return
146 seen.add(s_value_or_def)
147 check_no_flags(s_value_or_def.s_value)
148
149 for clsdef in self.classdefs:
150 check_no_flags(clsdef)
151
152 def consider_call_site(self, call_op):
153 from rpython.rtyper.llannotation import SomeLLADTMeth, lltype_to_annotation
154 annotation = self.annotator.annotation
155 s_callable = annotation(call_op.args[0])
156 args_s = [annotation(arg) for arg in call_op.args[1:]]
157 if isinstance(s_callable, SomeLLADTMeth):
158 adtmeth = s_callable
159 s_callable = self.immutablevalue(adtmeth.func)
160 args_s = [lltype_to_annotation(adtmeth.ll_ptrtype)] + args_s
161 if isinstance(s_callable, SomePBC):
162 s_result = annotation(call_op.result)
163 if s_result is None:
164 s_result = s_ImpossibleValue
165 args = call_op.build_args(args_s)
166 s_callable.consider_call_site(args, s_result, call_op)
167
168 def getuniqueclassdef(self, cls):
169 """Get the ClassDef associated with the given user cls."""
170 assert cls is not object
171 desc = self.getdesc(cls)
172 return desc.getuniqueclassdef()
173
174 def new_exception(self, exc_classes):
175 clsdefs = {self.getuniqueclassdef(cls) for cls in exc_classes}
176 return SomeException(clsdefs)
177
178 def getlistdef(self, **flags_if_new):
179 """Get the ListDef associated with the current position."""
180 try:
181 listdef = self.listdefs[self.position_key]
182 except KeyError:
183 listdef = self.listdefs[self.position_key] = ListDef(self)
184 listdef.listitem.__dict__.update(flags_if_new)
185 return listdef
186
187 def newlist(self, *s_values, **flags):
188 """Make a SomeList associated with the current position, general
189 enough to contain the s_values as items."""
190 listdef = self.getlistdef(**flags)
191 for s_value in s_values:
192 listdef.generalize(s_value)
193 if flags:
194 assert flags.keys() == ['range_step']
195 listdef.generalize_range_step(flags['range_step'])
196 return SomeList(listdef)
197
198 def getdictdef(self, is_r_dict=False, force_non_null=False, simple_hash_eq=False):
199 """Get the DictDef associated with the current position."""
200 try:
201 dictdef = self.dictdefs[self.position_key]
202 except KeyError:
203 dictdef = DictDef(self, is_r_dict=is_r_dict,
204 force_non_null=force_non_null,
205 simple_hash_eq=simple_hash_eq)
206 self.dictdefs[self.position_key] = dictdef
207 return dictdef
208
209 def newdict(self):
210 """Make a so-far empty SomeDict associated with the current
211 position."""
212 return SomeDict(self.getdictdef())
213
214 def immutablevalue(self, x):
215 """The most precise SomeValue instance that contains the
216 immutable value x."""
217 # convert unbound methods to the underlying function
218 if hasattr(x, 'im_self') and x.im_self is None:
219 x = x.im_func
220 assert not hasattr(x, 'im_self')
221 tp = type(x)
222 if issubclass(tp, Symbolic): # symbolic constants support
223 result = x.annotation()
224 result.const_box = Constant(x)
225 return result
226 if tp is bool:
227 result = SomeBool()
228 elif tp is int:
229 result = SomeInteger(nonneg = x>=0)
230 elif tp is long:
231 if -sys.maxint-1 <= x <= sys.maxint:
232 x = int(x)
233 result = SomeInteger(nonneg = x>=0)
234 else:
235 # XXX: better error reporting?
236 raise ValueError("seeing a prebuilt long (value %s)" % hex(x))
237 elif issubclass(tp, str): # py.lib uses annotated str subclasses
238 no_nul = not '\x00' in x
239 if len(x) == 1:
240 result = SomeChar(no_nul=no_nul)
241 else:
242 result = SomeString(no_nul=no_nul)
243 elif tp is unicode:
244 no_nul = not u'\x00' in x
245 if len(x) == 1:
246 result = SomeUnicodeCodePoint(no_nul=no_nul)
247 else:
248 result = SomeUnicodeString(no_nul=no_nul)
249 elif tp is bytearray:
250 result = SomeByteArray()
251 elif tp is tuple:
252 result = SomeTuple(items = [self.immutablevalue(e) for e in x])
253 elif tp is float:
254 result = SomeFloat()
255 elif tp is list:
256 key = Constant(x)
257 try:
258 return self.immutable_cache[key]
259 except KeyError:
260 result = SomeList(ListDef(self, s_ImpossibleValue))
261 self.immutable_cache[key] = result
262 for e in x:
263 result.listdef.generalize(self.immutablevalue(e))
264 result.const_box = key
265 return result
266 elif (tp is dict or tp is r_dict or
267 tp is OrderedDict or tp is r_ordereddict):
268 key = Constant(x)
269 try:
270 return self.immutable_cache[key]
271 except KeyError:
272 if tp is OrderedDict or tp is r_ordereddict:
273 cls = SomeOrderedDict
274 else:
275 cls = SomeDict
276 is_r_dict = issubclass(tp, r_dict)
277 result = cls(DictDef(self,
278 s_ImpossibleValue,
279 s_ImpossibleValue,
280 is_r_dict = is_r_dict))
281 self.immutable_cache[key] = result
282 if is_r_dict:
283 s_eqfn = self.immutablevalue(x.key_eq)
284 s_hashfn = self.immutablevalue(x.key_hash)
285 result.dictdef.dictkey.update_rdict_annotations(s_eqfn,
286 s_hashfn)
287 seen_elements = 0
288 while seen_elements != len(x):
289 items = x.items()
290 for ek, ev in items:
291 result.dictdef.generalize_key(self.immutablevalue(ek))
292 result.dictdef.generalize_value(self.immutablevalue(ev))
293 #dictdef.seen_prebuilt_key(ek)---not needed any more
294 seen_elements = len(items)
295 # if the dictionary grew during the iteration,
296 # start over again
297 result.const_box = key
298 return result
299 elif tp is weakref.ReferenceType:
300 x1 = x()
301 if x1 is None:
302 result = SomeWeakRef(None) # dead weakref
303 else:
304 s1 = self.immutablevalue(x1)
305 assert isinstance(s1, SomeInstance)
306 result = SomeWeakRef(s1.classdef)
307 elif tp is property:
308 return SomeProperty(x)
309 elif ishashable(x) and x in BUILTIN_ANALYZERS:
310 _module = getattr(x,"__module__","unknown")
311 result = SomeBuiltin(BUILTIN_ANALYZERS[x], methodname="%s.%s" % (_module, x.__name__))
312 elif extregistry.is_registered(x):
313 entry = extregistry.lookup(x)
314 result = entry.compute_annotation_bk(self)
315 elif tp is type:
316 result = SomeConstantType(x, self)
317 elif callable(x):
318 if hasattr(x, 'im_self') and hasattr(x, 'im_func'):
319 # on top of PyPy, for cases like 'l.append' where 'l' is a
320 # global constant list, the find_method() returns non-None
321 s_self = self.immutablevalue(x.im_self)
322 result = s_self.find_method(x.im_func.__name__)
323 elif hasattr(x, '__self__') and x.__self__ is not None:
324 # for cases like 'l.append' where 'l' is a global constant list
325 s_self = self.immutablevalue(x.__self__)
326 result = s_self.find_method(x.__name__)
327 assert result is not None
328 else:
329 result = None
330 if result is None:
331 result = SomePBC([self.getdesc(x)])
332 elif hasattr(x, '_freeze_'):
333 assert x._freeze_() is True
334 # user-defined classes can define a method _freeze_(), which
335 # is called when a prebuilt instance is found. If the method
336 # returns True, the instance is considered immutable and becomes
337 # a SomePBC(). Otherwise it's just SomeInstance().
338 result = SomePBC([self.getdesc(x)])
339 elif hasattr(x, '__class__') \
340 and x.__class__.__module__ != '__builtin__':
341 if hasattr(x, '_cleanup_'):
342 x._cleanup_()
343 classdef = self.getuniqueclassdef(x.__class__)
344 classdef.see_instance(x)
345 result = SomeInstance(classdef)
346 elif x is None:
347 return s_None
348 else:
349 raise AnnotatorError("Don't know how to represent %r" % (x,))
350 result.const = x
351 return result
352
353 def getdesc(self, pyobj):
354 # get the XxxDesc wrapper for the given Python object, which must be
355 # one of:
356 # * a user-defined Python function
357 # * a Python type or class (but not a built-in one like 'int')
358 # * a user-defined bound or unbound method object
359 # * a frozen pre-built constant (with _freeze_() == True)
360 # * a bound method of a frozen pre-built constant
361 obj_key = Constant(pyobj)
362 try:
363 return self.descs[obj_key]
364 except KeyError:
365 if isinstance(pyobj, types.FunctionType):
366 result = self.newfuncdesc(pyobj)
367 elif isinstance(pyobj, (type, types.ClassType)):
368 if pyobj is object:
369 raise AnnotatorError("ClassDesc for object not supported")
370 if pyobj.__module__ == '__builtin__': # avoid making classdefs for builtin types
371 result = self.getfrozen(pyobj)
372 else:
373 result = ClassDesc(self, pyobj)
374 elif isinstance(pyobj, types.MethodType):
375 if pyobj.im_self is None: # unbound
376 return self.getdesc(pyobj.im_func)
377 if hasattr(pyobj.im_self, '_cleanup_'):
378 pyobj.im_self._cleanup_()
379 if hasattr(pyobj.im_self, '_freeze_'): # method of frozen
380 assert pyobj.im_self._freeze_() is True
381 result = description.MethodOfFrozenDesc(self,
382 self.getdesc(pyobj.im_func), # funcdesc
383 self.getdesc(pyobj.im_self)) # frozendesc
384 else: # regular method
385 origincls, name = origin_of_meth(pyobj)
386 classdef = self.getuniqueclassdef(pyobj.im_class)
387 classdef.see_instance(pyobj.im_self)
388 assert pyobj == getattr(pyobj.im_self, name), (
389 "%r is not %s.%s ??" % (pyobj, pyobj.im_self, name))
390 # emulate a getattr to make sure it's on the classdef
391 classdef.find_attribute(name)
392 result = self.getmethoddesc(
393 self.getdesc(pyobj.im_func), # funcdesc
394 self.getuniqueclassdef(origincls), # originclassdef
395 classdef, # selfclassdef
396 name)
397 else:
398 # must be a frozen pre-built constant, but let's check
399 if hasattr(pyobj, '_freeze_'):
400 assert pyobj._freeze_() is True
401 else:
402 if hasattr(pyobj, '__call__'):
403 msg = "object with a __call__ is not RPython"
404 else:
405 msg = "unexpected prebuilt constant"
406 raise AnnotatorError("%s: %r" % (msg, pyobj))
407 result = self.getfrozen(pyobj)
408 self.descs[obj_key] = result
409 return result
410
411 def newfuncdesc(self, pyfunc):
412 name = pyfunc.__name__
413 if hasattr(pyfunc, '_generator_next_method_of_'):
414 from rpython.flowspace.argument import Signature
415 signature = Signature(['entry']) # haaaaaack
416 defaults = ()
417 else:
418 signature = cpython_code_signature(pyfunc.__code__)
419 defaults = pyfunc.__defaults__
420 # get the specializer based on the tag of the 'pyobj'
421 # (if any), according to the current policy
422 tag = getattr(pyfunc, '_annspecialcase_', None)
423 specializer = self.annotator.policy.get_specializer(tag)
424 if specializer is memo:
425 return description.MemoDesc(self, pyfunc, name, signature, defaults, specializer)
426 return description.FunctionDesc(self, pyfunc, name, signature, defaults, specializer)
427
428 def getfrozen(self, pyobj):
429 return description.FrozenDesc(self, pyobj)
430
431 def getmethoddesc(self, funcdesc, originclassdef, selfclassdef, name,
432 flags={}):
433 flagskey = flags.items()
434 flagskey.sort()
435 key = funcdesc, originclassdef, selfclassdef, name, tuple(flagskey)
436 try:
437 return self.methoddescs[key]
438 except KeyError:
439 result = description.MethodDesc(self, funcdesc, originclassdef,
440 selfclassdef, name, flags)
441 self.methoddescs[key] = result
442 return result
443
444 def valueoftype(self, t):
445 return annotationoftype(t, self)
446
447 def get_classpbc_attr_families(self, attrname):
448 """Return the UnionFind for the ClassAttrFamilies corresponding to
449 attributes of the given name.
450 """
451 map = self.classpbc_attr_families
452 try:
453 access_sets = map[attrname]
454 except KeyError:
455 access_sets = map[attrname] = UnionFind(description.ClassAttrFamily)
456 return access_sets
457
458 def pbc_getattr(self, pbc, s_attr):
459 assert s_attr.is_constant()
460 attr = s_attr.const
461
462 descs = list(pbc.descriptions)
463 first = descs[0]
464 if len(descs) == 1:
465 return first.s_read_attribute(attr)
466
467 change = first.mergeattrfamilies(descs[1:], attr)
468 attrfamily = first.getattrfamily(attr)
469
470 position = self.position_key
471 attrfamily.read_locations[position] = True
472
473 actuals = []
474 for desc in descs:
475 actuals.append(desc.s_read_attribute(attr))
476 s_result = unionof(*actuals)
477
478 s_oldvalue = attrfamily.get_s_value(attr)
479 attrfamily.set_s_value(attr, unionof(s_result, s_oldvalue))
480
481 if change:
482 for position in attrfamily.read_locations:
483 self.annotator.reflowfromposition(position)
484
485 if isinstance(s_result, SomeImpossibleValue):
486 for desc in descs:
487 try:
488 attrs = desc.read_attribute('_attrs_')
489 except AttributeError:
490 continue
491 if isinstance(attrs, Constant):
492 attrs = attrs.value
493 if attr in attrs:
494 raise HarmlesslyBlocked("getattr on enforced attr")
495
496 return s_result
497
498 def getattr_locations(self, clsdesc, attrname):
499 attrdef = clsdesc.classdef.find_attribute(attrname)
500 return attrdef.read_locations
501
502 def record_getattr(self, clsdesc, attrname):
503 locations = self.getattr_locations(clsdesc, attrname)
504 locations.add(self.position_key)
505
506 def update_attr(self, clsdef, attrdef):
507 locations = self.getattr_locations(clsdef.classdesc, attrdef.name)
508 for position in locations:
509 self.annotator.reflowfromposition(position)
510 attrdef.validate(homedef=clsdef)
511
512 def pbc_call(self, pbc, args, emulated=None):
513 """Analyse a call to a SomePBC() with the given args (list of
514 annotations).
515 """
516 if emulated is None:
517 whence = self.position_key
518 # fish the existing annotation for the result variable,
519 # needed by some kinds of specialization.
520 fn, block, i = self.position_key
521 op = block.operations[i]
522 s_previous_result = self.annotator.annotation(op.result)
523 if s_previous_result is None:
524 s_previous_result = s_ImpossibleValue
525 else:
526 if emulated is True:
527 whence = None
528 else:
529 whence = emulated # callback case
530 op = None
531 s_previous_result = s_ImpossibleValue
532
533 results = []
534 for desc in pbc.descriptions:
535 results.append(desc.pycall(whence, args, s_previous_result, op))
536 s_result = unionof(*results)
537 return s_result
538
539 def emulate_pbc_call(self, unique_key, pbc, args_s, replace=[], callback=None):
540 """For annotating some operation that causes indirectly a Python
541 function to be called. The annotation of the function is "pbc",
542 and the list of annotations of arguments is "args_s".
543
544 Can be called in various contexts, but from compute_annotation()
545 or compute_result_annotation() of an ExtRegistryEntry, call it
546 with both "unique_key" and "callback" set to
547 "self.bookkeeper.position_key". If there are several calls from
548 the same operation, they need their own "unique_key", like
549 (position_key, "first") and (position_key, "second").
550
551 In general, "unique_key" should somehow uniquely identify where
552 the call is in the source code, and "callback" is a
553 position_key to reflow from when we see more general results.
554
555 "replace" can be set to a list of old unique_key values to
556 forget now, because the given "unique_key" replaces them.
557 """
558 with self.at_position(None):
559 emulated_pbc_calls = self.emulated_pbc_calls
560 prev = [unique_key]
561 prev.extend(replace)
562 for other_key in prev:
563 if other_key in emulated_pbc_calls:
564 del emulated_pbc_calls[other_key]
565 emulated_pbc_calls[unique_key] = pbc, args_s
566
567 args = simple_args(args_s)
568 if callback is None:
569 emulated = True
570 else:
571 emulated = callback
572 return self.pbc_call(pbc, args, emulated=emulated)
573
574 def whereami(self):
575 return self.annotator.whereami(self.position_key)
576
577 def event(self, what, x):
578 return self.annotator.policy.event(self, what, x)
579
580 def warning(self, msg):
581 return self.annotator.warning(msg)
582
583 def origin_of_meth(boundmeth):
584 func = boundmeth.im_func
585 candname = func.__name__
586 for cls in inspect.getmro(boundmeth.im_class):
587 dict = cls.__dict__
588 if dict.get(candname) is func:
589 return cls, candname
590 for name, value in dict.iteritems():
591 if value is func:
592 return cls, name
593 raise AnnotatorError("could not match bound-method to attribute name: %r" % (boundmeth,))
594
595 def ishashable(x):
596 try:
597 hash(x)
598 except TypeError:
599 return False
600 else:
601 return True
602
603 # get current bookkeeper
604
605 def getbookkeeper():
606 """Get the current Bookkeeper.
607 Only works during the analysis of an operation."""
608 try:
609 return TLS.bookkeeper
610 except AttributeError:
611 return None
612
613 def immutablevalue(x):
614 return getbookkeeper().immutablevalue(x)