| 1 |
import weakref |
| 2 |
from pypy.interpreter import gateway |
| 3 |
from pypy.interpreter.baseobjspace import W_Root, SpaceCache |
| 4 |
from pypy.interpreter.error import OperationError, oefmt, oefmt_attribute_error |
| 5 |
from pypy.interpreter.function import ( |
| 6 |
Function, StaticMethod, ClassMethod, FunctionWithFixedCode) |
| 7 |
from pypy.interpreter.typedef import ( |
| 8 |
weakref_descr, GetSetProperty, dict_descr, Member, TypeDef) |
| 9 |
from pypy.interpreter.astcompiler.misc import mangle |
| 10 |
from pypy.module.__builtin__ import abstractinst |
| 11 |
|
| 12 |
from rpython.rlib.jit import (promote, elidable_promote, we_are_jitted, |
| 13 |
elidable, dont_look_inside, unroll_safe) |
| 14 |
from rpython.rlib.objectmodel import current_object_addr_as_int, compute_hash |
| 15 |
from rpython.rlib.objectmodel import we_are_translated, not_rpython |
| 16 |
from rpython.rlib.rarithmetic import intmask, r_uint |
| 17 |
from rpython.rlib.rutf8 import CheckError, check_utf8, surrogate_in_utf8 |
| 18 |
|
| 19 |
PATMA_SEQUENCE = 1 << 5 |
| 20 |
PATMA_MAPPING = 1 << 6 |
| 21 |
|
| 22 |
class MutableCell(W_Root): |
| 23 |
def unwrap_cell(self, space): |
| 24 |
raise NotImplementedError("abstract base") |
| 25 |
|
| 26 |
class ObjectMutableCell(MutableCell): |
| 27 |
def __init__(self, w_value=None): |
| 28 |
self.w_value = w_value |
| 29 |
|
| 30 |
def unwrap_cell(self, space): |
| 31 |
return self.w_value |
| 32 |
|
| 33 |
def __repr__(self): |
| 34 |
return "<ObjectMutableCell: %s>" % (self.w_value, ) |
| 35 |
|
| 36 |
|
| 37 |
class IntMutableCell(MutableCell): |
| 38 |
def __init__(self, intvalue): |
| 39 |
self.intvalue = intvalue |
| 40 |
|
| 41 |
def unwrap_cell(self, space): |
| 42 |
return space.newint(self.intvalue) |
| 43 |
|
| 44 |
def __repr__(self): |
| 45 |
return "<IntMutableCell: %s>" % (self.intvalue, ) |
| 46 |
|
| 47 |
|
| 48 |
def unwrap_cell(space, w_value): |
| 49 |
if isinstance(w_value, MutableCell): |
| 50 |
return w_value.unwrap_cell(space) |
| 51 |
return w_value |
| 52 |
|
| 53 |
def write_cell(space, w_cell, w_value): |
| 54 |
from pypy.objspace.std.listobject import is_plain_int1, plain_int_w |
| 55 |
if w_cell is None: |
| 56 |
|
| 57 |
return w_value |
| 58 |
if isinstance(w_cell, ObjectMutableCell): |
| 59 |
w_cell.w_value = w_value |
| 60 |
return None |
| 61 |
elif isinstance(w_cell, IntMutableCell) and is_plain_int1(w_value): |
| 62 |
w_cell.intvalue = plain_int_w(space, w_value) |
| 63 |
return None |
| 64 |
elif space.is_w(w_cell, w_value): |
| 65 |
|
| 66 |
|
| 67 |
return None |
| 68 |
if is_plain_int1(w_value): |
| 69 |
return IntMutableCell(plain_int_w(space, w_value)) |
| 70 |
else: |
| 71 |
return ObjectMutableCell(w_value) |
| 72 |
|
| 73 |
class VersionTag(object): |
| 74 |
pass |
| 75 |
|
| 76 |
class MethodCache(object): |
| 77 |
|
| 78 |
def __init__(self, space): |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
SIZE = 1 << space.config.objspace.std.methodcachesizeexp |
| 84 |
self.versions = [None] * SIZE |
| 85 |
self.names = [None] * SIZE |
| 86 |
self.lookup_where = [(None, None)] * SIZE |
| 87 |
if space.config.objspace.std.withmethodcachecounter: |
| 88 |
self.hits = {} |
| 89 |
self.misses = {} |
| 90 |
|
| 91 |
def clear(self): |
| 92 |
None_None = (None, None) |
| 93 |
for i in range(len(self.versions)): |
| 94 |
self.versions[i] = None |
| 95 |
for i in range(len(self.names)): |
| 96 |
self.names[i] = None |
| 97 |
for i in range(len(self.lookup_where)): |
| 98 |
self.lookup_where[i] = None_None |
| 99 |
|
| 100 |
def _cleanup_(self): |
| 101 |
self.clear() |
| 102 |
|
| 103 |
class _Global(object): |
| 104 |
weakref_warning_printed = False |
| 105 |
_global = _Global() |
| 106 |
|
| 107 |
|
| 108 |
class Layout(object): |
| 109 |
"""A Layout is attached to every W_TypeObject to represent the |
| 110 |
layout of instances. Some W_TypeObjects share the same layout. |
| 111 |
If a W_TypeObject is a base of another, then the layout of |
| 112 |
the first is either the same or a parent layout of the second. |
| 113 |
The Layouts have single inheritance, unlike W_TypeObjects. |
| 114 |
""" |
| 115 |
_immutable_ = True |
| 116 |
|
| 117 |
def __init__(self, typedef, nslots, newslotnames=[], base_layout=None): |
| 118 |
self.typedef = typedef |
| 119 |
self.nslots = nslots |
| 120 |
self.newslotnames = newslotnames[:] |
| 121 |
self.base_layout = base_layout |
| 122 |
|
| 123 |
def issublayout(self, parent): |
| 124 |
while self is not parent: |
| 125 |
self = self.base_layout |
| 126 |
if self is None: |
| 127 |
return False |
| 128 |
return True |
| 129 |
|
| 130 |
def expand(self, hasdict, weakrefable): |
| 131 |
"""Turn this Layout into a tuple. If two classes get equal |
| 132 |
tuples, it means their instances have a fully compatible layout.""" |
| 133 |
return (self.typedef, self.newslotnames, self.base_layout, |
| 134 |
hasdict, weakrefable) |
| 135 |
|
| 136 |
def __repr__(self): |
| 137 |
|
| 138 |
return "Layout(%s, %s, %s, %s)" % (self.typedef, self.nslots, self.newslotnames, self.base_layout) |
| 139 |
|
| 140 |
|
| 141 |
def _check_surrogate(space, name): |
| 142 |
try: |
| 143 |
check_utf8(name, False) |
| 144 |
except CheckError as e: |
| 145 |
raise OperationError(space.w_UnicodeEncodeError, |
| 146 |
space.newtuple([space.newtext('utf8'), |
| 147 |
space.newtext(name), |
| 148 |
space.newint(e.pos), |
| 149 |
space.newint(e.pos + 1), |
| 150 |
space.newtext('surrogates not allowed')])) |
| 151 |
|
| 152 |
|
| 153 |
UNKNOWN = 0 |
| 154 |
COMPARES_BY_IDENTITY = 1 |
| 155 |
OVERRIDES_EQ_CMP_OR_HASH = 2 |
| 156 |
|
| 157 |
class W_TypeObject(W_Root): |
| 158 |
lazyloaders = {} |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
_version_tag = None |
| 163 |
|
| 164 |
_immutable_fields_ = ["flag_heaptype", |
| 165 |
"flag_cpytype", |
| 166 |
"flag_abstract?", |
| 167 |
"flag_sequence_bug_compat", |
| 168 |
"flag_patma_collection?", |
| 169 |
"flag_map_or_seq", |
| 170 |
"flag_method_descriptor", |
| 171 |
"compares_by_identity_status?", |
| 172 |
'hasuserdel', |
| 173 |
'weakrefable', |
| 174 |
'hasdict', |
| 175 |
'layout?', |
| 176 |
'terminator', |
| 177 |
'_version_tag?', |
| 178 |
'name?', |
| 179 |
'mro_w?[*]', |
| 180 |
'hasmro?', |
| 181 |
] |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
uses_object_getattribute = False |
| 186 |
uses_object_setattr = False |
| 187 |
|
| 188 |
|
| 189 |
compares_by_identity_status = UNKNOWN |
| 190 |
|
| 191 |
|
| 192 |
w_new_function = None |
| 193 |
|
| 194 |
|
| 195 |
flag_cpytype = False |
| 196 |
|
| 197 |
flag_method_descriptor = False |
| 198 |
|
| 199 |
@dont_look_inside |
| 200 |
def __init__(self, space, name, bases_w, dict_w, |
| 201 |
overridetypedef=None, force_new_layout=False, |
| 202 |
is_heaptype=True): |
| 203 |
self.space = space |
| 204 |
_check_surrogate(space, name) |
| 205 |
self.name = name |
| 206 |
self.qualname = None |
| 207 |
self.bases_w = bases_w |
| 208 |
self.dict_w = dict_w |
| 209 |
self.hasdict = False |
| 210 |
self.hasuserdel = False |
| 211 |
self.weakrefable = False |
| 212 |
self.w_doc = space.w_None |
| 213 |
self.text_signature = None |
| 214 |
self.weak_subclasses = [] |
| 215 |
self.flag_heaptype = is_heaptype |
| 216 |
self.flag_abstract = False |
| 217 |
self.flag_sequence_bug_compat = False |
| 218 |
self.flag_patma_collection = "X" |
| 219 |
self.flag_map_or_seq = '?' |
| 220 |
|
| 221 |
self.layout = None |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
self.qualname = self.getname(space) |
| 227 |
if self.flag_heaptype: |
| 228 |
w_qualname = self.dict_w.pop('__qualname__', None) |
| 229 |
if w_qualname is not None: |
| 230 |
if space.isinstance_w(w_qualname, space.w_unicode): |
| 231 |
self.qualname = space.utf8_w(w_qualname) |
| 232 |
elif not self.flag_cpytype: |
| 233 |
raise oefmt(space.w_TypeError, |
| 234 |
"type __qualname__ must be a str, not %T", |
| 235 |
w_qualname) |
| 236 |
|
| 237 |
if overridetypedef is not None: |
| 238 |
assert not force_new_layout |
| 239 |
layout = setup_builtin_type(self, overridetypedef) |
| 240 |
else: |
| 241 |
layout = setup_user_defined_type(self, force_new_layout) |
| 242 |
self.layout = layout |
| 243 |
|
| 244 |
if not is_mro_purely_of_types(self.mro_w): |
| 245 |
pass |
| 246 |
else: |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
self._version_tag = VersionTag() |
| 251 |
from pypy.objspace.std.mapdict import DictTerminator, NoDictTerminator |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
typedef = self.layout.typedef |
| 256 |
self.flag_method_descriptor = typedef.method_descriptor |
| 257 |
if (self.hasdict and not typedef.hasdict): |
| 258 |
self.terminator = DictTerminator(space, self) |
| 259 |
else: |
| 260 |
self.terminator = NoDictTerminator(space, self) |
| 261 |
|
| 262 |
@not_rpython |
| 263 |
def __repr__(self): |
| 264 |
return '<W_TypeObject %r at 0x%x>' % (self.name, id(self)) |
| 265 |
|
| 266 |
def mutated(self, key): |
| 267 |
""" |
| 268 |
The type is being mutated. key is either the string containing the |
| 269 |
specific attribute which is being deleted/set or None to indicate a |
| 270 |
generic mutation. |
| 271 |
""" |
| 272 |
space = self.space |
| 273 |
assert self.is_heaptype() or self.is_cpytype() |
| 274 |
|
| 275 |
self.uses_object_getattribute = False |
| 276 |
self.uses_object_setattr = False |
| 277 |
|
| 278 |
|
| 279 |
if (key is None or key == '__eq__' or key == '__hash__'): |
| 280 |
self.compares_by_identity_status = UNKNOWN |
| 281 |
|
| 282 |
if space.config.objspace.std.newshortcut: |
| 283 |
self.w_new_function = None |
| 284 |
|
| 285 |
if self._version_tag is not None: |
| 286 |
self._version_tag = VersionTag() |
| 287 |
|
| 288 |
subclasses_w = self.get_subclasses() |
| 289 |
for w_subclass in subclasses_w: |
| 290 |
assert isinstance(w_subclass, W_TypeObject) |
| 291 |
w_subclass.mutated(key) |
| 292 |
|
| 293 |
def version_tag(self): |
| 294 |
if not we_are_jitted() or self.is_heaptype(): |
| 295 |
return self._version_tag |
| 296 |
|
| 297 |
return self._pure_version_tag() |
| 298 |
|
| 299 |
@elidable_promote() |
| 300 |
def _pure_version_tag(self): |
| 301 |
return self._version_tag |
| 302 |
|
| 303 |
def getattribute_if_not_from_object(self): |
| 304 |
""" this method returns the applevel __getattribute__ if that is not |
| 305 |
the one from object, in which case it returns None """ |
| 306 |
from pypy.objspace.descroperation import object_getattribute |
| 307 |
if not we_are_jitted(): |
| 308 |
if not self.uses_object_getattribute: |
| 309 |
|
| 310 |
w_descr = self.lookup('__getattribute__') |
| 311 |
|
| 312 |
|
| 313 |
if w_descr is object_getattribute(self.space): |
| 314 |
if self.space._side_effects_ok(): |
| 315 |
self.uses_object_getattribute = True |
| 316 |
else: |
| 317 |
return w_descr |
| 318 |
return None |
| 319 |
|
| 320 |
|
| 321 |
w_descr = self.lookup('__getattribute__') |
| 322 |
if w_descr is not object_getattribute(self.space): |
| 323 |
return w_descr |
| 324 |
|
| 325 |
def has_object_getattribute(self): |
| 326 |
return self.getattribute_if_not_from_object() is None |
| 327 |
|
| 328 |
def setattr_if_not_from_object(self): |
| 329 |
""" this method returns the applevel __setattr__ if that is not |
| 330 |
the one from object, in which case it returns None """ |
| 331 |
from pypy.objspace.descroperation import object_setattr |
| 332 |
if not we_are_jitted(): |
| 333 |
if not self.uses_object_setattr: |
| 334 |
|
| 335 |
w_descr = self.lookup('__setattr__') |
| 336 |
|
| 337 |
|
| 338 |
if w_descr is object_setattr(self.space): |
| 339 |
if self.space._side_effects_ok(): |
| 340 |
self.uses_object_setattr = True |
| 341 |
else: |
| 342 |
return w_descr |
| 343 |
return None |
| 344 |
|
| 345 |
|
| 346 |
w_descr = self.lookup('__setattr__') |
| 347 |
if w_descr is not object_setattr(self.space): |
| 348 |
return w_descr |
| 349 |
|
| 350 |
def has_object_setattr(self): |
| 351 |
return self.setattr_if_not_from_object() is None |
| 352 |
|
| 353 |
def compares_by_identity(self): |
| 354 |
from pypy.objspace.descroperation import object_hash, type_eq |
| 355 |
|
| 356 |
if self.compares_by_identity_status != UNKNOWN: |
| 357 |
|
| 358 |
return self.compares_by_identity_status == COMPARES_BY_IDENTITY |
| 359 |
|
| 360 |
default_hash = object_hash(self.space) |
| 361 |
my_eq = self.lookup('__eq__') |
| 362 |
overrides_eq = (my_eq and my_eq is not type_eq(self.space)) |
| 363 |
overrides_eq_cmp_or_hash = (overrides_eq or |
| 364 |
self.lookup('__hash__') is not default_hash) |
| 365 |
if overrides_eq_cmp_or_hash: |
| 366 |
result = OVERRIDES_EQ_CMP_OR_HASH |
| 367 |
else: |
| 368 |
result = COMPARES_BY_IDENTITY |
| 369 |
if self.space._side_effects_ok(): |
| 370 |
self.compares_by_identity_status = result |
| 371 |
return result == COMPARES_BY_IDENTITY |
| 372 |
|
| 373 |
def ready(self): |
| 374 |
for w_base in self.bases_w: |
| 375 |
if not isinstance(w_base, W_TypeObject): |
| 376 |
continue |
| 377 |
w_base.add_subclass(self) |
| 378 |
|
| 379 |
|
| 380 |
def get_full_instance_layout(self): |
| 381 |
return self.layout.expand(self.hasdict, self.weakrefable) |
| 382 |
|
| 383 |
def compute_default_mro(self): |
| 384 |
return compute_C3_mro(self.space, self) |
| 385 |
|
| 386 |
def getdictvalue(self, space, attr): |
| 387 |
version_tag = self.version_tag() |
| 388 |
if version_tag is not None: |
| 389 |
return unwrap_cell( |
| 390 |
space, |
| 391 |
self._pure_getdictvalue_no_unwrapping( |
| 392 |
space, version_tag, attr)) |
| 393 |
w_value = self._getdictvalue_no_unwrapping(space, attr) |
| 394 |
return unwrap_cell(space, w_value) |
| 395 |
|
| 396 |
def _getdictvalue_no_unwrapping(self, space, attr): |
| 397 |
w_value = self.dict_w.get(attr, None) |
| 398 |
if self.lazyloaders and w_value is None: |
| 399 |
if attr in self.lazyloaders: |
| 400 |
|
| 401 |
|
| 402 |
space.new_interned_str(attr) |
| 403 |
loader = self.lazyloaders[attr] |
| 404 |
del self.lazyloaders[attr] |
| 405 |
w_value = loader() |
| 406 |
if w_value is not None: |
| 407 |
self.dict_w[attr] = w_value |
| 408 |
return w_value |
| 409 |
return w_value |
| 410 |
|
| 411 |
@elidable |
| 412 |
def _pure_getdictvalue_no_unwrapping(self, space, version_tag, attr): |
| 413 |
return self._getdictvalue_no_unwrapping(space, attr) |
| 414 |
|
| 415 |
def setdictvalue(self, space, name, w_value): |
| 416 |
if not self.is_heaptype(): |
| 417 |
raise oefmt(space.w_TypeError, |
| 418 |
"cannot set '%s' attribute of immutable type '%N'", name, self) |
| 419 |
if name == "__del__" and name not in self.dict_w: |
| 420 |
msg = ("a __del__ method added to an existing type will not be " |
| 421 |
"called") |
| 422 |
space.warn(space.newtext(msg), space.w_RuntimeWarning) |
| 423 |
version_tag = self.version_tag() |
| 424 |
if version_tag is not None: |
| 425 |
w_curr = self._pure_getdictvalue_no_unwrapping( |
| 426 |
space, version_tag, name) |
| 427 |
w_value = write_cell(space, w_curr, w_value) |
| 428 |
if w_value is None: |
| 429 |
return True |
| 430 |
self.mutated(name) |
| 431 |
self.dict_w[name] = w_value |
| 432 |
return True |
| 433 |
|
| 434 |
def deldictvalue(self, space, key): |
| 435 |
if self.lazyloaders: |
| 436 |
self._cleanup_() |
| 437 |
if not (self.is_heaptype() or self.is_cpytype()): |
| 438 |
raise oefmt(space.w_TypeError, |
| 439 |
"cannot delete attributes on immutable type object '%N'", self) |
| 440 |
try: |
| 441 |
del self.dict_w[key] |
| 442 |
except KeyError: |
| 443 |
return False |
| 444 |
else: |
| 445 |
self.mutated(key) |
| 446 |
return True |
| 447 |
|
| 448 |
def lookup(self, name): |
| 449 |
|
| 450 |
space = self.space |
| 451 |
return self.lookup_where_with_method_cache(name)[1] |
| 452 |
|
| 453 |
def lookup_where(self, name): |
| 454 |
space = self.space |
| 455 |
return self.lookup_where_with_method_cache(name) |
| 456 |
|
| 457 |
@unroll_safe |
| 458 |
def lookup_starting_at(self, w_starttype, name): |
| 459 |
space = self.space |
| 460 |
look = False |
| 461 |
for w_class in self.mro_w: |
| 462 |
if w_class is w_starttype: |
| 463 |
look = True |
| 464 |
elif look: |
| 465 |
w_value = w_class.getdictvalue(space, name) |
| 466 |
if w_value is not None: |
| 467 |
return w_value |
| 468 |
return None |
| 469 |
|
| 470 |
@unroll_safe |
| 471 |
def _lookup(self, key): |
| 472 |
|
| 473 |
space = self.space |
| 474 |
for w_class in self.mro_w: |
| 475 |
w_value = w_class.getdictvalue(space, key) |
| 476 |
if w_value is not None: |
| 477 |
return w_value |
| 478 |
return None |
| 479 |
|
| 480 |
@unroll_safe |
| 481 |
def _lookup_where(self, key): |
| 482 |
|
| 483 |
|
| 484 |
space = self.space |
| 485 |
for w_class in self.mro_w: |
| 486 |
w_value = w_class.getdictvalue(space, key) |
| 487 |
if w_value is not None: |
| 488 |
return w_class, w_value |
| 489 |
return None, None |
| 490 |
|
| 491 |
def _lookup_where_all_typeobjects(self, key): |
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
space = self.space |
| 496 |
for w_class in self.mro_w: |
| 497 |
assert isinstance(w_class, W_TypeObject) |
| 498 |
w_value = w_class._getdictvalue_no_unwrapping(space, key) |
| 499 |
if w_value is not None: |
| 500 |
return w_class, w_value |
| 501 |
return None, None |
| 502 |
|
| 503 |
def lookup_where_with_method_cache(self, name): |
| 504 |
space = self.space |
| 505 |
promote(self) |
| 506 |
version_tag = promote(self.version_tag()) |
| 507 |
if version_tag is None: |
| 508 |
tup = self._lookup_where(name) |
| 509 |
return tup |
| 510 |
tup_w = self._pure_lookup_where_with_method_cache(name, version_tag) |
| 511 |
w_class, w_value = tup_w |
| 512 |
if isinstance(w_value, MutableCell): |
| 513 |
return w_class, w_value.unwrap_cell(space) |
| 514 |
return tup_w |
| 515 |
|
| 516 |
@elidable |
| 517 |
def _pure_lookup_where_with_method_cache(self, name, version_tag): |
| 518 |
space = self.space |
| 519 |
cache = space.fromcache(MethodCache) |
| 520 |
SHIFT2 = r_uint.BITS - space.config.objspace.std.methodcachesizeexp |
| 521 |
SHIFT1 = SHIFT2 - 5 |
| 522 |
version_tag_as_int = current_object_addr_as_int(version_tag) |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
hash_name = compute_hash(name) |
| 530 |
product = intmask(version_tag_as_int * hash_name) |
| 531 |
method_hash = (r_uint(product) ^ (r_uint(product) << SHIFT1)) >> SHIFT2 |
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
cached_version_tag = cache.versions[method_hash] |
| 537 |
if cached_version_tag is version_tag: |
| 538 |
cached_name = cache.names[method_hash] |
| 539 |
if cached_name == name: |
| 540 |
tup = cache.lookup_where[method_hash] |
| 541 |
if space.config.objspace.std.withmethodcachecounter: |
| 542 |
cache.hits[name] = cache.hits.get(name, 0) + 1 |
| 543 |
|
| 544 |
return tup |
| 545 |
tup = self._lookup_where_all_typeobjects(name) |
| 546 |
if space._side_effects_ok(): |
| 547 |
cache.versions[method_hash] = version_tag |
| 548 |
cache.names[method_hash] = name |
| 549 |
cache.lookup_where[method_hash] = tup |
| 550 |
if space.config.objspace.std.withmethodcachecounter: |
| 551 |
cache.misses[name] = cache.misses.get(name, 0) + 1 |
| 552 |
|
| 553 |
return tup |
| 554 |
|
| 555 |
def check_user_subclass(self, w_subtype): |
| 556 |
space = self.space |
| 557 |
if not isinstance(w_subtype, W_TypeObject): |
| 558 |
raise oefmt(space.w_TypeError, |
| 559 |
"X is not a type object ('%T')", w_subtype) |
| 560 |
if not w_subtype.layout: |
| 561 |
raise oefmt(space.w_TypeError, |
| 562 |
"%N.__new__(%N): uninitialized type %N may not be instantiated yet.", |
| 563 |
self, w_subtype, w_subtype) |
| 564 |
if not w_subtype.issubtype(self): |
| 565 |
raise oefmt(space.w_TypeError, |
| 566 |
"%N.__new__(%N): %N is not a subtype of %N", |
| 567 |
self, w_subtype, w_subtype, self) |
| 568 |
if self.layout.typedef is not w_subtype.layout.typedef: |
| 569 |
raise oefmt(space.w_TypeError, |
| 570 |
"%N.__new__(%N) is not safe, use %N.__new__()", |
| 571 |
self, w_subtype, w_subtype) |
| 572 |
return w_subtype |
| 573 |
|
| 574 |
@not_rpython |
| 575 |
def _cleanup_(self): |
| 576 |
"Forces the lazy attributes to be computed." |
| 577 |
if 'lazyloaders' in self.__dict__: |
| 578 |
for attr in self.lazyloaders.keys(): |
| 579 |
self.getdictvalue(self.space, attr) |
| 580 |
del self.lazyloaders |
| 581 |
|
| 582 |
def getdict(self, space): |
| 583 |
from pypy.objspace.std.classdict import ClassDictStrategy |
| 584 |
from pypy.objspace.std.dictmultiobject import W_DictObject |
| 585 |
if self.lazyloaders: |
| 586 |
self._cleanup_() |
| 587 |
strategy = space.fromcache(ClassDictStrategy) |
| 588 |
storage = strategy.erase(self) |
| 589 |
return W_DictObject(space, strategy, storage) |
| 590 |
|
| 591 |
def is_heaptype(self): |
| 592 |
return self.flag_heaptype |
| 593 |
|
| 594 |
def is_cpytype(self): |
| 595 |
return self.flag_cpytype |
| 596 |
|
| 597 |
def is_abstract(self): |
| 598 |
return self.flag_abstract |
| 599 |
|
| 600 |
def set_abstract(self, abstract): |
| 601 |
self.flag_abstract = bool(abstract) |
| 602 |
|
| 603 |
def issubtype(self, w_type): |
| 604 |
promote(self) |
| 605 |
promote(w_type) |
| 606 |
if we_are_jitted(): |
| 607 |
version_tag1 = self.version_tag() |
| 608 |
version_tag2 = w_type.version_tag() |
| 609 |
if version_tag1 is not None and version_tag2 is not None: |
| 610 |
res = _pure_issubtype(self, w_type, version_tag1, version_tag2) |
| 611 |
return res |
| 612 |
return _issubtype(self, w_type) |
| 613 |
|
| 614 |
def get_module(self): |
| 615 |
space = self.space |
| 616 |
if self.is_heaptype(): |
| 617 |
return self.getdictvalue(space, '__module__') |
| 618 |
else: |
| 619 |
dot = self.name.rfind('.') |
| 620 |
if dot >= 0: |
| 621 |
mod = self.name[:dot] |
| 622 |
else: |
| 623 |
mod = "builtins" |
| 624 |
return space.newtext(mod) |
| 625 |
|
| 626 |
def getname(self, space): |
| 627 |
if self.is_heaptype(): |
| 628 |
result = self.name |
| 629 |
else: |
| 630 |
dot = self.name.rfind('.') |
| 631 |
if dot >= 0: |
| 632 |
result = self.name[dot+1:] |
| 633 |
else: |
| 634 |
result = self.name |
| 635 |
return result |
| 636 |
|
| 637 |
def getqualname(self, space): |
| 638 |
return self.qualname |
| 639 |
|
| 640 |
def add_subclass(self, w_subclass): |
| 641 |
space = self.space |
| 642 |
if not space.config.translation.rweakref: |
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
if we_are_translated() and not _global.weakref_warning_printed: |
| 647 |
from rpython.rlib import debug |
| 648 |
debug.debug_print("Warning: no weakref support in this PyPy. " |
| 649 |
"All user-defined classes will leak!") |
| 650 |
_global.weakref_warning_printed = True |
| 651 |
|
| 652 |
assert isinstance(w_subclass, W_TypeObject) |
| 653 |
newref = weakref.ref(w_subclass) |
| 654 |
for i in range(len(self.weak_subclasses)): |
| 655 |
ref = self.weak_subclasses[i] |
| 656 |
if ref() is w_subclass: |
| 657 |
return |
| 658 |
if ref() is None: |
| 659 |
self.weak_subclasses[i] = newref |
| 660 |
return |
| 661 |
else: |
| 662 |
self.weak_subclasses.append(newref) |
| 663 |
|
| 664 |
def remove_subclass(self, w_subclass): |
| 665 |
space = self.space |
| 666 |
for i in range(len(self.weak_subclasses)): |
| 667 |
ref = self.weak_subclasses[i] |
| 668 |
if ref() is w_subclass: |
| 669 |
del self.weak_subclasses[i] |
| 670 |
return |
| 671 |
|
| 672 |
def get_subclasses(self, only_real_subclasses=False): |
| 673 |
""" return the subclasses of self. if only_real_subclasses is True, |
| 674 |
then we check whether the subclass has self in its .__bases__ before |
| 675 |
adding it to the result list (which can be false in the case of |
| 676 |
metaclasses that override type.mro, see _add_mro_classes_as_subclasses). |
| 677 |
|
| 678 |
only_real_subclasses should be False for all *invalidation* use cases, |
| 679 |
and True only for descr___subclasses__""" |
| 680 |
space = self.space |
| 681 |
subclasses_w = [] |
| 682 |
for ref in self.weak_subclasses: |
| 683 |
w_ob = ref() |
| 684 |
if w_ob is not None: |
| 685 |
if only_real_subclasses: |
| 686 |
if not space.contains_w(space.getattr(w_ob, space.newtext('__bases__')), self): |
| 687 |
continue |
| 688 |
subclasses_w.append(w_ob) |
| 689 |
return subclasses_w |
| 690 |
|
| 691 |
|
| 692 |
_lifeline_ = None |
| 693 |
|
| 694 |
def getweakref(self): |
| 695 |
return self._lifeline_ |
| 696 |
|
| 697 |
def setweakref(self, space, weakreflifeline): |
| 698 |
self._lifeline_ = weakreflifeline |
| 699 |
|
| 700 |
def delweakref(self): |
| 701 |
self._lifeline_ = None |
| 702 |
|
| 703 |
def descr_call(self, space, __args__): |
| 704 |
promote(self) |
| 705 |
|
| 706 |
if not we_are_jitted(): |
| 707 |
|
| 708 |
|
| 709 |
w_newfunc = self.w_new_function |
| 710 |
else: |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
w_newfunc = None |
| 715 |
if w_newfunc is None: |
| 716 |
w_newtype, w_newdescr = self.lookup_where('__new__') |
| 717 |
if w_newdescr is None: |
| 718 |
raise oefmt(space.w_TypeError, "cannot create '%N' instances", |
| 719 |
self) |
| 720 |
|
| 721 |
|
| 722 |
if space.config.objspace.usemodules.cpyext: |
| 723 |
w_newtype, w_newdescr = self.hack_which_new_to_call( |
| 724 |
w_newtype, w_newdescr) |
| 725 |
|
| 726 |
w_newfunc = space.get(w_newdescr, space.w_None, w_type=self) |
| 727 |
if (space.config.objspace.std.newshortcut and |
| 728 |
not we_are_jitted() and space._side_effects_ok() and |
| 729 |
isinstance(w_newtype, W_TypeObject)): |
| 730 |
self.w_new_function = w_newfunc |
| 731 |
w_newobject = space.call_obj_args(w_newfunc, self, __args__) |
| 732 |
call_init = space.isinstance_w(w_newobject, self) |
| 733 |
|
| 734 |
|
| 735 |
if (call_init and not (space.is_w(self, space.w_type) and |
| 736 |
not __args__.keyword_names_w and len(__args__.arguments_w) == 1)): |
| 737 |
w_descr = space.lookup(w_newobject, '__init__') |
| 738 |
if w_descr is not None: |
| 739 |
w_result = space.get_and_call_args(w_descr, w_newobject, |
| 740 |
__args__) |
| 741 |
if not space.is_w(w_result, space.w_None): |
| 742 |
raise oefmt(space.w_TypeError, |
| 743 |
"__init__() should return None") |
| 744 |
return w_newobject |
| 745 |
|
| 746 |
def hack_which_new_to_call(self, w_newtype, w_newdescr): |
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
from pypy.module.cpyext.methodobject import W_PyCFunctionObject |
| 761 |
|
| 762 |
if isinstance(w_newdescr, W_PyCFunctionObject): |
| 763 |
return self._find_which_tp_new_to_call(w_newtype, w_newdescr) |
| 764 |
else: |
| 765 |
return w_newtype, w_newdescr |
| 766 |
|
| 767 |
def _find_which_tp_new_to_call(self, w_newtype, w_newdescr): |
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
from pypy.module.cpyext.methodobject import W_PyCFunctionObject |
| 774 |
from pypy.module.cpyext.typeobject import is_tp_new_wrapper |
| 775 |
|
| 776 |
if (isinstance(w_newdescr, W_PyCFunctionObject) and |
| 777 |
w_newtype is not self and |
| 778 |
is_tp_new_wrapper(self.space, w_newdescr.ml)): |
| 779 |
w_bestbase = find_best_base(self.bases_w) |
| 780 |
if w_bestbase is not None: |
| 781 |
w_newtype2, w_newdescr2 = w_bestbase.lookup_where('__new__') |
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
if w_newtype2 is self.space.w_object: |
| 788 |
pass |
| 789 |
elif (isinstance(w_newdescr2, W_PyCFunctionObject) and |
| 790 |
is_tp_new_wrapper(self.space, w_newdescr2.ml)): |
| 791 |
return w_bestbase._find_which_tp_new_to_call( |
| 792 |
w_newtype2, w_newdescr2) |
| 793 |
else: |
| 794 |
return w_newtype2, w_newdescr2 |
| 795 |
return w_newtype, w_newdescr |
| 796 |
|
| 797 |
def descr_repr(self, space): |
| 798 |
w_mod = self.get_module() |
| 799 |
if w_mod is None or not space.isinstance_w(w_mod, space.w_text): |
| 800 |
mod = None |
| 801 |
else: |
| 802 |
mod = space.utf8_w(w_mod) |
| 803 |
if mod is not None and mod != b'builtins': |
| 804 |
return space.newtext(b"<class '%s.%s'>" % (mod, self.getqualname(space))) |
| 805 |
else: |
| 806 |
return space.newtext("<class '%s'>" % (self.name,)) |
| 807 |
|
| 808 |
def iterator_greenkey_printable(self): |
| 809 |
return self.name |
| 810 |
|
| 811 |
def descr_getattribute(self, space, w_name): |
| 812 |
name = space.text_w(w_name) |
| 813 |
w_descr = space.lookup(self, name) |
| 814 |
if w_descr is not None: |
| 815 |
if space.is_data_descr(w_descr): |
| 816 |
w_get = space.lookup(w_descr, "__get__") |
| 817 |
if w_get is not None: |
| 818 |
return space.get_and_call_function(w_get, w_descr, self, |
| 819 |
space.type(self)) |
| 820 |
w_value = self.lookup(name) |
| 821 |
if w_value is not None: |
| 822 |
|
| 823 |
return space.get(w_value, space.w_None, self) |
| 824 |
if w_descr is not None: |
| 825 |
return space.get(w_descr, self) |
| 826 |
raise oefmt_attribute_error( |
| 827 |
space, self, w_name, "type object '%N' has no attribute %R") |
| 828 |
|
| 829 |
def acceptable_as_base_class(self, space): |
| 830 |
|
| 831 |
return self.layout.typedef.acceptable_as_base_class |
| 832 |
|
| 833 |
def descr_or(self, space, w_other): |
| 834 |
w_builtins = space.getbuiltinmodule('builtins') |
| 835 |
w_mod = space.call_method(w_builtins, '__import__', space.newtext("_pypy_generic_alias")) |
| 836 |
w_union = space.getattr(w_mod, space.newtext("_create_union")) |
| 837 |
return space.call_function(w_union, self, w_other) |
| 838 |
|
| 839 |
def descr_ror(self, space, w_other): |
| 840 |
w_builtins = space.getbuiltinmodule('builtins') |
| 841 |
w_mod = space.call_method(w_builtins, '__import__', space.newtext("_pypy_generic_alias")) |
| 842 |
w_union = space.getattr(w_mod, space.newtext("_create_union")) |
| 843 |
return space.call_function(w_union, w_other, self) |
| 844 |
|
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
def descr_get_annotations(self, space): |
| 849 |
w_ann = self.getdictvalue(space, '__annotations__') |
| 850 |
if w_ann is None: |
| 851 |
if not self.is_heaptype(): |
| 852 |
raise oefmt_attribute_error( |
| 853 |
space, self, space.newtext("__annotations__"), |
| 854 |
"type object '%N' has no attribute %R") |
| 855 |
w_ann = space.newdict() |
| 856 |
self.setdictvalue(space, '__annotations__', w_ann) |
| 857 |
return w_ann |
| 858 |
|
| 859 |
def descr_set_annotations(self, space, w_ann): |
| 860 |
self.setdictvalue(space, '__annotations__', w_ann) |
| 861 |
|
| 862 |
def descr_del_annotations(self, space): |
| 863 |
if not self.deldictvalue(space, '__annotations__'): |
| 864 |
raise oefmt(space.w_AttributeError, "__annotations__") |
| 865 |
|
| 866 |
def get_flags(self): |
| 867 |
from copy_reg import _HEAPTYPE |
| 868 |
_CPYTYPE = 1 |
| 869 |
_ABSTRACT = 1 << 20 |
| 870 |
|
| 871 |
flags = 0 |
| 872 |
if self.flag_heaptype: |
| 873 |
flags |= _HEAPTYPE |
| 874 |
if self.flag_cpytype: |
| 875 |
flags |= _CPYTYPE |
| 876 |
if self.flag_abstract: |
| 877 |
flags |= _ABSTRACT |
| 878 |
if self.flag_patma_collection == "M": |
| 879 |
flags |= PATMA_MAPPING |
| 880 |
elif self.flag_patma_collection == "S": |
| 881 |
flags |= PATMA_SEQUENCE |
| 882 |
if self.flag_method_descriptor: |
| 883 |
flags |= 1 << 17 |
| 884 |
return flags |
| 885 |
|
| 886 |
def descr__new__(space, w_typetype, __args__): |
| 887 |
"""This is used to create user-defined classes only.""" |
| 888 |
if len(__args__.arguments_w) not in (1, 3): |
| 889 |
if space.is_w(w_typetype, space.w_type): |
| 890 |
raise oefmt(space.w_TypeError, |
| 891 |
"type.__new__() takes 1 or 3 arguments") |
| 892 |
else: |
| 893 |
raise oefmt(space.w_TypeError, |
| 894 |
"%N.__new__() takes exactly 3 arguments (1 given)", |
| 895 |
w_typetype) |
| 896 |
|
| 897 |
w_name = __args__.arguments_w[0] |
| 898 |
|
| 899 |
w_typetype = _precheck_for_new(space, w_typetype) |
| 900 |
|
| 901 |
|
| 902 |
if len(__args__.arguments_w) == 1: |
| 903 |
if space.is_w(w_typetype, space.w_type): |
| 904 |
return space.type(w_name) |
| 905 |
else: |
| 906 |
raise oefmt(space.w_TypeError, |
| 907 |
"%N.__new__() takes exactly 3 arguments (1 given)", |
| 908 |
w_typetype) |
| 909 |
w_bases = __args__.arguments_w[1] |
| 910 |
w_dict = __args__.arguments_w[2] |
| 911 |
return _create_new_type(space, w_typetype, w_name, w_bases, w_dict, __args__) |
| 912 |
|
| 913 |
|
| 914 |
def _check_new_args(space, w_name, w_bases, w_dict): |
| 915 |
if not space.isinstance_w(w_name, space.w_text): |
| 916 |
raise oefmt(space.w_TypeError, |
| 917 |
"type() argument 1 must be string, not %T", w_name) |
| 918 |
if not space.isinstance_w(w_bases, space.w_tuple): |
| 919 |
raise oefmt(space.w_TypeError, |
| 920 |
"type() argument 2 must be tuple, not %T", w_bases) |
| 921 |
if not space.isinstance_w(w_dict, space.w_dict): |
| 922 |
raise oefmt(space.w_TypeError, |
| 923 |
"type() argument 3 must be dict, not %T", w_dict) |
| 924 |
|
| 925 |
|
| 926 |
def _create_new_type(space, w_typetype, w_name, w_bases, w_dict, __args__): |
| 927 |
if hasattr(space, 'is_fake_objspace'): |
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
return space.newlong(42) |
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
_check_new_args(space, w_name, w_bases, w_dict) |
| 936 |
bases_w = space.fixedview(w_bases) |
| 937 |
for w_base in bases_w: |
| 938 |
if space.lookup(w_base, '__mro_entries__') is not None: |
| 939 |
raise oefmt(space.w_TypeError, |
| 940 |
"type() doesn't support MRO entry resolution; " |
| 941 |
"use types.new_class()") |
| 942 |
|
| 943 |
w_winner = _calculate_metaclass(space, w_typetype, bases_w) |
| 944 |
if not space.is_w(w_winner, w_typetype): |
| 945 |
newfunc = space.getattr(w_winner, space.newtext('__new__')) |
| 946 |
if not space.is_w(newfunc, space.getattr(space.w_type, space.newtext('__new__'))): |
| 947 |
return space.call_obj_args(newfunc, w_winner, __args__) |
| 948 |
w_typetype = w_winner |
| 949 |
|
| 950 |
name = space.text_w(w_name) |
| 951 |
if '\x00' in name: |
| 952 |
raise oefmt(space.w_ValueError, "type name must not contain null characters") |
| 953 |
_check_surrogate(space, name) |
| 954 |
dict_w = {} |
| 955 |
dictkeys_w = space.listview(w_dict) |
| 956 |
for w_key in dictkeys_w: |
| 957 |
key = space.text_w(w_key) |
| 958 |
dict_w[key] = space.getitem(w_dict, w_key) |
| 959 |
w_type = space.allocate_instance(W_TypeObject, w_typetype) |
| 960 |
|
| 961 |
|
| 962 |
w_classcell = dict_w.get("__classcell__", None) |
| 963 |
if w_classcell: |
| 964 |
_store_type_in_classcell(space, w_type, w_classcell, dict_w) |
| 965 |
|
| 966 |
W_TypeObject.__init__(w_type, space, name, bases_w or [space.w_object], |
| 967 |
dict_w, is_heaptype=True) |
| 968 |
|
| 969 |
|
| 970 |
w_type.ready() |
| 971 |
|
| 972 |
_set_names(space, w_type) |
| 973 |
_init_subclass(space, w_type, __args__) |
| 974 |
return w_type |
| 975 |
|
| 976 |
def _store_type_in_classcell(space, w_type, w_classcell, dict_w): |
| 977 |
from pypy.interpreter.nestedscope import Cell |
| 978 |
if isinstance(w_classcell, Cell): |
| 979 |
w_classcell.set(w_type) |
| 980 |
else: |
| 981 |
raise oefmt(space.w_TypeError, |
| 982 |
"__classcell__ must be a nonlocal cell, not %T", |
| 983 |
w_classcell) |
| 984 |
del dict_w['__classcell__'] |
| 985 |
|
| 986 |
def _calculate_metaclass(space, w_metaclass, bases_w): |
| 987 |
"""Determine the most derived metatype""" |
| 988 |
w_winner = w_metaclass |
| 989 |
for base in bases_w: |
| 990 |
w_typ = space.type(base) |
| 991 |
if space.issubtype_w(w_winner, w_typ): |
| 992 |
continue |
| 993 |
if space.issubtype_w(w_typ, w_winner): |
| 994 |
w_winner = w_typ |
| 995 |
continue |
| 996 |
msg = ("metaclass conflict: the metaclass of a derived class must be " |
| 997 |
"a (non-strict) subclass of the metaclasses of all its bases") |
| 998 |
raise oefmt(space.w_TypeError, msg) |
| 999 |
return w_winner |
| 1000 |
|
| 1001 |
def _precheck_for_new(space, w_type): |
| 1002 |
if not isinstance(w_type, W_TypeObject): |
| 1003 |
raise oefmt(space.w_TypeError, "X is not a type object (%T)", w_type) |
| 1004 |
return w_type |
| 1005 |
|
| 1006 |
def _set_names(space, w_type): |
| 1007 |
|
| 1008 |
for key, w_value in w_type.dict_w.items(): |
| 1009 |
w_meth = space.lookup(w_value, '__set_name__') |
| 1010 |
if w_meth is not None: |
| 1011 |
try: |
| 1012 |
space.get_and_call_function(w_meth, w_value, w_type, space.newtext(key)) |
| 1013 |
except OperationError as e: |
| 1014 |
e2 = oefmt(space.w_RuntimeError, |
| 1015 |
"Error calling __set_name__ on '%T' instance '%s' in '%N'", |
| 1016 |
w_value, key, w_type) |
| 1017 |
e2.chain_exceptions_from_cause(space, e) |
| 1018 |
raise e2 |
| 1019 |
|
| 1020 |
def _init_subclass(space, w_type, __args__): |
| 1021 |
|
| 1022 |
w_super = space.getattr(space.builtin, space.newtext("super")) |
| 1023 |
w_func = space.getattr(space.call_function(w_super, w_type, w_type), |
| 1024 |
space.newtext("__init_subclass__")) |
| 1025 |
args = __args__.replace_arguments([]) |
| 1026 |
space.call_args(w_func, args) |
| 1027 |
|
| 1028 |
def descr__init__(space, w_type, __args__): |
| 1029 |
if len(__args__.arguments_w) not in (1, 3): |
| 1030 |
raise oefmt(space.w_TypeError, |
| 1031 |
"type.__init__() takes 1 or 3 arguments") |
| 1032 |
|
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
def _check(space, w_type, msg="descriptor is for 'type'"): |
| 1037 |
if not isinstance(w_type, W_TypeObject): |
| 1038 |
raise OperationError(space.w_TypeError, space.newtext(msg)) |
| 1039 |
return w_type |
| 1040 |
|
| 1041 |
|
| 1042 |
def descr_get__name__(space, w_type): |
| 1043 |
w_type = _check(space, w_type) |
| 1044 |
return space.newtext(w_type.getname(space)) |
| 1045 |
|
| 1046 |
def descr_set__name__(space, w_type, w_value): |
| 1047 |
w_type = _check(space, w_type) |
| 1048 |
if not w_type.is_heaptype(): |
| 1049 |
raise oefmt(space.w_TypeError, "can't set %N.__name__", w_type) |
| 1050 |
if not space.isinstance_w(w_value, space.w_text): |
| 1051 |
raise oefmt(space.w_TypeError, |
| 1052 |
"can only assign string to %N.__name__, not '%T'", |
| 1053 |
w_type, w_value) |
| 1054 |
name = space.text_w(w_value) |
| 1055 |
if '\x00' in name: |
| 1056 |
raise oefmt(space.w_ValueError, "type name must not contain null characters") |
| 1057 |
_check_surrogate(space, name) |
| 1058 |
w_type.name = name |
| 1059 |
|
| 1060 |
def descr_get__qualname__(space, w_type): |
| 1061 |
w_type = _check(space, w_type) |
| 1062 |
return space.newtext(w_type.getqualname(space)) |
| 1063 |
|
| 1064 |
def descr_set__qualname__(space, w_type, w_value): |
| 1065 |
w_type = _check(space, w_type) |
| 1066 |
if not w_type.is_heaptype(): |
| 1067 |
raise oefmt(space.w_TypeError, "can't set %N.__qualname__", w_type) |
| 1068 |
if not space.isinstance_w(w_value, space.w_text): |
| 1069 |
raise oefmt(space.w_TypeError, |
| 1070 |
"can only assign string to %N.__name__, not '%T'", |
| 1071 |
w_type, w_value) |
| 1072 |
w_type.qualname = space.utf8_w(w_value) |
| 1073 |
|
| 1074 |
def descr_get__mro__(space, w_type): |
| 1075 |
w_type = _check(space, w_type) |
| 1076 |
if w_type.hasmro: |
| 1077 |
return space.newtuple(w_type.mro_w) |
| 1078 |
else: |
| 1079 |
return space.w_None |
| 1080 |
|
| 1081 |
def descr_mro(space, w_type): |
| 1082 |
"""Return a type's method resolution order.""" |
| 1083 |
w_type = _check(space, w_type, "expected type") |
| 1084 |
return space.newlist(w_type.compute_default_mro()) |
| 1085 |
|
| 1086 |
def descr_get__bases__(space, w_type): |
| 1087 |
w_type = _check(space, w_type) |
| 1088 |
return space.newtuple(w_type.bases_w) |
| 1089 |
|
| 1090 |
def mro_subclasses(space, w_type, temp): |
| 1091 |
old_mro_w = w_type.mro_w |
| 1092 |
compute_mro(w_type) |
| 1093 |
temp.append((w_type, old_mro_w, w_type.mro_w)) |
| 1094 |
for w_sc in w_type.get_subclasses(): |
| 1095 |
assert isinstance(w_sc, W_TypeObject) |
| 1096 |
mro_subclasses(space, w_sc, temp) |
| 1097 |
|
| 1098 |
def descr_set__bases__(space, w_type, w_value): |
| 1099 |
|
| 1100 |
w_type = _check(space, w_type) |
| 1101 |
if not w_type.is_heaptype(): |
| 1102 |
raise oefmt(space.w_TypeError, "can't set %N.__bases__", w_type) |
| 1103 |
if not space.isinstance_w(w_value, space.w_tuple): |
| 1104 |
raise oefmt(space.w_TypeError, |
| 1105 |
"can only assign tuple to %N.__bases__, not %T", |
| 1106 |
w_type, w_value) |
| 1107 |
newbases_w = space.fixedview(w_value) |
| 1108 |
if len(newbases_w) == 0: |
| 1109 |
raise oefmt(space.w_TypeError, |
| 1110 |
"can only assign non-empty tuple to %N.__bases__, not ()", |
| 1111 |
w_type) |
| 1112 |
|
| 1113 |
for w_newbase in newbases_w: |
| 1114 |
if isinstance(w_newbase, W_TypeObject): |
| 1115 |
if w_type in w_newbase.compute_default_mro(): |
| 1116 |
raise oefmt(space.w_TypeError, |
| 1117 |
"a __bases__ item causes an inheritance cycle") |
| 1118 |
|
| 1119 |
w_oldbestbase = check_and_find_best_base(space, w_type.bases_w) |
| 1120 |
w_newbestbase = check_and_find_best_base(space, newbases_w) |
| 1121 |
oldlayout = w_oldbestbase.get_full_instance_layout() |
| 1122 |
newlayout = w_newbestbase.get_full_instance_layout() |
| 1123 |
|
| 1124 |
if oldlayout != newlayout: |
| 1125 |
raise oefmt(space.w_TypeError, |
| 1126 |
"__bases__ assignment: '%N' object layout differs from " |
| 1127 |
"'%N'", w_newbestbase, w_oldbestbase) |
| 1128 |
|
| 1129 |
|
| 1130 |
w_type.mutated(None) |
| 1131 |
|
| 1132 |
|
| 1133 |
saved_bases_w = w_type.bases_w |
| 1134 |
temp = [] |
| 1135 |
try: |
| 1136 |
for w_oldbase in saved_bases_w: |
| 1137 |
if isinstance(w_oldbase, W_TypeObject): |
| 1138 |
w_oldbase.remove_subclass(w_type) |
| 1139 |
w_type.bases_w = newbases_w |
| 1140 |
for w_newbase in newbases_w: |
| 1141 |
if isinstance(w_newbase, W_TypeObject): |
| 1142 |
w_newbase.add_subclass(w_type) |
| 1143 |
|
| 1144 |
mro_subclasses(space, w_type, temp) |
| 1145 |
except: |
| 1146 |
for cls, old_mro, new_mro in temp: |
| 1147 |
if cls.mro_w is new_mro: |
| 1148 |
cls.mro_w = old_mro |
| 1149 |
if w_type.bases_w is newbases_w: |
| 1150 |
w_type.bases_w = saved_bases_w |
| 1151 |
raise |
| 1152 |
if (w_type.version_tag() is not None and |
| 1153 |
not is_mro_purely_of_types(w_type.mro_w)): |
| 1154 |
|
| 1155 |
w_type._version_tag = None |
| 1156 |
for w_subclass in w_type.get_subclasses(): |
| 1157 |
if isinstance(w_subclass, W_TypeObject): |
| 1158 |
w_subclass._version_tag = None |
| 1159 |
if space.config.objspace.usemodules.cpyext and bool(w_type._cpyext_as_pyobj(space)): |
| 1160 |
|
| 1161 |
from pypy.module.cpyext.typeobject import type_reattach |
| 1162 |
type_reattach(space, w_type) |
| 1163 |
|
| 1164 |
def descr__base(space, w_type): |
| 1165 |
w_type = _check(space, w_type) |
| 1166 |
return find_best_base(w_type.bases_w) |
| 1167 |
|
| 1168 |
def descr__doc(space, w_type): |
| 1169 |
if space.is_w(w_type, space.w_type): |
| 1170 |
return space.newtext("""type(object) -> the object's type |
| 1171 |
type(name, bases, dict) -> a new type""") |
| 1172 |
w_type = _check(space, w_type) |
| 1173 |
if not w_type.is_heaptype(): |
| 1174 |
return w_type.w_doc |
| 1175 |
w_result = w_type.getdictvalue(space, '__doc__') |
| 1176 |
if w_result is None: |
| 1177 |
return space.w_None |
| 1178 |
else: |
| 1179 |
return space.get(w_result, space.w_None, w_type) |
| 1180 |
|
| 1181 |
def descr_set__doc(space, w_type, w_value): |
| 1182 |
w_type = _check(space, w_type) |
| 1183 |
if not w_type.is_heaptype(): |
| 1184 |
raise oefmt(space.w_TypeError, "cannot set '__doc__' attribute of immutable type '%N'", w_type) |
| 1185 |
w_type.setdictvalue(space, '__doc__', w_value) |
| 1186 |
|
| 1187 |
def undotted_name(name): |
| 1188 |
"""Return the last component of a dotted name""" |
| 1189 |
dotpos = name.rfind('.') |
| 1190 |
if dotpos < 0: |
| 1191 |
return name |
| 1192 |
else: |
| 1193 |
return name[dotpos + 1:] |
| 1194 |
|
| 1195 |
SIGNATURE_MARKER = ')\n--\n\n' |
| 1196 |
|
| 1197 |
def extract_doc(raw_doc, name): |
| 1198 |
doc = raw_doc |
| 1199 |
name = undotted_name(name) |
| 1200 |
if raw_doc.startswith(name + '('): |
| 1201 |
end_sig = raw_doc.find(SIGNATURE_MARKER) |
| 1202 |
if end_sig > 0: |
| 1203 |
doc = raw_doc[end_sig + len(SIGNATURE_MARKER):] |
| 1204 |
if not doc: |
| 1205 |
return None |
| 1206 |
return doc |
| 1207 |
|
| 1208 |
def extract_txtsig(raw_doc, name): |
| 1209 |
name = undotted_name(name) |
| 1210 |
if raw_doc.startswith(name + '('): |
| 1211 |
end_sig = raw_doc.find(SIGNATURE_MARKER) |
| 1212 |
if end_sig > 0: |
| 1213 |
|
| 1214 |
|
| 1215 |
|
| 1216 |
|
| 1217 |
return raw_doc[len(name): end_sig + 1] |
| 1218 |
return None |
| 1219 |
|
| 1220 |
def type_get_text_signature(space, w_type): |
| 1221 |
w_type = _check(space, w_type) |
| 1222 |
if w_type.text_signature: |
| 1223 |
return space.newtext(w_type.text_signature) |
| 1224 |
w_doc = descr__doc(space, w_type) |
| 1225 |
if space.is_none(w_doc): |
| 1226 |
return space.w_None |
| 1227 |
rawdoc = space.text_w(w_doc) |
| 1228 |
txtsig = extract_txtsig(rawdoc, w_type.name) |
| 1229 |
if txtsig is not None: |
| 1230 |
return space.newtext(txtsig) |
| 1231 |
return space.w_None |
| 1232 |
|
| 1233 |
def descr__dir(space, w_type): |
| 1234 |
from pypy.objspace.std.util import _classdir |
| 1235 |
return space.call_function(space.w_list, _classdir(space, w_type)) |
| 1236 |
|
| 1237 |
def descr__flags(space, w_type): |
| 1238 |
w_type = _check(space, w_type) |
| 1239 |
return space.newint(w_type.get_flags()) |
| 1240 |
|
| 1241 |
def descr_get__module(space, w_type): |
| 1242 |
w_type = _check(space, w_type) |
| 1243 |
return w_type.get_module() |
| 1244 |
|
| 1245 |
def descr_set__module(space, w_type, w_value): |
| 1246 |
w_type = _check(space, w_type) |
| 1247 |
w_type.setdictvalue(space, '__module__', w_value) |
| 1248 |
|
| 1249 |
def descr_get___abstractmethods__(space, w_type): |
| 1250 |
w_type = _check(space, w_type) |
| 1251 |
|
| 1252 |
if not space.is_w(w_type, space.w_type): |
| 1253 |
w_result = w_type.getdictvalue(space, "__abstractmethods__") |
| 1254 |
if w_result is not None: |
| 1255 |
return w_result |
| 1256 |
raise oefmt(space.w_AttributeError, "__abstractmethods__") |
| 1257 |
|
| 1258 |
def descr_set___abstractmethods__(space, w_type, w_new): |
| 1259 |
w_type = _check(space, w_type) |
| 1260 |
w_type.setdictvalue(space, "__abstractmethods__", w_new) |
| 1261 |
w_type.set_abstract(space.is_true(w_new)) |
| 1262 |
|
| 1263 |
def descr_del___abstractmethods__(space, w_type): |
| 1264 |
w_type = _check(space, w_type) |
| 1265 |
if not w_type.deldictvalue(space, "__abstractmethods__"): |
| 1266 |
raise oefmt(space.w_AttributeError, "__abstractmethods__") |
| 1267 |
w_type.set_abstract(False) |
| 1268 |
|
| 1269 |
def descr___subclasses__(space, w_type): |
| 1270 |
"""Return the list of immediate subclasses.""" |
| 1271 |
w_type = _check(space, w_type) |
| 1272 |
return space.newlist(w_type.get_subclasses(only_real_subclasses=True)) |
| 1273 |
|
| 1274 |
def descr___prepare__(space, __args__): |
| 1275 |
return space.newdict(module=True) |
| 1276 |
|
| 1277 |
|
| 1278 |
|
| 1279 |
@gateway.unwrap_spec(w_obj=W_TypeObject) |
| 1280 |
def type_issubtype(w_obj, space, w_sub): |
| 1281 |
return space.newbool( |
| 1282 |
abstractinst.p_recursive_issubclass_w(space, w_sub, w_obj)) |
| 1283 |
|
| 1284 |
@gateway.unwrap_spec(w_obj=W_TypeObject) |
| 1285 |
def type_isinstance(w_obj, space, w_inst): |
| 1286 |
return space.newbool( |
| 1287 |
abstractinst.p_recursive_isinstance_type_w(space, w_inst, w_obj)) |
| 1288 |
|
| 1289 |
def type_get_dict(space, w_cls): |
| 1290 |
w_cls = _check(space, w_cls) |
| 1291 |
from pypy.objspace.std.dictproxyobject import W_DictProxyObject |
| 1292 |
w_dict = w_cls.getdict(space) |
| 1293 |
if w_dict is None: |
| 1294 |
return space.w_None |
| 1295 |
return W_DictProxyObject(w_dict) |
| 1296 |
|
| 1297 |
W_TypeObject.typedef = TypeDef("type", |
| 1298 |
__new__ = gateway.interp2app(descr__new__), |
| 1299 |
__init__ = gateway.interp2app(descr__init__), |
| 1300 |
__name__ = GetSetProperty(descr_get__name__, descr_set__name__), |
| 1301 |
__qualname__ = GetSetProperty(descr_get__qualname__, descr_set__qualname__), |
| 1302 |
__bases__ = GetSetProperty(descr_get__bases__, descr_set__bases__), |
| 1303 |
__base__ = GetSetProperty(descr__base), |
| 1304 |
__mro__ = GetSetProperty(descr_get__mro__), |
| 1305 |
__dict__=GetSetProperty(type_get_dict), |
| 1306 |
__doc__ = GetSetProperty(descr__doc, descr_set__doc, cls=W_TypeObject, name='__doc__'), |
| 1307 |
__text_signature__=GetSetProperty(type_get_text_signature), |
| 1308 |
__dir__ = gateway.interp2app(descr__dir), |
| 1309 |
mro = gateway.interp2app(descr_mro), |
| 1310 |
__flags__ = GetSetProperty(descr__flags), |
| 1311 |
__module__ = GetSetProperty(descr_get__module, descr_set__module), |
| 1312 |
__abstractmethods__ = GetSetProperty(descr_get___abstractmethods__, |
| 1313 |
descr_set___abstractmethods__, |
| 1314 |
descr_del___abstractmethods__), |
| 1315 |
__subclasses__ = gateway.interp2app(descr___subclasses__), |
| 1316 |
__weakref__ = weakref_descr, |
| 1317 |
__instancecheck__ = gateway.interp2app(type_isinstance), |
| 1318 |
__subclasscheck__ = gateway.interp2app(type_issubtype), |
| 1319 |
|
| 1320 |
__call__ = gateway.interp2app(W_TypeObject.descr_call), |
| 1321 |
__repr__ = gateway.interp2app(W_TypeObject.descr_repr), |
| 1322 |
__getattribute__ = gateway.interp2app(W_TypeObject.descr_getattribute), |
| 1323 |
__prepare__ = gateway.interp2app(descr___prepare__, as_classmethod=True), |
| 1324 |
__or__ = gateway.interp2app(W_TypeObject.descr_or), |
| 1325 |
__ror__ = gateway.interp2app(W_TypeObject.descr_ror), |
| 1326 |
__annotations__ = GetSetProperty(W_TypeObject.descr_get_annotations, |
| 1327 |
W_TypeObject.descr_set_annotations, |
| 1328 |
W_TypeObject.descr_del_annotations), |
| 1329 |
) |
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
def find_best_base(bases_w): |
| 1336 |
"""The best base is one of the bases in the given list: the one |
| 1337 |
whose layout a new type should use as a starting point. |
| 1338 |
""" |
| 1339 |
w_bestbase = None |
| 1340 |
for w_candidate in bases_w: |
| 1341 |
if not isinstance(w_candidate, W_TypeObject): |
| 1342 |
continue |
| 1343 |
if not w_candidate.hasmro: |
| 1344 |
raise oefmt(w_candidate.space.w_TypeError, |
| 1345 |
"Cannot extend an incomplete type '%N'", w_candidate) |
| 1346 |
if w_bestbase is None: |
| 1347 |
w_bestbase = w_candidate |
| 1348 |
continue |
| 1349 |
cand_layout = w_candidate.layout |
| 1350 |
best_layout = w_bestbase.layout |
| 1351 |
if (cand_layout is not best_layout and |
| 1352 |
cand_layout.issublayout(best_layout)): |
| 1353 |
w_bestbase = w_candidate |
| 1354 |
return w_bestbase |
| 1355 |
|
| 1356 |
def check_and_find_best_base(space, bases_w, is_cpytype=False): |
| 1357 |
"""The best base is one of the bases in the given list: the one |
| 1358 |
whose layout a new type should use as a starting point. |
| 1359 |
This version checks that bases_w is an acceptable tuple of bases. |
| 1360 |
""" |
| 1361 |
w_bestbase = find_best_base(bases_w) |
| 1362 |
if w_bestbase is None: |
| 1363 |
raise oefmt(space.w_TypeError, |
| 1364 |
"a new-style class can't have only classic bases") |
| 1365 |
if (not (is_cpytype and w_bestbase.is_cpytype()) and |
| 1366 |
not w_bestbase.acceptable_as_base_class(space)): |
| 1367 |
|
| 1368 |
raise oefmt(space.w_TypeError, |
| 1369 |
"type '%s' is not an acceptable base type", w_bestbase.name) |
| 1370 |
|
| 1371 |
|
| 1372 |
|
| 1373 |
best_layout = w_bestbase.layout |
| 1374 |
for w_base in bases_w: |
| 1375 |
if isinstance(w_base, W_TypeObject): |
| 1376 |
layout = w_base.layout |
| 1377 |
if not best_layout.issublayout(layout): |
| 1378 |
if _layouts_equivalent(best_layout, layout) and ( |
| 1379 |
is_cpytype or |
| 1380 |
(w_base.is_cpytype() and w_bestbase.is_cpytype())): |
| 1381 |
continue |
| 1382 |
raise oefmt(space.w_TypeError, |
| 1383 |
"instance layout conflicts in multiple inheritance") |
| 1384 |
return w_bestbase |
| 1385 |
|
| 1386 |
def _layouts_equivalent(l1, l2): |
| 1387 |
"""Return True if two Layout objects are structurally identical - same |
| 1388 |
typedef, nslots, slot names, and base chain - but are different Python |
| 1389 |
objects because force_new_layout created them independently. |
| 1390 |
|
| 1391 |
Used to allow multiple inheritance between two cpytypes that have the same |
| 1392 |
tp_basicsize/tp_itemsize. CPython's solid_base() logic permits |
| 1393 |
this combination because both types share the same solid ancestor.""" |
| 1394 |
return (l1.typedef is l2.typedef and |
| 1395 |
l1.nslots == l2.nslots and |
| 1396 |
l1.newslotnames == l2.newslotnames and |
| 1397 |
l1.base_layout is l2.base_layout) |
| 1398 |
|
| 1399 |
def copy_flags_from_bases(w_self, w_bestbase): |
| 1400 |
hasoldstylebase = False |
| 1401 |
for w_base in w_self.bases_w: |
| 1402 |
if not isinstance(w_base, W_TypeObject): |
| 1403 |
hasoldstylebase = True |
| 1404 |
continue |
| 1405 |
w_self.hasdict = w_self.hasdict or w_base.hasdict |
| 1406 |
w_self.hasuserdel = w_self.hasuserdel or w_base.hasuserdel |
| 1407 |
w_self.weakrefable = w_self.weakrefable or w_base.weakrefable |
| 1408 |
if w_self.flag_patma_collection == "X": |
| 1409 |
w_self.flag_patma_collection = w_base.flag_patma_collection |
| 1410 |
return hasoldstylebase |
| 1411 |
|
| 1412 |
def slot_w(space, w_name): |
| 1413 |
from pypy.objspace.std.unicodeobject import _isidentifier |
| 1414 |
if not space.isinstance_w(w_name, space.w_text): |
| 1415 |
raise oefmt(space.w_TypeError, |
| 1416 |
"__slots__ items must be strings, not '%T'", w_name) |
| 1417 |
s = space.utf8_w(w_name) |
| 1418 |
if not _isidentifier(s): |
| 1419 |
raise oefmt(space.w_TypeError, "__slots__ must be identifiers") |
| 1420 |
return s |
| 1421 |
|
| 1422 |
def create_all_slots(w_self, hasoldstylebase, w_bestbase, force_new_layout): |
| 1423 |
from pypy.interpreter.miscutils import string_sort |
| 1424 |
|
| 1425 |
base_layout = w_bestbase.layout |
| 1426 |
index_next_extra_slot = base_layout.nslots |
| 1427 |
space = w_self.space |
| 1428 |
dict_w = w_self.dict_w |
| 1429 |
newslotnames = [] |
| 1430 |
if '__slots__' not in dict_w: |
| 1431 |
wantdict = True |
| 1432 |
wantweakref = True |
| 1433 |
else: |
| 1434 |
wantdict = False |
| 1435 |
wantweakref = False |
| 1436 |
w_slots = dict_w['__slots__'] |
| 1437 |
if space.isinstance_w(w_slots, space.w_text): |
| 1438 |
slot_names_w = [w_slots] |
| 1439 |
else: |
| 1440 |
slot_names_w = space.unpackiterable(w_slots) |
| 1441 |
for w_slot_name in slot_names_w: |
| 1442 |
slot_name = slot_w(space, w_slot_name) |
| 1443 |
if slot_name == '__dict__': |
| 1444 |
if wantdict or w_bestbase.hasdict: |
| 1445 |
raise oefmt(space.w_TypeError, |
| 1446 |
"__dict__ slot disallowed: we already got one") |
| 1447 |
wantdict = True |
| 1448 |
elif slot_name == '__weakref__': |
| 1449 |
if wantweakref or w_bestbase.weakrefable: |
| 1450 |
raise oefmt(space.w_TypeError, |
| 1451 |
"__weakref__ slot disallowed: we already got one") |
| 1452 |
wantweakref = True |
| 1453 |
else: |
| 1454 |
newslotnames.append(slot_name) |
| 1455 |
|
| 1456 |
string_sort(newslotnames) |
| 1457 |
|
| 1458 |
|
| 1459 |
|
| 1460 |
|
| 1461 |
i = 0 |
| 1462 |
while i < len(newslotnames): |
| 1463 |
if create_slot(w_self, newslotnames[i], index_next_extra_slot): |
| 1464 |
index_next_extra_slot += 1 |
| 1465 |
i += 1 |
| 1466 |
else: |
| 1467 |
del newslotnames[i] |
| 1468 |
|
| 1469 |
wantdict = wantdict or hasoldstylebase |
| 1470 |
if wantdict: |
| 1471 |
create_dict_slot(w_self) |
| 1472 |
if wantweakref: |
| 1473 |
create_weakref_slot(w_self) |
| 1474 |
if '__del__' in dict_w: |
| 1475 |
w_self.hasuserdel = True |
| 1476 |
|
| 1477 |
assert index_next_extra_slot == base_layout.nslots + len(newslotnames) |
| 1478 |
if index_next_extra_slot == base_layout.nslots and not force_new_layout: |
| 1479 |
return base_layout |
| 1480 |
else: |
| 1481 |
return Layout(base_layout.typedef, index_next_extra_slot, |
| 1482 |
newslotnames, base_layout=base_layout) |
| 1483 |
|
| 1484 |
def create_slot(w_self, slot_name, index_next_extra_slot): |
| 1485 |
space = w_self.space |
| 1486 |
|
| 1487 |
slot_name = mangle(slot_name, w_self.name) |
| 1488 |
if slot_name not in w_self.dict_w: |
| 1489 |
|
| 1490 |
slot_name = space.text_w(space.new_interned_str(slot_name)) |
| 1491 |
|
| 1492 |
member = Member(index_next_extra_slot, slot_name, w_self) |
| 1493 |
w_self.dict_w[slot_name] = member |
| 1494 |
return True |
| 1495 |
else: |
| 1496 |
w_prev = w_self.dict_w[slot_name] |
| 1497 |
if isinstance(w_prev, Member) and w_prev.w_cls is w_self: |
| 1498 |
return False |
| 1499 |
|
| 1500 |
raise oefmt(space.w_ValueError, |
| 1501 |
"'%8' in __slots__ conflicts with class variable", |
| 1502 |
slot_name) |
| 1503 |
|
| 1504 |
def create_dict_slot(w_self): |
| 1505 |
if not w_self.hasdict: |
| 1506 |
descr = dict_descr.copy_for_type(w_self) |
| 1507 |
w_self.dict_w.setdefault('__dict__', descr) |
| 1508 |
w_self.hasdict = True |
| 1509 |
|
| 1510 |
def create_weakref_slot(w_self): |
| 1511 |
if not w_self.weakrefable: |
| 1512 |
descr = weakref_descr.copy_for_type(w_self) |
| 1513 |
w_self.dict_w.setdefault('__weakref__', descr) |
| 1514 |
w_self.weakrefable = True |
| 1515 |
|
| 1516 |
def setup_user_defined_type(w_self, force_new_layout): |
| 1517 |
if len(w_self.bases_w) == 0: |
| 1518 |
w_self.bases_w = [w_self.space.w_object] |
| 1519 |
w_bestbase = check_and_find_best_base(w_self.space, w_self.bases_w, w_self.is_cpytype()) |
| 1520 |
for w_base in w_self.bases_w: |
| 1521 |
if not isinstance(w_base, W_TypeObject): |
| 1522 |
continue |
| 1523 |
w_self.flag_cpytype |= w_base.flag_cpytype |
| 1524 |
if w_self.flag_map_or_seq == '?': |
| 1525 |
w_self.flag_map_or_seq = w_base.flag_map_or_seq |
| 1526 |
|
| 1527 |
hasoldstylebase = copy_flags_from_bases(w_self, w_bestbase) |
| 1528 |
layout = create_all_slots(w_self, hasoldstylebase, w_bestbase, |
| 1529 |
force_new_layout) |
| 1530 |
|
| 1531 |
ensure_common_attributes(w_self) |
| 1532 |
return layout |
| 1533 |
|
| 1534 |
def setup_builtin_type(w_self, instancetypedef): |
| 1535 |
w_self.hasdict = instancetypedef.hasdict |
| 1536 |
w_self.weakrefable = instancetypedef.weakrefable |
| 1537 |
w_self.w_doc = w_self.space.newtext_or_none(instancetypedef.doc) |
| 1538 |
w_self.text_signature = instancetypedef.text_signature |
| 1539 |
ensure_common_attributes(w_self) |
| 1540 |
|
| 1541 |
|
| 1542 |
|
| 1543 |
w_bestbase = find_best_base(w_self.bases_w) |
| 1544 |
if w_bestbase is None: |
| 1545 |
parent_layout = None |
| 1546 |
else: |
| 1547 |
parent_layout = w_bestbase.layout |
| 1548 |
if parent_layout.typedef is instancetypedef: |
| 1549 |
return parent_layout |
| 1550 |
return Layout(instancetypedef, 0, base_layout=parent_layout) |
| 1551 |
|
| 1552 |
def ensure_common_attributes(w_self): |
| 1553 |
ensure_static_new(w_self) |
| 1554 |
w_self.dict_w.setdefault('__doc__', w_self.w_doc) |
| 1555 |
if w_self.is_heaptype(): |
| 1556 |
ensure_module_attr(w_self) |
| 1557 |
ensure_hash(w_self) |
| 1558 |
w_self.mro_w = [] |
| 1559 |
w_self.hasmro = False |
| 1560 |
compute_mro(w_self) |
| 1561 |
ensure_classmethods(w_self, ['__init_subclass__', '__class_getitem__']) |
| 1562 |
|
| 1563 |
def ensure_static_new(w_self): |
| 1564 |
|
| 1565 |
|
| 1566 |
if '__new__' in w_self.dict_w: |
| 1567 |
w_new = w_self.dict_w['__new__'] |
| 1568 |
if isinstance(w_new, Function): |
| 1569 |
w_self.dict_w['__new__'] = StaticMethod(w_new) |
| 1570 |
|
| 1571 |
def ensure_classmethods(w_self, method_names): |
| 1572 |
for method_name in method_names: |
| 1573 |
if method_name in w_self.dict_w: |
| 1574 |
w_method = w_self.dict_w[method_name] |
| 1575 |
if isinstance(w_method, Function): |
| 1576 |
w_self.dict_w[method_name] = ClassMethod(w_method) |
| 1577 |
|
| 1578 |
def ensure_module_attr(w_self): |
| 1579 |
|
| 1580 |
if '__module__' not in w_self.dict_w: |
| 1581 |
space = w_self.space |
| 1582 |
caller = space.getexecutioncontext().gettopframe_nohidden() |
| 1583 |
if caller is not None: |
| 1584 |
w_globals = caller.get_w_globals() |
| 1585 |
w_name = space.finditem(w_globals, space.newtext('__name__')) |
| 1586 |
if w_name is not None: |
| 1587 |
w_self.dict_w['__module__'] = w_name |
| 1588 |
|
| 1589 |
def ensure_hash(w_self): |
| 1590 |
|
| 1591 |
|
| 1592 |
if '__eq__' in w_self.dict_w and '__hash__' not in w_self.dict_w: |
| 1593 |
w_self.dict_w['__hash__'] = w_self.space.w_None |
| 1594 |
|
| 1595 |
def compute_mro(w_self): |
| 1596 |
default_mro_w = w_self.compute_default_mro()[:] |
| 1597 |
if w_self.is_heaptype(): |
| 1598 |
space = w_self.space |
| 1599 |
w_metaclass = space.type(w_self) |
| 1600 |
w_where, w_mro_func = space.lookup_in_type_where(w_metaclass, 'mro') |
| 1601 |
if w_mro_func is not None and not space.is_w(w_where, space.w_type): |
| 1602 |
w_mro_meth = space.get(w_mro_func, w_self) |
| 1603 |
w_mro = space.call_function(w_mro_meth) |
| 1604 |
mro_w = space.fixedview(w_mro) |
| 1605 |
w_self.mro_w = validate_custom_mro(space, mro_w) |
| 1606 |
_add_mro_classes_as_subclasses(space, w_self, w_self.mro_w, default_mro_w) |
| 1607 |
w_self.hasmro = True |
| 1608 |
return |
| 1609 |
w_self.mro_w = default_mro_w |
| 1610 |
w_self.hasmro = True |
| 1611 |
|
| 1612 |
def validate_custom_mro(space, mro_w): |
| 1613 |
|
| 1614 |
|
| 1615 |
|
| 1616 |
for w_class in mro_w: |
| 1617 |
if not space.abstract_isclass_w(w_class): |
| 1618 |
raise oefmt(space.w_TypeError, "mro() returned a non-class") |
| 1619 |
return mro_w |
| 1620 |
|
| 1621 |
def _add_mro_classes_as_subclasses(space, w_self, mro_w, default_mro_w): |
| 1622 |
|
| 1623 |
|
| 1624 |
|
| 1625 |
|
| 1626 |
|
| 1627 |
for w_ancestor in mro_w: |
| 1628 |
if w_ancestor not in default_mro_w: |
| 1629 |
if isinstance(w_ancestor, W_TypeObject): |
| 1630 |
w_ancestor.add_subclass(w_self) |
| 1631 |
|
| 1632 |
def is_mro_purely_of_types(mro_w): |
| 1633 |
for w_class in mro_w: |
| 1634 |
if not isinstance(w_class, W_TypeObject): |
| 1635 |
return False |
| 1636 |
return True |
| 1637 |
|
| 1638 |
|
| 1639 |
|
| 1640 |
def _issubtype(w_sub, w_type): |
| 1641 |
if w_sub.hasmro: |
| 1642 |
return w_type in w_sub.mro_w |
| 1643 |
else: |
| 1644 |
return _issubtype_slow_and_wrong(w_sub, w_type) |
| 1645 |
|
| 1646 |
def _issubtype_slow_and_wrong(w_sub, w_type): |
| 1647 |
|
| 1648 |
|
| 1649 |
|
| 1650 |
w_cls = w_sub |
| 1651 |
while w_cls: |
| 1652 |
if w_cls is w_type: |
| 1653 |
return True |
| 1654 |
w_cls = find_best_base(w_cls.bases_w) |
| 1655 |
return False |
| 1656 |
|
| 1657 |
@elidable_promote() |
| 1658 |
def _pure_issubtype(w_sub, w_type, version_tag1, version_tag2): |
| 1659 |
return _issubtype(w_sub, w_type) |
| 1660 |
|
| 1661 |
|
| 1662 |
|
| 1663 |
|
| 1664 |
|
| 1665 |
abstract_mro = gateway.applevel(""" |
| 1666 |
def abstract_mro(klass): |
| 1667 |
# abstract/classic mro |
| 1668 |
mro = [] |
| 1669 |
stack = [klass] |
| 1670 |
while stack: |
| 1671 |
klass = stack.pop() |
| 1672 |
if klass not in mro: |
| 1673 |
mro.append(klass) |
| 1674 |
if not isinstance(klass.__bases__, tuple): |
| 1675 |
raise TypeError('__bases__ must be a tuple') |
| 1676 |
stack += klass.__bases__[::-1] |
| 1677 |
return mro |
| 1678 |
""", filename=__file__).interphook("abstract_mro") |
| 1679 |
|
| 1680 |
def get_mro(space, klass): |
| 1681 |
if isinstance(klass, W_TypeObject): |
| 1682 |
return list(klass.mro_w) |
| 1683 |
else: |
| 1684 |
return space.unpackiterable(abstract_mro(space, klass)) |
| 1685 |
|
| 1686 |
|
| 1687 |
def compute_C3_mro(space, cls): |
| 1688 |
order = [] |
| 1689 |
orderlists = [get_mro(space, base) for base in cls.bases_w] |
| 1690 |
orderlists.append([cls] + cls.bases_w) |
| 1691 |
while orderlists: |
| 1692 |
for candidatelist in orderlists: |
| 1693 |
candidate = candidatelist[0] |
| 1694 |
if mro_blockinglist(candidate, orderlists) is None: |
| 1695 |
break |
| 1696 |
else: |
| 1697 |
return mro_error(space, orderlists) |
| 1698 |
assert candidate not in order |
| 1699 |
order.append(candidate) |
| 1700 |
for i in range(len(orderlists) - 1, -1, -1): |
| 1701 |
if orderlists[i][0] is candidate: |
| 1702 |
del orderlists[i][0] |
| 1703 |
if len(orderlists[i]) == 0: |
| 1704 |
del orderlists[i] |
| 1705 |
return order |
| 1706 |
|
| 1707 |
|
| 1708 |
def mro_blockinglist(candidate, orderlists): |
| 1709 |
for lst in orderlists: |
| 1710 |
if candidate in lst[1:]: |
| 1711 |
return lst |
| 1712 |
return None |
| 1713 |
|
| 1714 |
def mro_error(space, orderlists): |
| 1715 |
cycle = [] |
| 1716 |
candidate = orderlists[-1][0] |
| 1717 |
if candidate in orderlists[-1][1:]: |
| 1718 |
|
| 1719 |
raise oefmt(space.w_TypeError, "duplicate base class '%N'", candidate) |
| 1720 |
while candidate not in cycle: |
| 1721 |
cycle.append(candidate) |
| 1722 |
nextblockinglist = mro_blockinglist(candidate, orderlists) |
| 1723 |
candidate = nextblockinglist[0] |
| 1724 |
del cycle[:cycle.index(candidate)] |
| 1725 |
cycle.append(candidate) |
| 1726 |
cycle.reverse() |
| 1727 |
names = [cls.getname(space) for cls in cycle] |
| 1728 |
|
| 1729 |
raise OperationError(space.w_TypeError, space.newtext( |
| 1730 |
"cycle among base classes: " + ' < '.join(names))) |
| 1731 |
|
| 1732 |
|
| 1733 |
class TypeCache(SpaceCache): |
| 1734 |
@not_rpython |
| 1735 |
def build(self, typedef): |
| 1736 |
"initialization-time only." |
| 1737 |
from pypy.objspace.std.objectobject import W_ObjectObject |
| 1738 |
from pypy.interpreter.typedef import GetSetProperty |
| 1739 |
from rpython.rlib.objectmodel import instantiate |
| 1740 |
|
| 1741 |
space = self.space |
| 1742 |
rawdict = typedef.rawdict |
| 1743 |
lazyloaders = {} |
| 1744 |
w_type = instantiate(W_TypeObject) |
| 1745 |
|
| 1746 |
|
| 1747 |
if typedef is W_ObjectObject.typedef: |
| 1748 |
bases_w = [] |
| 1749 |
else: |
| 1750 |
bases = typedef.bases or [W_ObjectObject.typedef] |
| 1751 |
bases_w = [space.gettypeobject(base) for base in bases] |
| 1752 |
|
| 1753 |
|
| 1754 |
dict_w = {} |
| 1755 |
for descrname, descrvalue in rawdict.items(): |
| 1756 |
|
| 1757 |
if isinstance(descrvalue, GetSetProperty): |
| 1758 |
descrvalue = descrvalue.copy_for_type(w_type) |
| 1759 |
dict_w[descrname] = space.wrap(descrvalue) |
| 1760 |
|
| 1761 |
if typedef.applevel_subclasses_base is not None: |
| 1762 |
overridetypedef = typedef.applevel_subclasses_base.typedef |
| 1763 |
else: |
| 1764 |
overridetypedef = typedef |
| 1765 |
w_type.__init__(space, typedef.name, bases_w, dict_w, |
| 1766 |
overridetypedef=overridetypedef, |
| 1767 |
is_heaptype=overridetypedef.heaptype) |
| 1768 |
if typedef is not overridetypedef: |
| 1769 |
w_type.w_doc = space.newtext_or_none(typedef.doc) |
| 1770 |
else: |
| 1771 |
|
| 1772 |
for name in rawdict: |
| 1773 |
w_obj = dict_w[name] |
| 1774 |
if isinstance(w_obj, ClassMethod): |
| 1775 |
w_obj = w_obj.w_function |
| 1776 |
if isinstance(w_obj, StaticMethod): |
| 1777 |
w_obj = w_obj.w_function |
| 1778 |
if isinstance(w_obj, FunctionWithFixedCode): |
| 1779 |
qualname = (w_type.getqualname(space).encode('utf-8') |
| 1780 |
+ '.' + name) |
| 1781 |
w_obj.set_qualname(qualname) |
| 1782 |
w_obj.set_objclass(w_type) |
| 1783 |
|
| 1784 |
if hasattr(typedef, 'flag_sequence_bug_compat'): |
| 1785 |
w_type.flag_sequence_bug_compat = typedef.flag_sequence_bug_compat |
| 1786 |
w_type.lazyloaders = lazyloaders |
| 1787 |
return w_type |
| 1788 |
|
| 1789 |
def ready(self, w_type): |
| 1790 |
w_type.ready() |