| 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 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
class Attribute(object): |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 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 |
|
| 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 |
|
| 106 |
if isinstance(s_newvalue, SomePBC): |
| 107 |
attr = self.name |
| 108 |
if s_newvalue.getKind() == MethodDesc: |
| 109 |
|
| 110 |
if homedef.classdesc.read_attribute(attr, None) is None: |
| 111 |
homedef.check_missing_attribute_update(attr) |
| 112 |
|
| 113 |
|
| 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 = {} |
| 142 |
self.classdesc = classdesc |
| 143 |
self.name = self.classdesc.name |
| 144 |
self.shortname = self.name.split('.')[-1] |
| 145 |
self.subdefs = [] |
| 146 |
self.attr_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 |
|
| 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 |
|
| 172 |
|
| 173 |
|
| 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 |
|
| 179 |
|
| 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 |
|
| 195 |
attrdef = cdef.attrs[attr] |
| 196 |
s_prev_value = attrdef.s_value |
| 197 |
attrdef.add_constant_source(self, source) |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
if attrdef.s_value != s_prev_value: |
| 202 |
self.bookkeeper.update_attr(cdef, attrdef) |
| 203 |
return |
| 204 |
else: |
| 205 |
|
| 206 |
sources = self.attr_sources.setdefault(attr, []) |
| 207 |
sources.append(source) |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 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 |
|
| 276 |
newattr = Attribute(attr) |
| 277 |
if s_value: |
| 278 |
newattr.s_value = s_value |
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
constant_sources = [] |
| 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 |
|
| 290 |
lst = subdef.attr_sources[attr] |
| 291 |
for source in lst: |
| 292 |
constant_sources.append((subdef, source)) |
| 293 |
del lst[:] |
| 294 |
|
| 295 |
|
| 296 |
|
| 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 |
|
| 304 |
|
| 305 |
self.attrs[attr] = newattr |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
for origin_classdef, source in constant_sources: |
| 310 |
newattr.add_constant_source(origin_classdef, source) |
| 311 |
|
| 312 |
|
| 313 |
self.bookkeeper.update_attr(self, newattr) |
| 314 |
|
| 315 |
def generalize_attr(self, attr, s_value=None): |
| 316 |
|
| 317 |
|
| 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 |
|
| 346 |
|
| 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 |
| 351 |
elif self.issubclass(methclassdef): |
| 352 |
|
| 353 |
if uplookup is None or methclassdef.issubclass(uplookup): |
| 354 |
uplookup = methclassdef |
| 355 |
updesc = desc |
| 356 |
continue |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
else: |
| 361 |
continue |
| 362 |
|
| 363 |
|
| 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 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 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 |
|
| 393 |
self.add_source_for_attribute(name, source) |
| 394 |
|
| 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 |
|
| 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 |
| 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 = {} |
| 506 |
self.classdict = classdict |
| 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 |
|
| 521 |
|
| 522 |
|
| 523 |
if cls is Exception: |
| 524 |
baselist = [] |
| 525 |
elif baselist == [BaseException]: |
| 526 |
baselist = [Exception] |
| 527 |
|
| 528 |
immutable_fields = cls.__dict__.get('_immutable_fields_', []) |
| 529 |
|
| 530 |
|
| 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 = [] |
| 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 |
|
| 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 |
|
| 606 |
if not hasattr(value, 'class_'): |
| 607 |
value.class_ = self.pyobj |
| 608 |
if mixin: |
| 609 |
|
| 610 |
|
| 611 |
funcdesc = self.bookkeeper.newfuncdesc(value) |
| 612 |
self.classdict[name] = funcdesc |
| 613 |
return |
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
if isinstance(value, staticmethod) and mixin: |
| 620 |
|
| 621 |
func = value.__get__(42) |
| 622 |
value = staticmethod(func_with_new_name(func, func.__name__)) |
| 623 |
|
| 624 |
if type(value) in MemberDescriptorTypes: |
| 625 |
|
| 626 |
return |
| 627 |
if name == '__init__' and self.is_builtin_exception_class(): |
| 628 |
|
| 629 |
|
| 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 |
|
| 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 |
|
| 685 |
|
| 686 |
classsources = {} |
| 687 |
for attr in self.classdict: |
| 688 |
classsources[attr] = self |
| 689 |
classdef.setup(classsources) |
| 690 |
|
| 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 |
|
| 709 |
|
| 710 |
s_init = self.s_read_attribute('__init__') |
| 711 |
if isinstance(s_init, SomeImpossibleValue): |
| 712 |
|
| 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 |
|
| 721 |
|
| 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 |
|
| 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 |
|
| 777 |
cdesc = self.lookup(name) |
| 778 |
if cdesc is None: |
| 779 |
return s_ImpossibleValue |
| 780 |
else: |
| 781 |
|
| 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): |
| 789 |
value = value.__get__(42) |
| 790 |
classdef = None |
| 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 |
|
| 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 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 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 |
| 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 |
|
| 859 |
|
| 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 |
|
| 865 |
classdefs = [desc.getuniqueclassdef() for desc in descs] |
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 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 |
|
| 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 |
|
| 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: |
| 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()} |