Debian Codegraph @

rpython/annotator/classdesc.py

raw symbols SCIP
1 """
2 Type inference for user-defined classes.
3 """
4 from __future__ import absolute_import
5 import types
6
7 from rpython.flowspace.model import Constant
8 from rpython.tool.flattenrec import FlattenRecursion
9 from rpython.tool.sourcetools import func_with_new_name
10 from rpython.tool.uid import Hashable
11 from rpython.annotator.model import (
12 SomePBC, s_ImpossibleValue, unionof, s_None, AnnotatorError, SomeInteger,
13 SomeString, SomeImpossibleValue, SomeList, HarmlesslyBlocked)
14 from rpython.annotator.description import (
15 Desc, FunctionDesc, MethodDesc, NODEFAULT)
16
17
18 # The main purpose of a ClassDef is to collect information about class/instance
19 # attributes as they are really used. An Attribute object is stored in the
20 # most general ClassDef where an attribute of that name is read/written:
21 # classdef.attrs = {'attrname': Attribute()}
22 #
23 # The following invariants hold:
24 #
25 # (A) if an attribute is read/written on an instance of class A, then the
26 # classdef of A or a parent class of A has an Attribute object corresponding
27 # to that name.
28 #
29 # (I) if B is a subclass of A, then they don't both have an Attribute for the
30 # same name. (All information from B's Attribute must be merged into A's.)
31 #
32 # Additionally, each ClassDef records an 'attr_sources': it maps attribute names
33 # to a list of 'source' objects that want to provide a constant value for this
34 # attribute at the level of this class. The attr_sources provide information
35 # higher in the class hierarchy than concrete Attribute()s. It is for the case
36 # where (so far or definitely) the user program only reads/writes the attribute
37 # at the level of a subclass, but a value for this attribute could possibly
38 # exist in the parent class or in an instance of a parent class.
39 #
40 # The point of not automatically forcing the Attribute instance up to the
41 # parent class which has a class attribute of the same name is apparent with
42 # multiple subclasses:
43 #
44 # A
45 # attr=s1
46 # / \
47 # / \
48 # B C
49 # attr=s2 attr=s3
50 #
51 # XXX this does not seem to be correct, but I don't know how to phrase
52 # it correctly. See test_specific_attributes in test_annrpython
53 #
54 # In this case, as long as 'attr' is only read/written from B or C, the
55 # Attribute on B says that it can be 's1 or s2', and the Attribute on C says
56 # it can be 's1 or s3'. Merging them into a single Attribute on A would give
57 # the more imprecise 's1 or s2 or s3'.
58 #
59 # The following invariant holds:
60 #
61 # (II) if a class A has an Attribute, the 'attr_sources' for the same name is
62 # empty. It is also empty on all subclasses of A. (The information goes
63 # into the Attribute directly in this case.)
64 #
65 # The following invariant holds:
66 #
67 # (III) for a class A, each attrsource that comes from the class (as opposed to
68 # from a prebuilt instance) must be merged into all Attributes of the
69 # same name in all subclasses of A, if any. (Parent class attributes can
70 # be visible in reads from instances of subclasses.)
71
72 class Attribute(object):
73 # readonly-ness
74 # SomeThing-ness
75 # NB. an attribute is readonly if it is a constant class attribute.
76 # Both writing to the instance attribute and discovering prebuilt
77 # instances that have the attribute set will turn off readonly-ness.
78
79 def __init__(self, name):
80 assert name != '__class__'
81 self.name = name
82 self.s_value = s_ImpossibleValue
83 self.readonly = True
84 self.attr_allowed = True
85 self.read_locations = set()
86
87 def add_constant_source(self, classdef, source):
88 s_value = source.s_get_value(classdef, self.name)
89 if source.instance_level:
90 # a prebuilt instance source forces readonly=False, see above
91 self.modified(classdef)
92 s_new_value = unionof(self.s_value, s_value)
93 self.s_value = s_new_value
94
95 def merge(self, other, classdef):
96 assert self.name == other.name
97 s_new_value = unionof(self.s_value, other.s_value)
98 self.s_value = s_new_value
99 if not other.readonly:
100 self.modified(classdef)
101 self.read_locations.update(other.read_locations)
102
103 def validate(self, homedef):
104 s_newvalue = self.s_value
105 # check for after-the-fact method additions
106 if isinstance(s_newvalue, SomePBC):
107 attr = self.name
108 if s_newvalue.getKind() == MethodDesc:
109 # is method
110 if homedef.classdesc.read_attribute(attr, None) is None:
111 homedef.check_missing_attribute_update(attr)
112
113 # check for attributes forbidden by slots or _attrs_
114 if homedef.classdesc.all_enforced_attrs is not None:
115 if self.name not in homedef.classdesc.all_enforced_attrs:
116 self.attr_allowed = False
117 if not self.readonly:
118 raise NoSuchAttrError(
119 "the attribute %r goes here to %r, but it is "
120 "forbidden here" % (self.name, homedef))
121
122 def modified(self, classdef='?'):
123 self.readonly = False
124 if not self.attr_allowed:
125 from rpython.annotator.bookkeeper import getbookkeeper
126 bk = getbookkeeper()
127 classdesc = classdef.classdesc
128 locations = bk.getattr_locations(classdesc, self.name)
129 raise NoSuchAttrError(
130 "Attribute %r on %r should be read-only.\n" % (self.name,
131 classdef) +
132 "This error can be caused by another 'getattr' that promoted\n"
133 "the attribute here; the list of read locations is:\n" +
134 '\n'.join([str(loc[0]) for loc in locations]))
135
136 class ClassDef(object):
137 "Wraps a user class."
138
139 def __init__(self, bookkeeper, classdesc):
140 self.bookkeeper = bookkeeper
141 self.attrs = {} # {name: Attribute}
142 self.classdesc = classdesc
143 self.name = self.classdesc.name
144 self.shortname = self.name.split('.')[-1]
145 self.subdefs = []
146 self.attr_sources = {} # {name: list-of-sources}
147 self.read_locations_of__class__ = {}
148 self.repr = None
149 self.extra_access_sets = {}
150 self.instances_seen = set()
151
152 if classdesc.basedesc:
153 self.basedef = classdesc.basedesc.getuniqueclassdef()
154 self.basedef.subdefs.append(self)
155 self.basedef.see_new_subclass(self)
156 else:
157 self.basedef = None
158
159 self.parentdefs = dict.fromkeys(self.getmro())
160
161 def setup(self, sources):
162 # collect the (supposed constant) class attributes
163 for name, source in sources.items():
164 self.add_source_for_attribute(name, source)
165 if self.bookkeeper:
166 self.bookkeeper.event('classdef_setup', self)
167
168 def s_getattr(self, attrname, flags):
169 attrdef = self.find_attribute(attrname)
170 s_result = attrdef.s_value
171 # hack: if s_result is a set of methods, discard the ones
172 # that can't possibly apply to an instance of self.
173 # XXX do it more nicely
174 if isinstance(s_result, SomePBC):
175 s_result = self.lookup_filter(s_result, attrname, flags)
176 elif isinstance(s_result, SomeImpossibleValue):
177 self.check_missing_attribute_update(attrname)
178 # blocking is harmless if the attribute is explicitly listed
179 # in the class or a parent class.
180 for basedef in self.getmro():
181 if basedef.classdesc.all_enforced_attrs is not None:
182 if attrname in basedef.classdesc.all_enforced_attrs:
183 raise HarmlesslyBlocked("get enforced attr")
184 elif isinstance(s_result, SomeList):
185 s_result = self.classdesc.maybe_return_immutable_list(
186 attrname, s_result)
187 return s_result
188
189 def add_source_for_attribute(self, attr, source):
190 """Adds information about a constant source for an attribute.
191 """
192 for cdef in self.getmro():
193 if attr in cdef.attrs:
194 # the Attribute() exists already for this class (or a parent)
195 attrdef = cdef.attrs[attr]
196 s_prev_value = attrdef.s_value
197 attrdef.add_constant_source(self, source)
198 # we should reflow from all the reader's position,
199 # but as an optimization we try to see if the attribute
200 # has really been generalized
201 if attrdef.s_value != s_prev_value:
202 self.bookkeeper.update_attr(cdef, attrdef)
203 return
204 else:
205 # remember the source in self.attr_sources
206 sources = self.attr_sources.setdefault(attr, [])
207 sources.append(source)
208 # register the source in any Attribute found in subclasses,
209 # to restore invariant (III)
210 # NB. add_constant_source() may discover new subdefs but the
211 # right thing will happen to them because self.attr_sources
212 # was already updated
213 if not source.instance_level:
214 for subdef in self.getallsubdefs():
215 if attr in subdef.attrs:
216 attrdef = subdef.attrs[attr]
217 s_prev_value = attrdef.s_value
218 attrdef.add_constant_source(self, source)
219 if attrdef.s_value != s_prev_value:
220 self.bookkeeper.update_attr(subdef, attrdef)
221
222 def get_owner(self, attrname):
223 """Return the classdef owning the attribute `attrname`."""
224 for cdef in self.getmro():
225 if attrname in cdef.attrs:
226 return cdef
227 else:
228 return None
229
230
231 def locate_attribute(self, attr):
232 cdef = self.get_owner(attr)
233 if cdef:
234 return cdef
235 else:
236 self._generalize_attr(attr, s_value=None)
237 return self
238
239 def find_attribute(self, attr):
240 return self.locate_attribute(attr).attrs[attr]
241
242 def __repr__(self):
243 return "<ClassDef '%s'>" % (self.name,)
244
245 def has_no_attrs(self):
246 for clsdef in self.getmro():
247 if clsdef.attrs:
248 return False
249 return True
250
251 def commonbase(self, other):
252 while other is not None and not self.issubclass(other):
253 other = other.basedef
254 return other
255
256 def getmro(self):
257 while self is not None:
258 yield self
259 self = self.basedef
260
261 def issubclass(self, other):
262 return self.classdesc.issubclass(other.classdesc)
263
264 def getallsubdefs(self):
265 pending = [self]
266 seen = {}
267 for clsdef in pending:
268 yield clsdef
269 for sub in clsdef.subdefs:
270 if sub not in seen:
271 pending.append(sub)
272 seen[sub] = True
273
274 def _generalize_attr(self, attr, s_value):
275 # create the Attribute and do the generalization asked for
276 newattr = Attribute(attr)
277 if s_value:
278 newattr.s_value = s_value
279
280 # remove the attribute from subclasses -- including us!
281 # invariant (I)
282 constant_sources = [] # [(classdef-of-origin, source)]
283 for subdef in self.getallsubdefs():
284 if attr in subdef.attrs:
285 subattr = subdef.attrs[attr]
286 newattr.merge(subattr, classdef=self)
287 del subdef.attrs[attr]
288 if attr in subdef.attr_sources:
289 # accumulate attr_sources for this attribute from all subclasses
290 lst = subdef.attr_sources[attr]
291 for source in lst:
292 constant_sources.append((subdef, source))
293 del lst[:] # invariant (II)
294
295 # accumulate attr_sources for this attribute from all parents, too
296 # invariant (III)
297 for superdef in self.getmro():
298 if attr in superdef.attr_sources:
299 for source in superdef.attr_sources[attr]:
300 if not source.instance_level:
301 constant_sources.append((superdef, source))
302
303 # store this new Attribute, generalizing the previous ones from
304 # subclasses -- invariant (A)
305 self.attrs[attr] = newattr
306
307 # add the values of the pending constant attributes
308 # completes invariants (II) and (III)
309 for origin_classdef, source in constant_sources:
310 newattr.add_constant_source(origin_classdef, source)
311
312 # reflow from all read positions
313 self.bookkeeper.update_attr(self, newattr)
314
315 def generalize_attr(self, attr, s_value=None):
316 # if the attribute exists in a superclass, generalize there,
317 # as imposed by invariant (I)
318 clsdef = self.get_owner(attr)
319 if clsdef:
320 clsdef._generalize_attr(attr, s_value)
321 else:
322 self._generalize_attr(attr, s_value)
323
324 def about_attribute(self, name):
325 """This is the interface for the code generators to ask about
326 the annotation given to a attribute."""
327 for cdef in self.getmro():
328 if name in cdef.attrs:
329 s_result = cdef.attrs[name].s_value
330 if s_result != s_ImpossibleValue:
331 return s_result
332 else:
333 return None
334 return None
335
336 def lookup_filter(self, pbc, name=None, flags={}):
337 """Selects the methods in the pbc that could possibly be seen by
338 a lookup performed on an instance of 'self', removing the ones
339 that cannot appear.
340 """
341 d = []
342 uplookup = None
343 updesc = None
344 for desc in pbc.descriptions:
345 # pick methods but ignore already-bound methods, which can come
346 # from an instance attribute
347 if (isinstance(desc, MethodDesc) and desc.selfclassdef is None):
348 methclassdef = desc.originclassdef
349 if methclassdef is not self and methclassdef.issubclass(self):
350 pass # subclasses methods are always candidates
351 elif self.issubclass(methclassdef):
352 # upward consider only the best match
353 if uplookup is None or methclassdef.issubclass(uplookup):
354 uplookup = methclassdef
355 updesc = desc
356 continue
357 # for clsdef1 >= clsdef2, we guarantee that
358 # clsdef1.lookup_filter(pbc) includes
359 # clsdef2.lookup_filter(pbc) (see formal proof...)
360 else:
361 continue # not matching
362 # bind the method by giving it a selfclassdef. Use the
363 # more precise subclass that it's coming from.
364 desc = desc.bind_self(methclassdef, flags)
365 d.append(desc)
366 if uplookup is not None:
367 d.append(updesc.bind_self(self, flags))
368
369 if d:
370 return SomePBC(d, can_be_None=pbc.can_be_None)
371 elif pbc.can_be_None:
372 return s_None
373 else:
374 return s_ImpossibleValue
375
376 def check_missing_attribute_update(self, name):
377 # haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaack
378 # sometimes, new methods can show up on classes, added
379 # e.g. by W_TypeObject._freeze_() -- the multimethod
380 # implementations. Check that here...
381 found = False
382 parents = list(self.getmro())
383 parents.reverse()
384 for base in parents:
385 if base.check_attr_here(name):
386 found = True
387 return found
388
389 def check_attr_here(self, name):
390 source = self.classdesc.find_source_for(name)
391 if source is not None:
392 # oups! new attribute showed up
393 self.add_source_for_attribute(name, source)
394 # maybe it also showed up in some subclass?
395 for subdef in self.getallsubdefs():
396 if subdef is not self:
397 subdef.check_attr_here(name)
398 return True
399 else:
400 return False
401
402 _see_instance_flattenrec = FlattenRecursion()
403
404 def see_instance(self, x):
405 assert isinstance(x, self.classdesc.pyobj)
406 key = Hashable(x)
407 if key in self.instances_seen:
408 return
409 self.instances_seen.add(key)
410 self.bookkeeper.event('mutable', x)
411 source = InstanceSource(self.bookkeeper, x)
412 def delayed():
413 for attr in source.all_instance_attributes():
414 self.add_source_for_attribute(attr, source)
415 # ^^^ can trigger reflowing
416 self._see_instance_flattenrec(delayed)
417
418 def see_new_subclass(self, classdef):
419 for position in self.read_locations_of__class__:
420 self.bookkeeper.annotator.reflowfromposition(position)
421 if self.basedef is not None:
422 self.basedef.see_new_subclass(classdef)
423
424 def read_attr__class__(self):
425 position = self.bookkeeper.position_key
426 self.read_locations_of__class__[position] = True
427 return SomePBC([subdef.classdesc for subdef in self.getallsubdefs()])
428
429 def _freeze_(self):
430 raise Exception("ClassDefs are used as knowntype for instances but "
431 "cannot be used as immutablevalue arguments directly")
432
433 # ____________________________________________________________
434
435 class InstanceSource(object):
436 instance_level = True
437
438 def __init__(self, bookkeeper, obj):
439 self.bookkeeper = bookkeeper
440 self.obj = obj
441
442 def s_get_value(self, classdef, name):
443 try:
444 v = getattr(self.obj, name)
445 except AttributeError:
446 all_enforced_attrs = classdef.classdesc.all_enforced_attrs
447 if all_enforced_attrs and name in all_enforced_attrs:
448 return s_ImpossibleValue
449 raise
450 s_value = self.bookkeeper.immutablevalue(v)
451 return s_value
452
453 def all_instance_attributes(self):
454 result = getattr(self.obj, '__dict__', {}).keys()
455 tp = self.obj.__class__
456 if isinstance(tp, type):
457 for basetype in tp.__mro__:
458 slots = basetype.__dict__.get('__slots__')
459 if slots:
460 if isinstance(slots, str):
461 result.append(slots)
462 else:
463 result.extend(slots)
464 return result
465
466 class NoSuchAttrError(AnnotatorError):
467 """Raised when an attribute is found on a class where __slots__
468 or _attrs_ forbits it."""
469
470
471 def is_mixin(cls):
472 return cls.__dict__.get('_mixin_', False)
473
474 def is_primitive_type(cls):
475 from rpython.rlib.rarithmetic import base_int
476 return cls.__module__ == '__builtin__' or issubclass(cls, base_int)
477
478
479 class BuiltinTypeDesc(object):
480 """Represents a primitive or builtin type object"""
481 def __init__(self, cls):
482 self.pyobj = cls
483
484 def issubclass(self, other):
485 return issubclass(self.pyobj, other.pyobj)
486
487
488 class ClassDesc(Desc):
489 knowntype = type
490 instance_level = False
491 all_enforced_attrs = None # or a set
492 _detect_invalid_attrs = None
493
494 def __init__(self, bookkeeper, cls,
495 name=None, basedesc=None, classdict=None):
496 super(ClassDesc, self).__init__(bookkeeper, cls)
497 if '__NOT_RPYTHON__' in cls.__dict__:
498 raise AnnotatorError('Bad class')
499
500 if name is None:
501 name = cls.__module__ + '.' + cls.__name__
502 self.name = name
503 self.basedesc = basedesc
504 if classdict is None:
505 classdict = {} # populated below
506 self.classdict = classdict # {attr: Constant-or-Desc}
507 if cls.__dict__.get('_annspecialcase_', ''):
508 raise AnnotatorError(
509 "Class specialization has been removed. The "
510 "'_annspecialcase_' class tag is now unsupported.")
511 self.classdef = None
512
513 if is_mixin(cls):
514 raise AnnotatorError("cannot use directly the class %r because "
515 "it is a _mixin_" % (cls,))
516
517 assert cls.__module__ != '__builtin__'
518 baselist = list(cls.__bases__)
519
520 # special case: skip BaseException, and pretend
521 # that all exceptions ultimately inherit from Exception instead
522 # of BaseException (XXX hack)
523 if cls is Exception:
524 baselist = []
525 elif baselist == [BaseException]:
526 baselist = [Exception]
527
528 immutable_fields = cls.__dict__.get('_immutable_fields_', [])
529 # To prevent confusion, we forbid strings. Any other bona fide sequence
530 # of strings is OK.
531 if isinstance(immutable_fields, basestring):
532 raise AnnotatorError(
533 "In class %s, '_immutable_fields_' must be a sequence of "
534 "attribute names, not a string." % cls)
535 self.immutable_fields = set(immutable_fields)
536
537 mixins_before = []
538 mixins_after = []
539 base = object
540 for b1 in baselist:
541 if b1 is object:
542 continue
543 if is_mixin(b1):
544 if base is object:
545 mixins_before.append(b1)
546 else:
547 mixins_after.append(b1)
548 else:
549 assert base is object, ("multiple inheritance only supported "
550 "with _mixin_: %r" % (cls,))
551 base = b1
552 if mixins_before and mixins_after:
553 raise AnnotatorError("unsupported: class %r has mixin bases both"
554 " before and after the regular base" % (self,))
555 self.add_mixins(mixins_after, check_not_in=base)
556 self.add_mixins(mixins_before)
557 self.add_sources_for_class(cls)
558
559 if base is not object:
560 self.basedesc = bookkeeper.getdesc(base)
561
562 if '__slots__' in cls.__dict__ or '_attrs_' in cls.__dict__:
563 attrs = {}
564 for decl in ('__slots__', '_attrs_'):
565 decl = cls.__dict__.get(decl, [])
566 if isinstance(decl, str):
567 decl = (decl,)
568 decl = dict.fromkeys(decl)
569 attrs.update(decl)
570 if self.basedesc is not None:
571 if self.basedesc.all_enforced_attrs is None:
572 raise AnnotatorError("%r has slots or _attrs_, "
573 "but not its base class" % (cls,))
574 attrs.update(self.basedesc.all_enforced_attrs)
575 self.all_enforced_attrs = attrs
576
577 if (self.is_builtin_exception_class() and
578 self.all_enforced_attrs is None):
579 if cls not in FORCE_ATTRIBUTES_INTO_CLASSES:
580 self.all_enforced_attrs = [] # no attribute allowed
581
582 if (getattr(cls, '_must_be_light_finalizer_', False) and
583 hasattr(cls, '__del__') and
584 not getattr(cls.__del__, '_must_be_light_finalizer_', False)):
585 raise AnnotatorError(
586 "Class %r is in a class hierarchy with "
587 "_must_be_light_finalizer_ = True: it cannot have a "
588 "finalizer without @rgc.must_be_light_finalizer" % (cls,))
589
590 def add_source_attribute(self, name, value, mixin=False):
591 if isinstance(value, property):
592 # special case for property object
593 if value.fget is not None:
594 newname = name + '__getter__'
595 func = func_with_new_name(value.fget, newname)
596 self.add_source_attribute(newname, func, mixin)
597 if value.fset is not None:
598 newname = name + '__setter__'
599 func = func_with_new_name(value.fset, newname)
600 self.add_source_attribute(newname, func, mixin)
601 self.classdict[name] = Constant(value)
602 return
603
604 if isinstance(value, types.FunctionType):
605 # for debugging
606 if not hasattr(value, 'class_'):
607 value.class_ = self.pyobj
608 if mixin:
609 # make a new copy of the FunctionDesc for this class,
610 # but don't specialize further for all subclasses
611 funcdesc = self.bookkeeper.newfuncdesc(value)
612 self.classdict[name] = funcdesc
613 return
614 # NB. if value is, say, AssertionError.__init__, then we
615 # should not use getdesc() on it. Never. The problem is
616 # that the py lib has its own AssertionError.__init__ which
617 # is of type FunctionType. But bookkeeper.immutablevalue()
618 # will do the right thing in s_get_value().
619 if isinstance(value, staticmethod) and mixin:
620 # make a new copy of staticmethod
621 func = value.__get__(42)
622 value = staticmethod(func_with_new_name(func, func.__name__))
623
624 if type(value) in MemberDescriptorTypes:
625 # skip __slots__, showing up in the class as 'member' objects
626 return
627 if name == '__init__' and self.is_builtin_exception_class():
628 # pretend that built-in exceptions have no __init__,
629 # unless explicitly specified in builtin.py
630 from rpython.annotator.builtin import BUILTIN_ANALYZERS
631 value = getattr(value, 'im_func', value)
632 if value not in BUILTIN_ANALYZERS:
633 return
634 self.classdict[name] = Constant(value)
635
636 def add_mixins(self, mixins, check_not_in=object):
637 if not mixins:
638 return
639 A = type('tmp', tuple(mixins) + (object,), {})
640 mro = A.__mro__
641 assert mro[0] is A and mro[-1] is object
642 mro = mro[1:-1]
643 #
644 skip = set()
645 def add(cls):
646 if cls is not object:
647 for base in cls.__bases__:
648 add(base)
649 for name in cls.__dict__:
650 skip.add(name)
651 add(check_not_in)
652 #
653 for base in reversed(mro):
654 assert is_mixin(base), (
655 "Mixin class %r has non mixin base class %r" % (mixins, base))
656 for name, value in base.__dict__.items():
657 if name in skip:
658 continue
659 self.add_source_attribute(name, value, mixin=True)
660 if '_immutable_fields_' in base.__dict__:
661 self.immutable_fields.update(
662 set(base.__dict__['_immutable_fields_']))
663
664
665 def add_sources_for_class(self, cls):
666 for name, value in cls.__dict__.items():
667 self.add_source_attribute(name, value)
668
669 def getclassdef(self, key):
670 return self.getuniqueclassdef()
671
672 def _init_classdef(self):
673 classdef = ClassDef(self.bookkeeper, self)
674 self.bookkeeper.classdefs.append(classdef)
675 self.classdef = classdef
676
677 # forced attributes
678 cls = self.pyobj
679 if cls in FORCE_ATTRIBUTES_INTO_CLASSES:
680 for name, s_value in FORCE_ATTRIBUTES_INTO_CLASSES[cls].items():
681 classdef.generalize_attr(name, s_value)
682 classdef.find_attribute(name).modified(classdef)
683
684 # register all class attributes as coming from this ClassDesc
685 # (as opposed to prebuilt instances)
686 classsources = {}
687 for attr in self.classdict:
688 classsources[attr] = self # comes from this ClassDesc
689 classdef.setup(classsources)
690 # look for a __del__ method and annotate it if it's there
691 if '__del__' in self.classdict:
692 from rpython.annotator.model import s_None, SomeInstance
693 s_func = self.s_read_attribute('__del__')
694 args_s = [SomeInstance(classdef)]
695 s = self.bookkeeper.emulate_pbc_call(classdef, s_func, args_s)
696 assert s_None.contains(s)
697 return classdef
698
699 def getuniqueclassdef(self):
700 if self.classdef is None:
701 self._init_classdef()
702 return self.classdef
703
704 def pycall(self, whence, args, s_previous_result, op=None):
705 from rpython.annotator.model import SomeInstance, SomeImpossibleValue
706 classdef = self.getuniqueclassdef()
707 s_instance = SomeInstance(classdef)
708 # look up __init__ directly on the class, bypassing the normal
709 # lookup mechanisms ClassDef (to avoid influencing Attribute placement)
710 s_init = self.s_read_attribute('__init__')
711 if isinstance(s_init, SomeImpossibleValue):
712 # no __init__: check that there are no constructor args
713 if not self.is_exception_class():
714 try:
715 args.fixedunpack(0)
716 except ValueError:
717 raise AnnotatorError("default __init__ takes no argument"
718 " (class %s)" % (self.name,))
719 elif self.pyobj is Exception:
720 # check explicitly against "raise Exception, x" where x
721 # is a low-level exception pointer
722 try:
723 [s_arg] = args.fixedunpack(1)
724 except ValueError:
725 pass
726 else:
727 from rpython.rtyper.llannotation import SomePtr
728 assert not isinstance(s_arg, SomePtr)
729 else:
730 # call the constructor
731 args = args.prepend(s_instance)
732 s_init.call(args)
733 return s_instance
734
735 def is_exception_class(self):
736 return issubclass(self.pyobj, BaseException)
737
738 def is_builtin_exception_class(self):
739 if self.is_exception_class():
740 if self.pyobj.__module__ == 'exceptions':
741 return True
742 if issubclass(self.pyobj, AssertionError):
743 return True
744 return False
745
746 def issubclass(self, other):
747 return issubclass(self.pyobj, other.pyobj)
748
749 def lookup(self, name):
750 cdesc = self
751 while name not in cdesc.classdict:
752 cdesc = cdesc.basedesc
753 if cdesc is None:
754 return None
755 else:
756 return cdesc
757
758 def get_param(self, name, default=None, inherit=True):
759 cls = self.pyobj
760 if inherit:
761 return getattr(cls, name, default)
762 else:
763 return cls.__dict__.get(name, default)
764
765 def read_attribute(self, name, default=NODEFAULT):
766 cdesc = self.lookup(name)
767 if cdesc is None:
768 if default is NODEFAULT:
769 raise AttributeError
770 else:
771 return default
772 else:
773 return cdesc.classdict[name]
774
775 def s_read_attribute(self, name):
776 # look up an attribute in the class
777 cdesc = self.lookup(name)
778 if cdesc is None:
779 return s_ImpossibleValue
780 else:
781 # delegate to s_get_value to turn it into an annotation
782 return cdesc.s_get_value(None, name)
783
784 def s_get_value(self, classdef, name):
785 obj = self.classdict[name]
786 if isinstance(obj, Constant):
787 value = obj.value
788 if isinstance(value, staticmethod): # special case
789 value = value.__get__(42)
790 classdef = None # don't bind
791 elif isinstance(value, classmethod):
792 raise AnnotatorError("classmethods are not supported")
793 s_value = self.bookkeeper.immutablevalue(value)
794 if classdef is not None:
795 s_value = s_value.bind_callables_under(classdef, name)
796 elif isinstance(obj, Desc):
797 if classdef is not None:
798 obj = obj.bind_under(classdef, name)
799 s_value = SomePBC([obj])
800 else:
801 raise TypeError("classdict should not contain %r" % (obj,))
802 return s_value
803
804 def create_new_attribute(self, name, value):
805 assert name not in self.classdict, "name clash: %r" % (name,)
806 self.classdict[name] = Constant(value)
807
808 def find_source_for(self, name):
809 if name in self.classdict:
810 return self
811 # check whether there is a new attribute
812 cls = self.pyobj
813 if name in cls.__dict__:
814 self.add_source_attribute(name, cls.__dict__[name])
815 if name in self.classdict:
816 return self
817 return None
818
819 def maybe_return_immutable_list(self, attr, s_result):
820 # hack: 'x.lst' where lst is listed in _immutable_fields_ as
821 # either 'lst[*]' or 'lst?[*]'
822 # should really return an immutable list as a result. Implemented
823 # by changing the result's annotation (but not, of course, doing an
824 # actual copy in the rtyper). Tested in rpython.rtyper.test.test_rlist,
825 # test_immutable_list_out_of_instance.
826 if self._detect_invalid_attrs and attr in self._detect_invalid_attrs:
827 raise AnnotatorError("field %r was migrated to %r from a subclass in "
828 "which it was declared as _immutable_fields_" %
829 (attr, self.pyobj))
830 search1 = '%s[*]' % (attr,)
831 search2 = '%s?[*]' % (attr,)
832 cdesc = self
833 while cdesc is not None:
834 immutable_fields = cdesc.immutable_fields
835 if immutable_fields:
836 if (search1 in immutable_fields or search2 in immutable_fields):
837 s_result.listdef.never_resize()
838 s_copy = s_result.listdef.offspring(self.bookkeeper)
839 s_copy.listdef.mark_as_immutable()
840 #
841 cdesc = cdesc.basedesc
842 while cdesc is not None:
843 if cdesc._detect_invalid_attrs is None:
844 cdesc._detect_invalid_attrs = set()
845 cdesc._detect_invalid_attrs.add(attr)
846 cdesc = cdesc.basedesc
847 #
848 return s_copy
849 cdesc = cdesc.basedesc
850 return s_result # common case
851
852 @staticmethod
853 def consider_call_site(descs, args, s_result, op):
854 descs[0].getcallfamily()
855 descs[0].mergecallfamilies(*descs[1:])
856 from rpython.annotator.model import SomeInstance, SomePBC, s_None
857 if len(descs) == 1:
858 # call to a single class, look at the result annotation
859 # in case it was specialized
860 if not isinstance(s_result, SomeInstance):
861 raise AnnotatorError("calling a class didn't return an instance??")
862 classdefs = [s_result.classdef]
863 else:
864 # call to multiple classes: specialization not supported
865 classdefs = [desc.getuniqueclassdef() for desc in descs]
866 # If some of the classes have an __init__ and others not, then
867 # we complain, even though in theory it could work if all the
868 # __init__s take no argument. But it's messy to implement, so
869 # let's just say it is not RPython and you have to add an empty
870 # __init__ to your base class.
871 has_init = False
872 for desc in descs:
873 s_init = desc.s_read_attribute('__init__')
874 has_init |= isinstance(s_init, SomePBC)
875 basedesc = ClassDesc.getcommonbase(descs)
876 s_init = basedesc.s_read_attribute('__init__')
877 parent_has_init = isinstance(s_init, SomePBC)
878 if has_init and not parent_has_init:
879 raise AnnotatorError(
880 "some subclasses among %r declare __init__(),"
881 " but not the common parent class" % (descs,))
882 # make a PBC of MethodDescs, one for the __init__ of each class
883 initdescs = []
884 for desc, classdef in zip(descs, classdefs):
885 s_init = desc.s_read_attribute('__init__')
886 if isinstance(s_init, SomePBC):
887 assert len(s_init.descriptions) == 1, (
888 "unexpected dynamic __init__?")
889 initfuncdesc, = s_init.descriptions
890 if isinstance(initfuncdesc, FunctionDesc):
891 from rpython.annotator.bookkeeper import getbookkeeper
892 initmethdesc = getbookkeeper().getmethoddesc(
893 initfuncdesc, classdef, classdef, '__init__')
894 initdescs.append(initmethdesc)
895 # register a call to exactly these __init__ methods
896 if initdescs:
897 initdescs[0].mergecallfamilies(*initdescs[1:])
898 MethodDesc.consider_call_site(initdescs, args, s_None, op)
899
900 def getallbases(self):
901 desc = self
902 while desc is not None:
903 yield desc
904 desc = desc.basedesc
905
906 @staticmethod
907 def getcommonbase(descs):
908 commondesc = descs[0]
909 for desc in descs[1:]:
910 allbases = set(commondesc.getallbases())
911 while desc not in allbases:
912 assert desc is not None, "no common base for %r" % (descs,)
913 desc = desc.basedesc
914 commondesc = desc
915 return commondesc
916
917 def rowkey(self):
918 return self
919
920 def getattrfamily(self, attrname):
921 "Get the ClassAttrFamily object for attrname. Possibly creates one."
922 access_sets = self.bookkeeper.get_classpbc_attr_families(attrname)
923 _, _, attrfamily = access_sets.find(self)
924 return attrfamily
925
926 def queryattrfamily(self, attrname):
927 """Retrieve the ClassAttrFamily object for attrname if there is one,
928 otherwise return None."""
929 access_sets = self.bookkeeper.get_classpbc_attr_families(attrname)
930 try:
931 return access_sets[self]
932 except KeyError:
933 return None
934
935 def mergeattrfamilies(self, others, attrname):
936 """Merge the attr families of the given Descs into one."""
937 access_sets = self.bookkeeper.get_classpbc_attr_families(attrname)
938 changed, rep, attrfamily = access_sets.find(self)
939 for desc in others:
940 changed1, rep, attrfamily = access_sets.union(rep, desc)
941 changed = changed or changed1
942 return changed
943
944 # ____________________________________________________________
945
946 class Sample(object):
947 __slots__ = 'x'
948 MemberDescriptorTypes = [type(Sample.x)]
949 del Sample
950 try:
951 MemberDescriptorTypes.append(type(OSError.errno))
952 except AttributeError: # on CPython <= 2.4
953 pass
954
955 # ____________________________________________________________
956
957 FORCE_ATTRIBUTES_INTO_CLASSES = {
958 EnvironmentError: {'errno': SomeInteger(),
959 'strerror': SomeString(can_be_None=True),
960 'filename': SomeString(can_be_None=True)},
961 }
962
963 try:
964 WindowsError
965 except NameError:
966 pass
967 else:
968 FORCE_ATTRIBUTES_INTO_CLASSES[WindowsError] = {'winerror': SomeInteger()}