Debian Codegraph @

rpython/annotator/description.py

raw symbols SCIP
1 from __future__ import absolute_import
2 import types
3 from rpython.annotator.signature import (
4 enforce_signature_args, enforce_signature_return, finish_type)
5 from rpython.flowspace.model import FunctionGraph
6 from rpython.annotator.argument import rawshape, ArgErr, simple_args
7 from rpython.tool.sourcetools import valid_identifier
8 from rpython.tool.pairtype import extendabletype
9 from rpython.annotator.model import AnnotatorError, s_ImpossibleValue, unionof
10
11 class CallFamily(object):
12 """A family of Desc objects that could be called from common call sites.
13 The call families are conceptually a partition of all (callable) Desc
14 objects, where the equivalence relation is the transitive closure of
15 'd1~d2 if d1 and d2 might be called at the same call site'.
16 """
17 normalized = False
18 modified = True
19
20 def __init__(self, desc):
21 self.descs = {desc: True}
22 self.calltables = {} # see calltable_lookup_row()
23 self.total_calltable_size = 0
24
25 def update(self, other):
26 self.modified = True
27 self.normalized = self.normalized or other.normalized
28 self.descs.update(other.descs)
29 for shape, table in other.calltables.items():
30 for row in table:
31 self.calltable_add_row(shape, row)
32 absorb = update # UnionFind API
33
34 def calltable_lookup_row(self, callshape, row):
35 # this code looks up a table of which graph to
36 # call at which call site. Each call site gets a row of graphs,
37 # sharable with other call sites. Each column is a FunctionDesc.
38 # There is one such table per "call shape".
39 table = self.calltables.get(callshape, [])
40 for i, existing_row in enumerate(table):
41 if existing_row == row: # XXX maybe use a dict again here?
42 return i
43 raise LookupError
44
45 def calltable_add_row(self, callshape, row):
46 try:
47 self.calltable_lookup_row(callshape, row)
48 except LookupError:
49 self.modified = True
50 table = self.calltables.setdefault(callshape, [])
51 table.append(row)
52 self.total_calltable_size += 1
53
54 def find_row(self, bookkeeper, descs, args, op):
55 shape = rawshape(args)
56 with bookkeeper.at_position(None):
57 row = build_calltable_row(descs, args, op)
58 index = self.calltable_lookup_row(shape, row)
59 return shape, index
60
61 def build_calltable_row(descs, args, op):
62 # see comments in CallFamily
63 row = {}
64 for desc in descs:
65 graph = desc.get_graph(args, op)
66 assert isinstance(graph, FunctionGraph)
67 row[desc.rowkey()] = graph
68 return row
69
70
71 class FrozenAttrFamily(object):
72 """A family of FrozenDesc objects that have any common 'getattr' sites.
73 The attr families are conceptually a partition of FrozenDesc objects,
74 where the equivalence relation is the transitive closure of:
75 d1~d2 if d1 and d2 might have some attribute read on them by the same
76 getattr operation.
77 """
78 def __init__(self, desc):
79 self.descs = {desc: True}
80 self.read_locations = {} # set of position_keys
81 self.attrs = {} # { attr: s_value }
82
83 def update(self, other):
84 self.descs.update(other.descs)
85 self.read_locations.update(other.read_locations)
86 self.attrs.update(other.attrs)
87 absorb = update # UnionFind API
88
89 def get_s_value(self, attrname):
90 try:
91 return self.attrs[attrname]
92 except KeyError:
93 return s_ImpossibleValue
94
95 def set_s_value(self, attrname, s_value):
96 self.attrs[attrname] = s_value
97
98
99 class ClassAttrFamily(object):
100 """A family of ClassDesc objects that have common 'getattr' sites for a
101 given attribute name. The attr families are conceptually a partition
102 of ClassDesc objects, where the equivalence relation is the transitive
103 closure of: d1~d2 if d1 and d2 might have a common attribute 'attrname'
104 read on them by the same getattr operation.
105
106 The 'attrname' is not explicitly stored here, but is the key used
107 in the dictionary bookkeeper.pbc_maximal_access_sets_map.
108 """
109 # The difference between ClassAttrFamily and FrozenAttrFamily is that
110 # FrozenAttrFamily is the union for all attribute names, but
111 # ClassAttrFamily is more precise: it is only about one attribut name.
112
113 def __init__(self, desc):
114 self.descs = {desc: True}
115 self.read_locations = {} # set of position_keys
116 self.s_value = s_ImpossibleValue # union of possible values
117
118 def update(self, other):
119 self.descs.update(other.descs)
120 self.read_locations.update(other.read_locations)
121 self.s_value = unionof(self.s_value, other.s_value)
122 absorb = update # UnionFind API
123
124 def get_s_value(self, attrname):
125 return self.s_value
126
127 def set_s_value(self, attrname, s_value):
128 self.s_value = s_value
129
130 # ____________________________________________________________
131
132 class Desc(object):
133 __metaclass__ = extendabletype
134
135 def __init__(self, bookkeeper, pyobj=None):
136 self.bookkeeper = bookkeeper
137 # 'pyobj' is non-None if there is an associated underlying Python obj
138 self.pyobj = pyobj
139
140 def __repr__(self):
141 pyobj = self.pyobj
142 if pyobj is None:
143 return object.__repr__(self)
144 return '<%s for %r>' % (self.__class__.__name__, pyobj)
145
146 def querycallfamily(self):
147 """Retrieve the CallFamily object if there is one, otherwise
148 return None."""
149 call_families = self.bookkeeper.pbc_maximal_call_families
150 try:
151 return call_families[self]
152 except KeyError:
153 return None
154
155 def getcallfamily(self):
156 """Get the CallFamily object. Possibly creates one."""
157 call_families = self.bookkeeper.pbc_maximal_call_families
158 _, _, callfamily = call_families.find(self.rowkey())
159 return callfamily
160
161 def mergecallfamilies(self, *others):
162 """Merge the call families of the given Descs into one."""
163 if not others:
164 return False
165 call_families = self.bookkeeper.pbc_maximal_call_families
166 changed, rep, callfamily = call_families.find(self.rowkey())
167 for desc in others:
168 changed1, rep, callfamily = call_families.union(rep, desc.rowkey())
169 changed = changed or changed1
170 return changed
171
172 def queryattrfamily(self):
173 # no attributes supported by default;
174 # overriden in FrozenDesc and ClassDesc
175 return None
176
177 def bind_under(self, classdef, name):
178 return self
179
180 @staticmethod
181 def simplify_desc_set(descs):
182 pass
183
184
185 class NoStandardGraph(Exception):
186 """The function doesn't have a single standard non-specialized graph."""
187
188 NODEFAULT = object()
189
190 class FunctionDesc(Desc):
191 knowntype = types.FunctionType
192
193 def __init__(self, bookkeeper, pyobj, name, signature, defaults,
194 specializer=None):
195 super(FunctionDesc, self).__init__(bookkeeper, pyobj)
196 self.name = name
197 self.signature = signature
198 self.defaults = defaults if defaults is not None else ()
199 # 'specializer' is a function with the following signature:
200 # specializer(funcdesc, args_s) => graph
201 # or => s_result (overridden/memo cases)
202 self.specializer = specializer
203 self._cache = {} # convenience for the specializer
204
205 def buildgraph(self, alt_name=None, builder=None):
206 translator = self.bookkeeper.annotator.translator
207 if builder:
208 graph = builder(translator, self.pyobj)
209 else:
210 graph = translator.buildflowgraph(self.pyobj)
211 if alt_name:
212 graph.name = alt_name
213 return graph
214
215 def getgraphs(self):
216 return self._cache.values()
217
218 def getuniquegraph(self):
219 if len(self._cache) != 1:
220 raise NoStandardGraph(self)
221 [graph] = self._cache.values()
222 relax_sig_check = getattr(self.pyobj, "relax_sig_check", False)
223 if (graph.signature != self.signature or
224 graph.defaults != self.defaults) and not relax_sig_check:
225 raise NoStandardGraph(self)
226 return graph
227
228 def cachedgraph(self, key, alt_name=None, builder=None):
229 try:
230 return self._cache[key]
231 except KeyError:
232 def nameof(thing):
233 if isinstance(thing, str):
234 return thing
235 elif hasattr(thing, '__name__'): # mostly types and functions
236 return thing.__name__
237 elif hasattr(thing, 'name') and isinstance(thing.name, str):
238 return thing.name # mostly ClassDescs
239 elif isinstance(thing, tuple):
240 return '_'.join(map(nameof, thing))
241 else:
242 return str(thing)[:30]
243
244 if key is not None and alt_name is None:
245 postfix = valid_identifier(nameof(key))
246 alt_name = "%s__%s" % (self.name, postfix)
247 graph = self.buildgraph(alt_name, builder)
248 self._cache[key] = graph
249 return graph
250
251 def parse_arguments(self, args, graph=None):
252 defs_s = []
253 if graph is None:
254 signature = self.signature
255 defaults = self.defaults
256 else:
257 signature = graph.signature
258 defaults = graph.defaults
259 if defaults:
260 for x in defaults:
261 if x is NODEFAULT:
262 defs_s.append(None)
263 else:
264 defs_s.append(self.bookkeeper.immutablevalue(x))
265 try:
266 inputcells = args.match_signature(signature, defs_s)
267 except ArgErr as e:
268 raise AnnotatorError("signature mismatch: %s() %s" %
269 (self.name, e.getmsg()))
270 return inputcells
271
272 def specialize(self, inputcells, op=None):
273 if (op is None and
274 getattr(self.bookkeeper, "position_key", None) is not None):
275 _, block, i = self.bookkeeper.position_key
276 op = block.operations[i]
277 self.normalize_args(inputcells)
278 if getattr(self.pyobj, '_annspecialcase_', '').endswith("call_location"):
279 return self.specializer(self, inputcells, op)
280 else:
281 return self.specializer(self, inputcells)
282
283 def pycall(self, whence, args, s_previous_result, op=None):
284 inputcells = self.parse_arguments(args)
285 graph = self.specialize(inputcells, op)
286 assert isinstance(graph, FunctionGraph)
287 # if that graph has a different signature, we need to re-parse
288 # the arguments.
289 # recreate the args object because inputcells may have been changed
290 new_args = args.unmatch_signature(self.signature, inputcells)
291 inputcells = self.parse_arguments(new_args, graph)
292 annotator = self.bookkeeper.annotator
293 result = annotator.recursivecall(graph, whence, inputcells)
294 signature = getattr(self.pyobj, '_signature_', None)
295 if signature:
296 sigresult = enforce_signature_return(self, signature[1], result)
297 if sigresult is not None:
298 annotator.addpendingblock(
299 graph, graph.returnblock, [sigresult])
300 result = sigresult
301 # Some specializations may break the invariant of returning
302 # annotations that are always more general than the previous time.
303 # We restore it here:
304 result = unionof(result, s_previous_result)
305 return result
306
307 def normalize_args(self, inputs_s):
308 """
309 Canonicalize argument annotations into the exact parameter
310 annotations of a specific specialized graph.
311
312 Note: this method has no return value but mutates its argument instead.
313 """
314 enforceargs = getattr(self.pyobj, '_annenforceargs_', None)
315 signature = getattr(self.pyobj, '_signature_', None)
316 if enforceargs and signature:
317 raise AnnotatorError("%r: signature and enforceargs cannot both be "
318 "used" % (self,))
319 if enforceargs:
320 if not callable(enforceargs):
321 from rpython.annotator.signature import Sig
322 enforceargs = Sig(*enforceargs)
323 self.pyobj._annenforceargs_ = enforceargs
324 enforceargs(self, inputs_s) # can modify inputs_s in-place
325 if signature:
326 enforce_signature_args(self, signature[0], inputs_s) # mutates inputs_s
327
328 def get_graph(self, args, op):
329 inputs_s = self.parse_arguments(args)
330 return self.specialize(inputs_s, op)
331
332 def get_call_parameters(self, args_s):
333 args = simple_args(args_s)
334 inputcells = self.parse_arguments(args)
335 graph = self.specialize(inputcells)
336 assert isinstance(graph, FunctionGraph)
337 # if that graph has a different signature, we need to re-parse
338 # the arguments.
339 # recreate the args object because inputcells may have been changed
340 new_args = args.unmatch_signature(self.signature, inputcells)
341 inputcells = self.parse_arguments(new_args, graph)
342 signature = getattr(self.pyobj, '_signature_', None)
343 if signature:
344 s_result = finish_type(signature[1], self.bookkeeper, self.pyobj)
345 if s_result is not None:
346 self.bookkeeper.annotator.addpendingblock(
347 graph, graph.returnblock, [s_result])
348 return graph, inputcells
349
350 def bind_under(self, classdef, name):
351 # XXX static methods
352 return self.bookkeeper.getmethoddesc(self,
353 classdef, # originclassdef,
354 None, # selfclassdef
355 name)
356
357 @staticmethod
358 def consider_call_site(descs, args, s_result, op):
359 family = descs[0].getcallfamily()
360 shape = rawshape(args)
361 row = build_calltable_row(descs, args, op)
362 family.calltable_add_row(shape, row)
363 descs[0].mergecallfamilies(*descs[1:])
364
365 def rowkey(self):
366 return self
367
368 def get_s_signatures(self, shape):
369 family = self.getcallfamily()
370 table = family.calltables.get(shape)
371 if table is None:
372 return []
373 else:
374 graph_seen = {}
375 s_sigs = []
376
377 binding = self.bookkeeper.annotator.binding
378
379 def enlist(graph):
380 if graph in graph_seen:
381 return
382 graph_seen[graph] = True
383 s_sig = ([binding(v) for v in graph.getargs()],
384 binding(graph.getreturnvar()))
385 if s_sig in s_sigs:
386 return
387 s_sigs.append(s_sig)
388
389 for row in table:
390 for graph in row.itervalues():
391 enlist(graph)
392
393 return s_sigs
394
395 class MemoDesc(FunctionDesc):
396 def pycall(self, whence, args, s_previous_result, op=None):
397 inputcells = self.parse_arguments(args)
398 s_result = self.specialize(inputcells, op)
399 if isinstance(s_result, FunctionGraph):
400 s_result = s_result.getreturnvar().annotation
401 if s_result is None:
402 s_result = s_ImpossibleValue
403 s_result = unionof(s_result, s_previous_result)
404 return s_result
405
406
407 class MethodDesc(Desc):
408 knowntype = types.MethodType
409
410 def __init__(self, bookkeeper, funcdesc, originclassdef,
411 selfclassdef, name, flags={}):
412 super(MethodDesc, self).__init__(bookkeeper)
413 self.funcdesc = funcdesc
414 self.originclassdef = originclassdef
415 self.selfclassdef = selfclassdef
416 self.name = name
417 self.flags = flags
418
419 def __repr__(self):
420 if self.selfclassdef is None:
421 return '<unbound MethodDesc %r of %r>' % (self.name,
422 self.originclassdef)
423 else:
424 return '<MethodDesc %r of %r bound to %r %r>' % (self.name,
425 self.originclassdef,
426 self.selfclassdef,
427 self.flags)
428
429 def getuniquegraph(self):
430 return self.funcdesc.getuniquegraph()
431
432 def func_args(self, args):
433 from rpython.annotator.model import SomeInstance
434 if self.selfclassdef is None:
435 raise AnnotatorError("calling %r" % (self,))
436 s_instance = SomeInstance(self.selfclassdef, flags=self.flags)
437 return args.prepend(s_instance)
438
439 def pycall(self, whence, args, s_previous_result, op=None):
440 func_args = self.func_args(args)
441 return self.funcdesc.pycall(whence, func_args, s_previous_result, op)
442
443 def get_graph(self, args, op):
444 func_args = self.func_args(args)
445 return self.funcdesc.get_graph(func_args, op)
446
447 def bind_under(self, classdef, name):
448 self.bookkeeper.warning("rebinding an already bound %r" % (self,))
449 return self.funcdesc.bind_under(classdef, name)
450
451 def bind_self(self, newselfclassdef, flags={}):
452 return self.bookkeeper.getmethoddesc(self.funcdesc,
453 self.originclassdef,
454 newselfclassdef,
455 self.name,
456 flags)
457
458 @staticmethod
459 def consider_call_site(descs, args, s_result, op):
460 cnt, keys, star = rawshape(args)
461 shape = cnt + 1, keys, star # account for the extra 'self'
462 row = build_calltable_row(descs, args, op)
463 family = descs[0].getcallfamily()
464 family.calltable_add_row(shape, row)
465 descs[0].mergecallfamilies(*descs[1:])
466
467 def rowkey(self):
468 # we are computing call families and call tables that always contain
469 # FunctionDescs, not MethodDescs. The present method returns the
470 # FunctionDesc to use as a key in that family.
471 return self.funcdesc
472
473 @staticmethod
474 def simplify_desc_set(descs):
475 # Some hacking needed to make contains() happy on SomePBC: if the
476 # set of MethodDescs contains some "redundant" ones, i.e. ones that
477 # are less general than others already in the set, then kill them.
478 # This ensures that if 'a' is less general than 'b', then
479 # SomePBC({a}) union SomePBC({b}) is again SomePBC({b}).
480 #
481 # Two cases:
482 # 1. if two MethodDescs differ in their selfclassdefs, and if one
483 # of the selfclassdefs is a subclass of the other;
484 # 2. if two MethodDescs differ in their flags, take the intersection.
485
486 # --- case 2 ---
487 # only keep the intersection of all the flags, that's good enough
488 lst = list(descs)
489 commonflags = lst[0].flags.copy()
490 for key, value in commonflags.items():
491 for desc in lst[1:]:
492 if key not in desc.flags or desc.flags[key] != value:
493 del commonflags[key]
494 break
495 for desc in lst:
496 if desc.flags != commonflags:
497 newdesc = desc.bookkeeper.getmethoddesc(desc.funcdesc,
498 desc.originclassdef,
499 desc.selfclassdef,
500 desc.name,
501 commonflags)
502 descs.remove(desc)
503 descs.add(newdesc)
504
505 # --- case 1 ---
506 groups = {}
507 for desc in descs:
508 if desc.selfclassdef is not None:
509 key = desc.funcdesc, desc.originclassdef, desc.name
510 groups.setdefault(key, []).append(desc)
511 for group in groups.values():
512 if len(group) > 1:
513 for desc1 in group:
514 cdef1 = desc1.selfclassdef
515 for desc2 in group:
516 cdef2 = desc2.selfclassdef
517 if cdef1 is not cdef2 and cdef1.issubclass(cdef2):
518 descs.remove(desc1)
519 break
520
521
522 def new_or_old_class(c):
523 if hasattr(c, '__class__'):
524 return c.__class__
525 else:
526 return type(c)
527
528 class FrozenDesc(Desc):
529
530 def __init__(self, bookkeeper, pyobj, read_attribute=None):
531 super(FrozenDesc, self).__init__(bookkeeper, pyobj)
532 if read_attribute is None:
533 read_attribute = lambda attr: getattr(pyobj, attr)
534 self._read_attribute = read_attribute
535 self.attrcache = {}
536 self.knowntype = new_or_old_class(pyobj)
537 assert bool(pyobj), "__nonzero__ unsupported on frozen PBC %r" % (pyobj,)
538
539 def has_attribute(self, attr):
540 if attr in self.attrcache:
541 return True
542 try:
543 self._read_attribute(attr)
544 return True
545 except AttributeError:
546 return False
547
548 def warn_missing_attribute(self, attr):
549 # only warn for missing attribute names whose name doesn't start
550 # with '$', to silence the warnings about '$memofield_xxx'.
551 return not self.has_attribute(attr) and not attr.startswith('$')
552
553 def read_attribute(self, attr):
554 try:
555 return self.attrcache[attr]
556 except KeyError:
557 result = self.attrcache[attr] = self._read_attribute(attr)
558 return result
559
560 def s_read_attribute(self, attr):
561 try:
562 value = self.read_attribute(attr)
563 except AttributeError:
564 return s_ImpossibleValue
565 else:
566 return self.bookkeeper.immutablevalue(value)
567
568 def create_new_attribute(self, name, value):
569 try:
570 self.read_attribute(name)
571 except AttributeError:
572 pass
573 else:
574 raise AssertionError("name clash: %r" % (name,))
575 self.attrcache[name] = value
576
577 def getattrfamily(self, attrname=None):
578 "Get the FrozenAttrFamily object for attrname. Possibly creates one."
579 access_sets = self.bookkeeper.frozenpbc_attr_families
580 _, _, attrfamily = access_sets.find(self)
581 return attrfamily
582
583 def queryattrfamily(self, attrname=None):
584 """Retrieve the FrozenAttrFamily object for attrname if there is one,
585 otherwise return None."""
586 access_sets = self.bookkeeper.frozenpbc_attr_families
587 try:
588 return access_sets[self]
589 except KeyError:
590 return None
591
592 def mergeattrfamilies(self, others, attrname=None):
593 """Merge the attr families of the given Descs into one."""
594 access_sets = self.bookkeeper.frozenpbc_attr_families
595 changed, rep, attrfamily = access_sets.find(self)
596 for desc in others:
597 changed1, rep, attrfamily = access_sets.union(rep, desc)
598 changed = changed or changed1
599 return changed
600
601
602 class MethodOfFrozenDesc(Desc):
603 knowntype = types.MethodType
604
605 def __init__(self, bookkeeper, funcdesc, frozendesc):
606 super(MethodOfFrozenDesc, self).__init__(bookkeeper)
607 self.funcdesc = funcdesc
608 self.frozendesc = frozendesc
609
610 def __repr__(self):
611 return '<MethodOfFrozenDesc %r of %r>' % (self.funcdesc,
612 self.frozendesc)
613
614 def func_args(self, args):
615 from rpython.annotator.model import SomePBC
616 s_self = SomePBC([self.frozendesc])
617 return args.prepend(s_self)
618
619 def pycall(self, whence, args, s_previous_result, op=None):
620 func_args = self.func_args(args)
621 return self.funcdesc.pycall(whence, func_args, s_previous_result, op)
622
623 def get_graph(self, args, op):
624 func_args = self.func_args(args)
625 return self.funcdesc.get_graph(func_args, op)
626
627 @staticmethod
628 def consider_call_site(descs, args, s_result, op):
629 cnt, keys, star = rawshape(args)
630 shape = cnt + 1, keys, star # account for the extra 'self'
631 row = build_calltable_row(descs, args, op)
632 family = descs[0].getcallfamily()
633 family.calltable_add_row(shape, row)
634 descs[0].mergecallfamilies(*descs[1:])
635
636 def rowkey(self):
637 return self.funcdesc