Line data Source code
1 : /* Type object implementation */
2 :
3 : #include "Python.h"
4 : #include "frameobject.h"
5 : #include "structmember.h"
6 :
7 : #include <ctype.h>
8 :
9 :
10 : /* Support type attribute cache */
11 :
12 : /* The cache can keep references to the names alive for longer than
13 : they normally would. This is why the maximum size is limited to
14 : MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 : strings are used as attribute names. */
16 : #define MCACHE_MAX_ATTR_SIZE 100
17 : #define MCACHE_SIZE_EXP 9
18 : #define MCACHE_HASH(version, name_hash) \
19 : (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 : >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
21 : #define MCACHE_HASH_METHOD(type, name) \
22 : MCACHE_HASH((type)->tp_version_tag, \
23 : ((PyASCIIObject *)(name))->hash)
24 : #define MCACHE_CACHEABLE_NAME(name) \
25 : PyUnicode_CheckExact(name) && \
26 : PyUnicode_READY(name) != -1 && \
27 : PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
28 :
29 : struct method_cache_entry {
30 : unsigned int version;
31 : PyObject *name; /* reference to exactly a str or None */
32 : PyObject *value; /* borrowed */
33 : };
34 :
35 : static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
36 : static unsigned int next_version_tag = 0;
37 :
38 : _Py_IDENTIFIER(__class__);
39 : _Py_IDENTIFIER(__dict__);
40 : _Py_IDENTIFIER(__doc__);
41 : _Py_IDENTIFIER(__getitem__);
42 : _Py_IDENTIFIER(__getattribute__);
43 : _Py_IDENTIFIER(__hash__);
44 : _Py_IDENTIFIER(__module__);
45 : _Py_IDENTIFIER(__name__);
46 : _Py_IDENTIFIER(__new__);
47 :
48 : static PyObject *
49 : _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name);
50 :
51 : static PyObject *
52 : slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
53 :
54 : unsigned int
55 0 : PyType_ClearCache(void)
56 : {
57 : Py_ssize_t i;
58 0 : unsigned int cur_version_tag = next_version_tag - 1;
59 :
60 0 : for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
61 0 : method_cache[i].version = 0;
62 0 : Py_CLEAR(method_cache[i].name);
63 0 : method_cache[i].value = NULL;
64 : }
65 0 : next_version_tag = 0;
66 : /* mark all version tags as invalid */
67 0 : PyType_Modified(&PyBaseObject_Type);
68 0 : return cur_version_tag;
69 : }
70 :
71 : void
72 750 : PyType_Modified(PyTypeObject *type)
73 : {
74 : /* Invalidate any cached data for the specified type and all
75 : subclasses. This function is called after the base
76 : classes, mro, or attributes of the type are altered.
77 :
78 : Invariants:
79 :
80 : - Py_TPFLAGS_VALID_VERSION_TAG is never set if
81 : Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
82 : objects coming from non-recompiled extension modules)
83 :
84 : - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
85 : it must first be set on all super types.
86 :
87 : This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
88 : type (so it must first clear it on all subclasses). The
89 : tp_version_tag value is meaningless unless this flag is set.
90 : We don't assign new version tags eagerly, but only as
91 : needed.
92 : */
93 : PyObject *raw, *ref;
94 : Py_ssize_t i, n;
95 :
96 750 : if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
97 1361 : return;
98 :
99 139 : raw = type->tp_subclasses;
100 139 : if (raw != NULL) {
101 0 : n = PyList_GET_SIZE(raw);
102 0 : for (i = 0; i < n; i++) {
103 0 : ref = PyList_GET_ITEM(raw, i);
104 0 : ref = PyWeakref_GET_OBJECT(ref);
105 0 : if (ref != Py_None) {
106 0 : PyType_Modified((PyTypeObject *)ref);
107 : }
108 : }
109 : }
110 139 : type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
111 : }
112 :
113 : static void
114 874 : type_mro_modified(PyTypeObject *type, PyObject *bases) {
115 : /*
116 : Check that all base classes or elements of the MRO of type are
117 : able to be cached. This function is called after the base
118 : classes or mro of the type are altered.
119 :
120 : Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
121 : has a custom MRO that includes a type which is not officially
122 : super type.
123 :
124 : Called from mro_internal, which will subsequently be called on
125 : each subclass when their mro is recursively updated.
126 : */
127 : Py_ssize_t i, n;
128 874 : int clear = 0;
129 :
130 874 : if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
131 876 : return;
132 :
133 872 : n = PyTuple_GET_SIZE(bases);
134 2822 : for (i = 0; i < n; i++) {
135 1950 : PyObject *b = PyTuple_GET_ITEM(bases, i);
136 : PyTypeObject *cls;
137 :
138 : assert(PyType_Check(b));
139 1950 : cls = (PyTypeObject *)b;
140 :
141 3900 : if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
142 1950 : !PyType_IsSubtype(type, cls)) {
143 0 : clear = 1;
144 0 : break;
145 : }
146 : }
147 :
148 872 : if (clear)
149 0 : type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
150 : Py_TPFLAGS_VALID_VERSION_TAG);
151 : }
152 :
153 : static int
154 24100 : assign_version_tag(PyTypeObject *type)
155 : {
156 : /* Ensure that the tp_version_tag is valid and set
157 : Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
158 : must first be done on all super classes. Return 0 if this
159 : cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
160 : */
161 : Py_ssize_t i, n;
162 : PyObject *bases;
163 :
164 24100 : if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
165 23681 : return 1;
166 419 : if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
167 0 : return 0;
168 419 : if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
169 0 : return 0;
170 :
171 419 : type->tp_version_tag = next_version_tag++;
172 : /* for stress-testing: next_version_tag &= 0xFF; */
173 :
174 419 : if (type->tp_version_tag == 0) {
175 : /* wrap-around or just starting Python - clear the whole
176 : cache by filling names with references to Py_None.
177 : Values are also set to NULL for added protection, as they
178 : are borrowed reference */
179 513 : for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
180 512 : method_cache[i].value = NULL;
181 512 : Py_XDECREF(method_cache[i].name);
182 512 : method_cache[i].name = Py_None;
183 512 : Py_INCREF(Py_None);
184 : }
185 : /* mark all version tags as invalid */
186 1 : PyType_Modified(&PyBaseObject_Type);
187 1 : return 1;
188 : }
189 418 : bases = type->tp_bases;
190 418 : n = PyTuple_GET_SIZE(bases);
191 889 : for (i = 0; i < n; i++) {
192 471 : PyObject *b = PyTuple_GET_ITEM(bases, i);
193 : assert(PyType_Check(b));
194 471 : if (!assign_version_tag((PyTypeObject *)b))
195 0 : return 0;
196 : }
197 418 : type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
198 418 : return 1;
199 : }
200 :
201 :
202 : static PyMemberDef type_members[] = {
203 : {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
204 : {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
205 : {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
206 : {"__weakrefoffset__", T_LONG,
207 : offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
208 : {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
209 : {"__dictoffset__", T_LONG,
210 : offsetof(PyTypeObject, tp_dictoffset), READONLY},
211 : {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
212 : {0}
213 : };
214 :
215 : static int
216 3 : check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
217 : {
218 3 : if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
219 0 : PyErr_Format(PyExc_TypeError,
220 : "can't set %s.%s", type->tp_name, name);
221 0 : return 0;
222 : }
223 3 : if (!value) {
224 0 : PyErr_Format(PyExc_TypeError,
225 : "can't delete %s.%s", type->tp_name, name);
226 0 : return 0;
227 : }
228 3 : return 1;
229 : }
230 :
231 : static PyObject *
232 1890 : type_name(PyTypeObject *type, void *context)
233 : {
234 : const char *s;
235 :
236 1890 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
237 0 : PyHeapTypeObject* et = (PyHeapTypeObject*)type;
238 :
239 0 : Py_INCREF(et->ht_name);
240 0 : return et->ht_name;
241 : }
242 : else {
243 1890 : s = strrchr(type->tp_name, '.');
244 1890 : if (s == NULL)
245 0 : s = type->tp_name;
246 : else
247 1890 : s++;
248 1890 : return PyUnicode_FromString(s);
249 : }
250 : }
251 :
252 : static PyObject *
253 1890 : type_qualname(PyTypeObject *type, void *context)
254 : {
255 1890 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
256 0 : PyHeapTypeObject* et = (PyHeapTypeObject*)type;
257 0 : Py_INCREF(et->ht_qualname);
258 0 : return et->ht_qualname;
259 : }
260 : else {
261 1890 : return type_name(type, context);
262 : }
263 : }
264 :
265 : static int
266 0 : type_set_name(PyTypeObject *type, PyObject *value, void *context)
267 : {
268 : PyHeapTypeObject* et;
269 : char *tp_name;
270 : PyObject *tmp;
271 :
272 0 : if (!check_set_special_type_attr(type, value, "__name__"))
273 0 : return -1;
274 0 : if (!PyUnicode_Check(value)) {
275 0 : PyErr_Format(PyExc_TypeError,
276 : "can only assign string to %s.__name__, not '%s'",
277 0 : type->tp_name, Py_TYPE(value)->tp_name);
278 0 : return -1;
279 : }
280 :
281 : /* Check absence of null characters */
282 0 : tmp = PyUnicode_FromStringAndSize("\0", 1);
283 0 : if (tmp == NULL)
284 0 : return -1;
285 0 : if (PyUnicode_Contains(value, tmp) != 0) {
286 0 : Py_DECREF(tmp);
287 0 : PyErr_Format(PyExc_ValueError,
288 : "__name__ must not contain null bytes");
289 0 : return -1;
290 : }
291 0 : Py_DECREF(tmp);
292 :
293 0 : tp_name = _PyUnicode_AsString(value);
294 0 : if (tp_name == NULL)
295 0 : return -1;
296 :
297 0 : et = (PyHeapTypeObject*)type;
298 :
299 0 : Py_INCREF(value);
300 :
301 0 : Py_DECREF(et->ht_name);
302 0 : et->ht_name = value;
303 :
304 0 : type->tp_name = tp_name;
305 :
306 0 : return 0;
307 : }
308 :
309 : static int
310 0 : type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
311 : {
312 : PyHeapTypeObject* et;
313 :
314 0 : if (!PyUnicode_Check(value)) {
315 0 : PyErr_Format(PyExc_TypeError,
316 : "can only assign string to %s.__qualname__, not '%s'",
317 0 : type->tp_name, Py_TYPE(value)->tp_name);
318 0 : return -1;
319 : }
320 :
321 0 : et = (PyHeapTypeObject*)type;
322 0 : Py_INCREF(value);
323 0 : Py_DECREF(et->ht_qualname);
324 0 : et->ht_qualname = value;
325 0 : return 0;
326 : }
327 :
328 : static PyObject *
329 1908 : type_module(PyTypeObject *type, void *context)
330 : {
331 : PyObject *mod;
332 : char *s;
333 :
334 1908 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
335 18 : mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
336 18 : if (!mod) {
337 0 : PyErr_Format(PyExc_AttributeError, "__module__");
338 0 : return 0;
339 : }
340 18 : Py_XINCREF(mod);
341 18 : return mod;
342 : }
343 : else {
344 1890 : s = strrchr(type->tp_name, '.');
345 1890 : if (s != NULL)
346 3780 : return PyUnicode_FromStringAndSize(
347 1890 : type->tp_name, (Py_ssize_t)(s - type->tp_name));
348 0 : return PyUnicode_FromString("builtins");
349 : }
350 : }
351 :
352 : static int
353 3 : type_set_module(PyTypeObject *type, PyObject *value, void *context)
354 : {
355 3 : if (!check_set_special_type_attr(type, value, "__module__"))
356 0 : return -1;
357 :
358 3 : PyType_Modified(type);
359 :
360 3 : return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
361 : }
362 :
363 : static PyObject *
364 35 : type_abstractmethods(PyTypeObject *type, void *context)
365 : {
366 35 : PyObject *mod = NULL;
367 : /* type itself has an __abstractmethods__ descriptor (this). Don't return
368 : that. */
369 35 : if (type != &PyType_Type)
370 35 : mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
371 35 : if (!mod) {
372 4 : PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
373 4 : return NULL;
374 : }
375 31 : Py_XINCREF(mod);
376 31 : return mod;
377 : }
378 :
379 : static int
380 29 : type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
381 : {
382 : /* __abstractmethods__ should only be set once on a type, in
383 : abc.ABCMeta.__new__, so this function doesn't do anything
384 : special to update subclasses.
385 : */
386 : int abstract, res;
387 29 : if (value != NULL) {
388 29 : abstract = PyObject_IsTrue(value);
389 29 : if (abstract < 0)
390 0 : return -1;
391 29 : res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
392 : }
393 : else {
394 0 : abstract = 0;
395 0 : res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
396 0 : if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
397 0 : PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
398 0 : return -1;
399 : }
400 : }
401 29 : if (res == 0) {
402 29 : PyType_Modified(type);
403 29 : if (abstract)
404 13 : type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
405 : else
406 16 : type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
407 : }
408 29 : return res;
409 : }
410 :
411 : static PyObject *
412 18 : type_get_bases(PyTypeObject *type, void *context)
413 : {
414 18 : Py_INCREF(type->tp_bases);
415 18 : return type->tp_bases;
416 : }
417 :
418 : static PyTypeObject *best_base(PyObject *);
419 : static int mro_internal(PyTypeObject *);
420 : static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
421 : static int add_subclass(PyTypeObject*, PyTypeObject*);
422 : static void remove_subclass(PyTypeObject *, PyTypeObject *);
423 : static void update_all_slots(PyTypeObject *);
424 :
425 : typedef int (*update_callback)(PyTypeObject *, void *);
426 : static int update_subclasses(PyTypeObject *type, PyObject *name,
427 : update_callback callback, void *data);
428 : static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
429 : update_callback callback, void *data);
430 :
431 : static int
432 0 : mro_subclasses(PyTypeObject *type, PyObject* temp)
433 : {
434 : PyTypeObject *subclass;
435 : PyObject *ref, *subclasses, *old_mro;
436 : Py_ssize_t i, n;
437 :
438 0 : subclasses = type->tp_subclasses;
439 0 : if (subclasses == NULL)
440 0 : return 0;
441 : assert(PyList_Check(subclasses));
442 0 : n = PyList_GET_SIZE(subclasses);
443 0 : for (i = 0; i < n; i++) {
444 0 : ref = PyList_GET_ITEM(subclasses, i);
445 : assert(PyWeakref_CheckRef(ref));
446 0 : subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
447 : assert(subclass != NULL);
448 0 : if ((PyObject *)subclass == Py_None)
449 0 : continue;
450 : assert(PyType_Check(subclass));
451 0 : old_mro = subclass->tp_mro;
452 0 : if (mro_internal(subclass) < 0) {
453 0 : subclass->tp_mro = old_mro;
454 0 : return -1;
455 : }
456 : else {
457 : PyObject* tuple;
458 0 : tuple = PyTuple_Pack(2, subclass, old_mro);
459 0 : Py_DECREF(old_mro);
460 0 : if (!tuple)
461 0 : return -1;
462 0 : if (PyList_Append(temp, tuple) < 0)
463 0 : return -1;
464 0 : Py_DECREF(tuple);
465 : }
466 0 : if (mro_subclasses(subclass, temp) < 0)
467 0 : return -1;
468 : }
469 0 : return 0;
470 : }
471 :
472 : static int
473 0 : type_set_bases(PyTypeObject *type, PyObject *value, void *context)
474 : {
475 : Py_ssize_t i;
476 0 : int r = 0;
477 : PyObject *ob, *temp;
478 : PyTypeObject *new_base, *old_base;
479 : PyObject *old_bases, *old_mro;
480 :
481 0 : if (!check_set_special_type_attr(type, value, "__bases__"))
482 0 : return -1;
483 0 : if (!PyTuple_Check(value)) {
484 0 : PyErr_Format(PyExc_TypeError,
485 : "can only assign tuple to %s.__bases__, not %s",
486 0 : type->tp_name, Py_TYPE(value)->tp_name);
487 0 : return -1;
488 : }
489 0 : if (PyTuple_GET_SIZE(value) == 0) {
490 0 : PyErr_Format(PyExc_TypeError,
491 : "can only assign non-empty tuple to %s.__bases__, not ()",
492 : type->tp_name);
493 0 : return -1;
494 : }
495 0 : for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
496 0 : ob = PyTuple_GET_ITEM(value, i);
497 0 : if (!PyType_Check(ob)) {
498 0 : PyErr_Format(PyExc_TypeError,
499 : "%s.__bases__ must be tuple of classes, not '%s'",
500 0 : type->tp_name, Py_TYPE(ob)->tp_name);
501 0 : return -1;
502 : }
503 0 : if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
504 0 : PyErr_SetString(PyExc_TypeError,
505 : "a __bases__ item causes an inheritance cycle");
506 0 : return -1;
507 : }
508 : }
509 :
510 0 : new_base = best_base(value);
511 :
512 0 : if (!new_base)
513 0 : return -1;
514 :
515 0 : if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
516 0 : return -1;
517 :
518 0 : Py_INCREF(new_base);
519 0 : Py_INCREF(value);
520 :
521 0 : old_bases = type->tp_bases;
522 0 : old_base = type->tp_base;
523 0 : old_mro = type->tp_mro;
524 :
525 0 : type->tp_bases = value;
526 0 : type->tp_base = new_base;
527 :
528 0 : if (mro_internal(type) < 0) {
529 0 : goto bail;
530 : }
531 :
532 0 : temp = PyList_New(0);
533 0 : if (!temp)
534 0 : goto bail;
535 :
536 0 : r = mro_subclasses(type, temp);
537 :
538 0 : if (r < 0) {
539 0 : for (i = 0; i < PyList_Size(temp); i++) {
540 : PyTypeObject* cls;
541 : PyObject* mro;
542 0 : PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
543 : "", 2, 2, &cls, &mro);
544 0 : Py_INCREF(mro);
545 0 : ob = cls->tp_mro;
546 0 : cls->tp_mro = mro;
547 0 : Py_DECREF(ob);
548 : }
549 0 : Py_DECREF(temp);
550 0 : goto bail;
551 : }
552 :
553 0 : Py_DECREF(temp);
554 :
555 : /* any base that was in __bases__ but now isn't, we
556 : need to remove |type| from its tp_subclasses.
557 : conversely, any class now in __bases__ that wasn't
558 : needs to have |type| added to its subclasses. */
559 :
560 : /* for now, sod that: just remove from all old_bases,
561 : add to all new_bases */
562 :
563 0 : for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
564 0 : ob = PyTuple_GET_ITEM(old_bases, i);
565 0 : if (PyType_Check(ob)) {
566 0 : remove_subclass(
567 : (PyTypeObject*)ob, type);
568 : }
569 : }
570 :
571 0 : for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
572 0 : ob = PyTuple_GET_ITEM(value, i);
573 0 : if (PyType_Check(ob)) {
574 0 : if (add_subclass((PyTypeObject*)ob, type) < 0)
575 0 : r = -1;
576 : }
577 : }
578 :
579 0 : update_all_slots(type);
580 :
581 0 : Py_DECREF(old_bases);
582 0 : Py_DECREF(old_base);
583 0 : Py_DECREF(old_mro);
584 :
585 0 : return r;
586 :
587 : bail:
588 0 : Py_DECREF(type->tp_bases);
589 0 : Py_DECREF(type->tp_base);
590 0 : if (type->tp_mro != old_mro) {
591 0 : Py_DECREF(type->tp_mro);
592 : }
593 :
594 0 : type->tp_bases = old_bases;
595 0 : type->tp_base = old_base;
596 0 : type->tp_mro = old_mro;
597 :
598 0 : return -1;
599 : }
600 :
601 : static PyObject *
602 25 : type_dict(PyTypeObject *type, void *context)
603 : {
604 25 : if (type->tp_dict == NULL) {
605 0 : Py_INCREF(Py_None);
606 0 : return Py_None;
607 : }
608 25 : return PyDictProxy_New(type->tp_dict);
609 : }
610 :
611 : static PyObject *
612 0 : type_get_doc(PyTypeObject *type, void *context)
613 : {
614 : PyObject *result;
615 0 : if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
616 0 : return PyUnicode_FromString(type->tp_doc);
617 0 : result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
618 0 : if (result == NULL) {
619 0 : result = Py_None;
620 0 : Py_INCREF(result);
621 : }
622 0 : else if (Py_TYPE(result)->tp_descr_get) {
623 0 : result = Py_TYPE(result)->tp_descr_get(result, NULL,
624 : (PyObject *)type);
625 : }
626 : else {
627 0 : Py_INCREF(result);
628 : }
629 0 : return result;
630 : }
631 :
632 : static int
633 0 : type_set_doc(PyTypeObject *type, PyObject *value, void *context)
634 : {
635 0 : if (!check_set_special_type_attr(type, value, "__doc__"))
636 0 : return -1;
637 0 : PyType_Modified(type);
638 0 : return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
639 : }
640 :
641 : static PyObject *
642 3046 : type___instancecheck__(PyObject *type, PyObject *inst)
643 : {
644 3046 : switch (_PyObject_RealIsInstance(inst, type)) {
645 : case -1:
646 0 : return NULL;
647 : case 0:
648 3045 : Py_RETURN_FALSE;
649 : default:
650 1 : Py_RETURN_TRUE;
651 : }
652 : }
653 :
654 :
655 : static PyObject *
656 328 : type___subclasscheck__(PyObject *type, PyObject *inst)
657 : {
658 328 : switch (_PyObject_RealIsSubclass(inst, type)) {
659 : case -1:
660 0 : return NULL;
661 : case 0:
662 42 : Py_RETURN_FALSE;
663 : default:
664 286 : Py_RETURN_TRUE;
665 : }
666 : }
667 :
668 :
669 : static PyGetSetDef type_getsets[] = {
670 : {"__name__", (getter)type_name, (setter)type_set_name, NULL},
671 : {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
672 : {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
673 : {"__module__", (getter)type_module, (setter)type_set_module, NULL},
674 : {"__abstractmethods__", (getter)type_abstractmethods,
675 : (setter)type_set_abstractmethods, NULL},
676 : {"__dict__", (getter)type_dict, NULL, NULL},
677 : {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
678 : {0}
679 : };
680 :
681 : static PyObject *
682 0 : type_repr(PyTypeObject *type)
683 : {
684 : PyObject *mod, *name, *rtn;
685 :
686 0 : mod = type_module(type, NULL);
687 0 : if (mod == NULL)
688 0 : PyErr_Clear();
689 0 : else if (!PyUnicode_Check(mod)) {
690 0 : Py_DECREF(mod);
691 0 : mod = NULL;
692 : }
693 0 : name = type_qualname(type, NULL);
694 0 : if (name == NULL)
695 0 : return NULL;
696 :
697 0 : if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
698 0 : rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
699 : else
700 0 : rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
701 :
702 0 : Py_XDECREF(mod);
703 0 : Py_DECREF(name);
704 0 : return rtn;
705 : }
706 :
707 : static PyObject *
708 19914 : type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
709 : {
710 : PyObject *obj;
711 :
712 19914 : if (type->tp_new == NULL) {
713 0 : PyErr_Format(PyExc_TypeError,
714 : "cannot create '%.100s' instances",
715 : type->tp_name);
716 0 : return NULL;
717 : }
718 :
719 19914 : obj = type->tp_new(type, args, kwds);
720 19914 : if (obj != NULL) {
721 : /* Ugly exception: when the call was type(something),
722 : don't call tp_init on the result. */
723 20503 : if (type == &PyType_Type &&
724 1178 : PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
725 0 : (kwds == NULL ||
726 0 : (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
727 373 : return obj;
728 : /* If the returned object is not an instance of type,
729 : it won't be initialized. */
730 19541 : if (!PyType_IsSubtype(Py_TYPE(obj), type))
731 1 : return obj;
732 19540 : type = Py_TYPE(obj);
733 39080 : if (type->tp_init != NULL &&
734 19540 : type->tp_init(obj, args, kwds) < 0) {
735 28 : Py_DECREF(obj);
736 28 : obj = NULL;
737 : }
738 : }
739 19540 : return obj;
740 : }
741 :
742 : PyObject *
743 6514 : PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
744 : {
745 : PyObject *obj;
746 6514 : const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
747 : /* note that we need to add one, for the sentinel */
748 :
749 6514 : if (PyType_IS_GC(type))
750 6420 : obj = _PyObject_GC_Malloc(size);
751 : else
752 94 : obj = (PyObject *)PyObject_MALLOC(size);
753 :
754 6514 : if (obj == NULL)
755 0 : return PyErr_NoMemory();
756 :
757 6514 : memset(obj, '\0', size);
758 :
759 6514 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
760 1784 : Py_INCREF(type);
761 :
762 6514 : if (type->tp_itemsize == 0)
763 6268 : PyObject_INIT(obj, type);
764 : else
765 246 : (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
766 :
767 6514 : if (PyType_IS_GC(type))
768 6420 : _PyObject_GC_TRACK(obj);
769 6514 : return obj;
770 : }
771 :
772 : PyObject *
773 545 : PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
774 : {
775 545 : return type->tp_alloc(type, 0);
776 : }
777 :
778 : /* Helpers for subtyping */
779 :
780 : static int
781 120 : traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
782 : {
783 : Py_ssize_t i, n;
784 : PyMemberDef *mp;
785 :
786 120 : n = Py_SIZE(type);
787 120 : mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
788 240 : for (i = 0; i < n; i++, mp++) {
789 120 : if (mp->type == T_OBJECT_EX) {
790 120 : char *addr = (char *)self + mp->offset;
791 120 : PyObject *obj = *(PyObject **)addr;
792 120 : if (obj != NULL) {
793 120 : int err = visit(obj, arg);
794 120 : if (err)
795 0 : return err;
796 : }
797 : }
798 : }
799 120 : return 0;
800 : }
801 :
802 : static int
803 1166 : subtype_traverse(PyObject *self, visitproc visit, void *arg)
804 : {
805 : PyTypeObject *type, *base;
806 : traverseproc basetraverse;
807 :
808 : /* Find the nearest base with a different tp_traverse,
809 : and traverse slots while we're at it */
810 1166 : type = Py_TYPE(self);
811 1166 : base = type;
812 3724 : while ((basetraverse = base->tp_traverse) == subtype_traverse) {
813 1392 : if (Py_SIZE(base)) {
814 120 : int err = traverse_slots(base, self, visit, arg);
815 120 : if (err)
816 0 : return err;
817 : }
818 1392 : base = base->tp_base;
819 : assert(base);
820 : }
821 :
822 1166 : if (type->tp_dictoffset != base->tp_dictoffset) {
823 874 : PyObject **dictptr = _PyObject_GetDictPtr(self);
824 874 : if (dictptr && *dictptr)
825 870 : Py_VISIT(*dictptr);
826 : }
827 :
828 1166 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
829 : /* For a heaptype, the instances count as references
830 : to the type. Traverse the type so the collector
831 : can find cycles involving this link. */
832 1166 : Py_VISIT(type);
833 :
834 1166 : if (basetraverse)
835 296 : return basetraverse(self, visit, arg);
836 870 : return 0;
837 : }
838 :
839 : static void
840 80 : clear_slots(PyTypeObject *type, PyObject *self)
841 : {
842 : Py_ssize_t i, n;
843 : PyMemberDef *mp;
844 :
845 80 : n = Py_SIZE(type);
846 80 : mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
847 160 : for (i = 0; i < n; i++, mp++) {
848 80 : if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
849 80 : char *addr = (char *)self + mp->offset;
850 80 : PyObject *obj = *(PyObject **)addr;
851 80 : if (obj != NULL) {
852 80 : *(PyObject **)addr = NULL;
853 80 : Py_DECREF(obj);
854 : }
855 : }
856 : }
857 80 : }
858 :
859 : static int
860 0 : subtype_clear(PyObject *self)
861 : {
862 : PyTypeObject *type, *base;
863 : inquiry baseclear;
864 :
865 : /* Find the nearest base with a different tp_clear
866 : and clear slots while we're at it */
867 0 : type = Py_TYPE(self);
868 0 : base = type;
869 0 : while ((baseclear = base->tp_clear) == subtype_clear) {
870 0 : if (Py_SIZE(base))
871 0 : clear_slots(base, self);
872 0 : base = base->tp_base;
873 : assert(base);
874 : }
875 :
876 : /* Clear the instance dict (if any), to break cycles involving only
877 : __dict__ slots (as in the case 'self.__dict__ is self'). */
878 0 : if (type->tp_dictoffset != base->tp_dictoffset) {
879 0 : PyObject **dictptr = _PyObject_GetDictPtr(self);
880 0 : if (dictptr && *dictptr)
881 0 : Py_CLEAR(*dictptr);
882 : }
883 :
884 0 : if (baseclear)
885 0 : return baseclear(self);
886 0 : return 0;
887 : }
888 :
889 : static void
890 1454 : subtype_dealloc(PyObject *self)
891 : {
892 : PyTypeObject *type, *base;
893 : destructor basedealloc;
894 1454 : PyThreadState *tstate = PyThreadState_GET();
895 :
896 : /* Extract the type; we expect it to be a heap type */
897 1454 : type = Py_TYPE(self);
898 : assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
899 :
900 : /* Test whether the type has GC exactly once */
901 :
902 1454 : if (!PyType_IS_GC(type)) {
903 : /* It's really rare to find a dynamic type that doesn't have
904 : GC; it can only happen when deriving from 'object' and not
905 : adding any slots or instance variables. This allows
906 : certain simplifications: there's no need to call
907 : clear_slots(), or DECREF the dict, or clear weakrefs. */
908 :
909 : /* Maybe call finalizer; exit early if resurrected */
910 0 : if (type->tp_del) {
911 0 : type->tp_del(self);
912 0 : if (self->ob_refcnt > 0)
913 0 : return;
914 : }
915 :
916 : /* Find the nearest base with a different tp_dealloc */
917 0 : base = type;
918 0 : while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
919 : assert(Py_SIZE(base) == 0);
920 0 : base = base->tp_base;
921 : assert(base);
922 : }
923 :
924 : /* Extract the type again; tp_del may have changed it */
925 0 : type = Py_TYPE(self);
926 :
927 : /* Call the base tp_dealloc() */
928 : assert(basedealloc);
929 0 : basedealloc(self);
930 :
931 : /* Can't reference self beyond this point */
932 0 : Py_DECREF(type);
933 :
934 : /* Done */
935 0 : return;
936 : }
937 :
938 : /* We get here only if the type has GC */
939 :
940 : /* UnTrack and re-Track around the trashcan macro, alas */
941 : /* See explanation at end of function for full disclosure */
942 1454 : PyObject_GC_UnTrack(self);
943 1454 : ++_PyTrash_delete_nesting;
944 1454 : ++ tstate->trash_delete_nesting;
945 1454 : Py_TRASHCAN_SAFE_BEGIN(self);
946 1454 : --_PyTrash_delete_nesting;
947 1454 : -- tstate->trash_delete_nesting;
948 : /* DO NOT restore GC tracking at this point. weakref callbacks
949 : * (if any, and whether directly here or indirectly in something we
950 : * call) may trigger GC, and if self is tracked at that point, it
951 : * will look like trash to GC and GC will try to delete self again.
952 : */
953 :
954 : /* Find the nearest base with a different tp_dealloc */
955 1454 : base = type;
956 4414 : while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
957 1506 : base = base->tp_base;
958 : assert(base);
959 : }
960 :
961 : /* If we added a weaklist, we clear it. Do this *before* calling
962 : the finalizer (__del__), clearing slots, or clearing the instance
963 : dict. */
964 :
965 1454 : if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
966 1374 : PyObject_ClearWeakRefs(self);
967 :
968 : /* Maybe call finalizer; exit early if resurrected */
969 1454 : if (type->tp_del) {
970 0 : _PyObject_GC_TRACK(self);
971 0 : type->tp_del(self);
972 0 : if (self->ob_refcnt > 0)
973 0 : goto endlabel; /* resurrected */
974 : else
975 0 : _PyObject_GC_UNTRACK(self);
976 : /* New weakrefs could be created during the finalizer call.
977 : If this occurs, clear them out without calling their
978 : finalizers since they might rely on part of the object
979 : being finalized that has already been destroyed. */
980 0 : if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
981 : /* Modeled after GET_WEAKREFS_LISTPTR() */
982 0 : PyWeakReference **list = (PyWeakReference **) \
983 0 : PyObject_GET_WEAKREFS_LISTPTR(self);
984 0 : while (*list)
985 0 : _PyWeakref_ClearRef(*list);
986 : }
987 : }
988 :
989 : /* Clear slots up to the nearest base with a different tp_dealloc */
990 1454 : base = type;
991 4414 : while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
992 1506 : if (Py_SIZE(base))
993 80 : clear_slots(base, self);
994 1506 : base = base->tp_base;
995 : assert(base);
996 : }
997 :
998 : /* If we added a dict, DECREF it */
999 1454 : if (type->tp_dictoffset && !base->tp_dictoffset) {
1000 1330 : PyObject **dictptr = _PyObject_GetDictPtr(self);
1001 1330 : if (dictptr != NULL) {
1002 1330 : PyObject *dict = *dictptr;
1003 1330 : if (dict != NULL) {
1004 1110 : Py_DECREF(dict);
1005 1110 : *dictptr = NULL;
1006 : }
1007 : }
1008 : }
1009 :
1010 : /* Extract the type again; tp_del may have changed it */
1011 1454 : type = Py_TYPE(self);
1012 :
1013 : /* Call the base tp_dealloc(); first retrack self if
1014 : * basedealloc knows about gc.
1015 : */
1016 1454 : if (PyType_IS_GC(base))
1017 124 : _PyObject_GC_TRACK(self);
1018 : assert(basedealloc);
1019 1454 : basedealloc(self);
1020 :
1021 : /* Can't reference self beyond this point */
1022 1454 : Py_DECREF(type);
1023 :
1024 : endlabel:
1025 1454 : ++_PyTrash_delete_nesting;
1026 1454 : ++ tstate->trash_delete_nesting;
1027 1454 : Py_TRASHCAN_SAFE_END(self);
1028 1454 : --_PyTrash_delete_nesting;
1029 1454 : -- tstate->trash_delete_nesting;
1030 :
1031 : /* Explanation of the weirdness around the trashcan macros:
1032 :
1033 : Q. What do the trashcan macros do?
1034 :
1035 : A. Read the comment titled "Trashcan mechanism" in object.h.
1036 : For one, this explains why there must be a call to GC-untrack
1037 : before the trashcan begin macro. Without understanding the
1038 : trashcan code, the answers to the following questions don't make
1039 : sense.
1040 :
1041 : Q. Why do we GC-untrack before the trashcan and then immediately
1042 : GC-track again afterward?
1043 :
1044 : A. In the case that the base class is GC-aware, the base class
1045 : probably GC-untracks the object. If it does that using the
1046 : UNTRACK macro, this will crash when the object is already
1047 : untracked. Because we don't know what the base class does, the
1048 : only safe thing is to make sure the object is tracked when we
1049 : call the base class dealloc. But... The trashcan begin macro
1050 : requires that the object is *untracked* before it is called. So
1051 : the dance becomes:
1052 :
1053 : GC untrack
1054 : trashcan begin
1055 : GC track
1056 :
1057 : Q. Why did the last question say "immediately GC-track again"?
1058 : It's nowhere near immediately.
1059 :
1060 : A. Because the code *used* to re-track immediately. Bad Idea.
1061 : self has a refcount of 0, and if gc ever gets its hands on it
1062 : (which can happen if any weakref callback gets invoked), it
1063 : looks like trash to gc too, and gc also tries to delete self
1064 : then. But we're already deleting self. Double deallocation is
1065 : a subtle disaster.
1066 :
1067 : Q. Why the bizarre (net-zero) manipulation of
1068 : _PyTrash_delete_nesting around the trashcan macros?
1069 :
1070 : A. Some base classes (e.g. list) also use the trashcan mechanism.
1071 : The following scenario used to be possible:
1072 :
1073 : - suppose the trashcan level is one below the trashcan limit
1074 :
1075 : - subtype_dealloc() is called
1076 :
1077 : - the trashcan limit is not yet reached, so the trashcan level
1078 : is incremented and the code between trashcan begin and end is
1079 : executed
1080 :
1081 : - this destroys much of the object's contents, including its
1082 : slots and __dict__
1083 :
1084 : - basedealloc() is called; this is really list_dealloc(), or
1085 : some other type which also uses the trashcan macros
1086 :
1087 : - the trashcan limit is now reached, so the object is put on the
1088 : trashcan's to-be-deleted-later list
1089 :
1090 : - basedealloc() returns
1091 :
1092 : - subtype_dealloc() decrefs the object's type
1093 :
1094 : - subtype_dealloc() returns
1095 :
1096 : - later, the trashcan code starts deleting the objects from its
1097 : to-be-deleted-later list
1098 :
1099 : - subtype_dealloc() is called *AGAIN* for the same object
1100 :
1101 : - at the very least (if the destroyed slots and __dict__ don't
1102 : cause problems) the object's type gets decref'ed a second
1103 : time, which is *BAD*!!!
1104 :
1105 : The remedy is to make sure that if the code between trashcan
1106 : begin and end in subtype_dealloc() is called, the code between
1107 : trashcan begin and end in basedealloc() will also be called.
1108 : This is done by decrementing the level after passing into the
1109 : trashcan block, and incrementing it just before leaving the
1110 : block.
1111 :
1112 : But now it's possible that a chain of objects consisting solely
1113 : of objects whose deallocator is subtype_dealloc() will defeat
1114 : the trashcan mechanism completely: the decremented level means
1115 : that the effective level never reaches the limit. Therefore, we
1116 : *increment* the level *before* entering the trashcan block, and
1117 : matchingly decrement it after leaving. This means the trashcan
1118 : code will trigger a little early, but that's no big deal.
1119 :
1120 : Q. Are there any live examples of code in need of all this
1121 : complexity?
1122 :
1123 : A. Yes. See SF bug 668433 for code that crashed (when Python was
1124 : compiled in debug mode) before the trashcan level manipulations
1125 : were added. For more discussion, see SF patches 581742, 575073
1126 : and bug 574207.
1127 : */
1128 : }
1129 :
1130 : static PyTypeObject *solid_base(PyTypeObject *type);
1131 :
1132 : /* type test with subclassing support */
1133 :
1134 : int
1135 57303 : PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1136 : {
1137 : PyObject *mro;
1138 :
1139 57303 : mro = a->tp_mro;
1140 57303 : if (mro != NULL) {
1141 : /* Deal with multiple inheritance without recursion
1142 : by walking the MRO tuple */
1143 : Py_ssize_t i, n;
1144 : assert(PyTuple_Check(mro));
1145 57250 : n = PyTuple_GET_SIZE(mro);
1146 125959 : for (i = 0; i < n; i++) {
1147 100838 : if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1148 32129 : return 1;
1149 : }
1150 25121 : return 0;
1151 : }
1152 : else {
1153 : /* a is not completely initilized yet; follow tp_base */
1154 : do {
1155 98 : if (a == b)
1156 40 : return 1;
1157 58 : a = a->tp_base;
1158 58 : } while (a != NULL);
1159 13 : return b == &PyBaseObject_Type;
1160 : }
1161 : }
1162 :
1163 : /* Internal routines to do a method lookup in the type
1164 : without looking in the instance dictionary
1165 : (so we can't use PyObject_GetAttr) but still binding
1166 : it to the instance. The arguments are the object,
1167 : the method name as a C string, and the address of a
1168 : static variable used to cache the interned Python string.
1169 :
1170 : Two variants:
1171 :
1172 : - lookup_maybe() returns NULL without raising an exception
1173 : when the _PyType_Lookup() call fails;
1174 :
1175 : - lookup_method() always raises an exception upon errors.
1176 :
1177 : - _PyObject_LookupSpecial() exported for the benefit of other places.
1178 : */
1179 :
1180 : static PyObject *
1181 9369 : lookup_maybe(PyObject *self, _Py_Identifier *attrid)
1182 : {
1183 : PyObject *res;
1184 :
1185 9369 : res = _PyType_LookupId(Py_TYPE(self), attrid);
1186 9369 : if (res != NULL) {
1187 : descrgetfunc f;
1188 8975 : if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1189 0 : Py_INCREF(res);
1190 : else
1191 8975 : res = f(res, self, (PyObject *)(Py_TYPE(self)));
1192 : }
1193 9369 : return res;
1194 : }
1195 :
1196 : static PyObject *
1197 1839 : lookup_method(PyObject *self, _Py_Identifier *attrid)
1198 : {
1199 1839 : PyObject *res = lookup_maybe(self, attrid);
1200 1839 : if (res == NULL && !PyErr_Occurred())
1201 0 : PyErr_SetObject(PyExc_AttributeError, attrid->object);
1202 1839 : return res;
1203 : }
1204 :
1205 : PyObject *
1206 5410 : _PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
1207 : {
1208 5410 : return lookup_maybe(self, attrid);
1209 : }
1210 :
1211 : /* A variation of PyObject_CallMethod that uses lookup_method()
1212 : instead of PyObject_GetAttrString(). This uses the same convention
1213 : as lookup_method to cache the interned name string object. */
1214 :
1215 : static PyObject *
1216 2061 : call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
1217 : {
1218 : va_list va;
1219 2061 : PyObject *args, *func = 0, *retval;
1220 2061 : va_start(va, format);
1221 :
1222 2061 : func = lookup_maybe(o, nameid);
1223 2061 : if (func == NULL) {
1224 0 : va_end(va);
1225 0 : if (!PyErr_Occurred())
1226 0 : PyErr_SetObject(PyExc_AttributeError, nameid->object);
1227 0 : return NULL;
1228 : }
1229 :
1230 2061 : if (format && *format)
1231 2061 : args = Py_VaBuildValue(format, va);
1232 : else
1233 0 : args = PyTuple_New(0);
1234 :
1235 2061 : va_end(va);
1236 :
1237 2061 : if (args == NULL)
1238 0 : return NULL;
1239 :
1240 : assert(PyTuple_Check(args));
1241 2061 : retval = PyObject_Call(func, args, NULL);
1242 :
1243 2061 : Py_DECREF(args);
1244 2061 : Py_DECREF(func);
1245 :
1246 2061 : return retval;
1247 : }
1248 :
1249 : /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1250 :
1251 : static PyObject *
1252 0 : call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
1253 : {
1254 : va_list va;
1255 0 : PyObject *args, *func = 0, *retval;
1256 0 : va_start(va, format);
1257 :
1258 0 : func = lookup_maybe(o, nameid);
1259 0 : if (func == NULL) {
1260 0 : va_end(va);
1261 0 : if (!PyErr_Occurred())
1262 0 : Py_RETURN_NOTIMPLEMENTED;
1263 0 : return NULL;
1264 : }
1265 :
1266 0 : if (format && *format)
1267 0 : args = Py_VaBuildValue(format, va);
1268 : else
1269 0 : args = PyTuple_New(0);
1270 :
1271 0 : va_end(va);
1272 :
1273 0 : if (args == NULL)
1274 0 : return NULL;
1275 :
1276 : assert(PyTuple_Check(args));
1277 0 : retval = PyObject_Call(func, args, NULL);
1278 :
1279 0 : Py_DECREF(args);
1280 0 : Py_DECREF(func);
1281 :
1282 0 : return retval;
1283 : }
1284 :
1285 : /*
1286 : Method resolution order algorithm C3 described in
1287 : "A Monotonic Superclass Linearization for Dylan",
1288 : by Kim Barrett, Bob Cassel, Paul Haahr,
1289 : David A. Moon, Keith Playford, and P. Tucker Withington.
1290 : (OOPSLA 1996)
1291 :
1292 : Some notes about the rules implied by C3:
1293 :
1294 : No duplicate bases.
1295 : It isn't legal to repeat a class in a list of base classes.
1296 :
1297 : The next three properties are the 3 constraints in "C3".
1298 :
1299 : Local precendece order.
1300 : If A precedes B in C's MRO, then A will precede B in the MRO of all
1301 : subclasses of C.
1302 :
1303 : Monotonicity.
1304 : The MRO of a class must be an extension without reordering of the
1305 : MRO of each of its superclasses.
1306 :
1307 : Extended Precedence Graph (EPG).
1308 : Linearization is consistent if there is a path in the EPG from
1309 : each class to all its successors in the linearization. See
1310 : the paper for definition of EPG.
1311 : */
1312 :
1313 : static int
1314 2424 : tail_contains(PyObject *list, int whence, PyObject *o) {
1315 : Py_ssize_t j, size;
1316 2424 : size = PyList_GET_SIZE(list);
1317 :
1318 3850 : for (j = whence+1; j < size; j++) {
1319 1486 : if (PyList_GET_ITEM(list, j) == o)
1320 60 : return 1;
1321 : }
1322 2364 : return 0;
1323 : }
1324 :
1325 : static PyObject *
1326 0 : class_name(PyObject *cls)
1327 : {
1328 0 : PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
1329 0 : if (name == NULL) {
1330 0 : PyErr_Clear();
1331 0 : Py_XDECREF(name);
1332 0 : name = PyObject_Repr(cls);
1333 : }
1334 0 : if (name == NULL)
1335 0 : return NULL;
1336 0 : if (!PyUnicode_Check(name)) {
1337 0 : Py_DECREF(name);
1338 0 : return NULL;
1339 : }
1340 0 : return name;
1341 : }
1342 :
1343 : static int
1344 437 : check_duplicates(PyObject *list)
1345 : {
1346 : Py_ssize_t i, j, n;
1347 : /* Let's use a quadratic time algorithm,
1348 : assuming that the bases lists is short.
1349 : */
1350 437 : n = PyList_GET_SIZE(list);
1351 905 : for (i = 0; i < n; i++) {
1352 468 : PyObject *o = PyList_GET_ITEM(list, i);
1353 516 : for (j = i + 1; j < n; j++) {
1354 48 : if (PyList_GET_ITEM(list, j) == o) {
1355 0 : o = class_name(o);
1356 0 : if (o != NULL) {
1357 0 : PyErr_Format(PyExc_TypeError,
1358 : "duplicate base class %U",
1359 : o);
1360 0 : Py_DECREF(o);
1361 : } else {
1362 0 : PyErr_SetString(PyExc_TypeError,
1363 : "duplicate base class");
1364 : }
1365 0 : return -1;
1366 : }
1367 : }
1368 : }
1369 437 : return 0;
1370 : }
1371 :
1372 : /* Raise a TypeError for an MRO order disagreement.
1373 :
1374 : It's hard to produce a good error message. In the absence of better
1375 : insight into error reporting, report the classes that were candidates
1376 : to be put next into the MRO. There is some conflict between the
1377 : order in which they should be put in the MRO, but it's hard to
1378 : diagnose what constraint can't be satisfied.
1379 : */
1380 :
1381 : static void
1382 0 : set_mro_error(PyObject *to_merge, int *remain)
1383 : {
1384 : Py_ssize_t i, n, off, to_merge_size;
1385 : char buf[1000];
1386 : PyObject *k, *v;
1387 0 : PyObject *set = PyDict_New();
1388 0 : if (!set) return;
1389 :
1390 0 : to_merge_size = PyList_GET_SIZE(to_merge);
1391 0 : for (i = 0; i < to_merge_size; i++) {
1392 0 : PyObject *L = PyList_GET_ITEM(to_merge, i);
1393 0 : if (remain[i] < PyList_GET_SIZE(L)) {
1394 0 : PyObject *c = PyList_GET_ITEM(L, remain[i]);
1395 0 : if (PyDict_SetItem(set, c, Py_None) < 0) {
1396 0 : Py_DECREF(set);
1397 : return;
1398 : }
1399 : }
1400 : }
1401 0 : n = PyDict_Size(set);
1402 :
1403 0 : off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1404 : consistent method resolution\norder (MRO) for bases");
1405 0 : i = 0;
1406 0 : while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1407 0 : PyObject *name = class_name(k);
1408 : char *name_str;
1409 0 : if (name != NULL) {
1410 0 : name_str = _PyUnicode_AsString(name);
1411 0 : if (name_str == NULL)
1412 0 : name_str = "?";
1413 : } else
1414 0 : name_str = "?";
1415 0 : off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
1416 0 : Py_XDECREF(name);
1417 0 : if (--n && (size_t)(off+1) < sizeof(buf)) {
1418 0 : buf[off++] = ',';
1419 0 : buf[off] = '\0';
1420 : }
1421 : }
1422 0 : PyErr_SetString(PyExc_TypeError, buf);
1423 0 : Py_DECREF(set);
1424 : }
1425 :
1426 : static int
1427 437 : pmerge(PyObject *acc, PyObject* to_merge) {
1428 : Py_ssize_t i, j, to_merge_size, empty_cnt;
1429 : int *remain;
1430 : int ok;
1431 :
1432 437 : to_merge_size = PyList_GET_SIZE(to_merge);
1433 :
1434 : /* remain stores an index into each sublist of to_merge.
1435 : remain[i] is the index of the next base in to_merge[i]
1436 : that is not included in acc.
1437 : */
1438 437 : remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1439 437 : if (remain == NULL)
1440 0 : return -1;
1441 1342 : for (i = 0; i < to_merge_size; i++)
1442 905 : remain[i] = 0;
1443 :
1444 : again:
1445 1485 : empty_cnt = 0;
1446 2450 : for (i = 0; i < to_merge_size; i++) {
1447 : PyObject *candidate;
1448 :
1449 2013 : PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1450 :
1451 2013 : if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1452 905 : empty_cnt++;
1453 905 : continue;
1454 : }
1455 :
1456 : /* Choose next candidate for MRO.
1457 :
1458 : The input sequences alone can determine the choice.
1459 : If not, choose the class which appears in the MRO
1460 : of the earliest direct superclass of the new class.
1461 : */
1462 :
1463 1108 : candidate = PyList_GET_ITEM(cur_list, remain[i]);
1464 3472 : for (j = 0; j < to_merge_size; j++) {
1465 2424 : PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1466 2424 : if (tail_contains(j_lst, remain[j], candidate)) {
1467 60 : goto skip; /* continue outer loop */
1468 : }
1469 : }
1470 1048 : ok = PyList_Append(acc, candidate);
1471 1048 : if (ok < 0) {
1472 0 : PyMem_Free(remain);
1473 0 : return -1;
1474 : }
1475 3321 : for (j = 0; j < to_merge_size; j++) {
1476 2273 : PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1477 3968 : if (remain[j] < PyList_GET_SIZE(j_lst) &&
1478 1695 : PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1479 1574 : remain[j]++;
1480 : }
1481 : }
1482 1048 : goto again;
1483 : skip: ;
1484 : }
1485 :
1486 437 : if (empty_cnt == to_merge_size) {
1487 437 : PyMem_FREE(remain);
1488 437 : return 0;
1489 : }
1490 0 : set_mro_error(to_merge, remain);
1491 0 : PyMem_FREE(remain);
1492 0 : return -1;
1493 : }
1494 :
1495 : static PyObject *
1496 437 : mro_implementation(PyTypeObject *type)
1497 : {
1498 : Py_ssize_t i, n;
1499 : int ok;
1500 : PyObject *bases, *result;
1501 : PyObject *to_merge, *bases_aslist;
1502 :
1503 437 : if (type->tp_dict == NULL) {
1504 0 : if (PyType_Ready(type) < 0)
1505 0 : return NULL;
1506 : }
1507 :
1508 : /* Find a superclass linearization that honors the constraints
1509 : of the explicit lists of bases and the constraints implied by
1510 : each base class.
1511 :
1512 : to_merge is a list of lists, where each list is a superclass
1513 : linearization implied by a base class. The last element of
1514 : to_merge is the declared list of bases.
1515 : */
1516 :
1517 437 : bases = type->tp_bases;
1518 437 : n = PyTuple_GET_SIZE(bases);
1519 :
1520 437 : to_merge = PyList_New(n+1);
1521 437 : if (to_merge == NULL)
1522 0 : return NULL;
1523 :
1524 905 : for (i = 0; i < n; i++) {
1525 468 : PyObject *base = PyTuple_GET_ITEM(bases, i);
1526 : PyObject *parentMRO;
1527 468 : parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
1528 468 : if (parentMRO == NULL) {
1529 0 : Py_DECREF(to_merge);
1530 0 : return NULL;
1531 : }
1532 :
1533 468 : PyList_SET_ITEM(to_merge, i, parentMRO);
1534 : }
1535 :
1536 437 : bases_aslist = PySequence_List(bases);
1537 437 : if (bases_aslist == NULL) {
1538 0 : Py_DECREF(to_merge);
1539 0 : return NULL;
1540 : }
1541 : /* This is just a basic sanity check. */
1542 437 : if (check_duplicates(bases_aslist) < 0) {
1543 0 : Py_DECREF(to_merge);
1544 0 : Py_DECREF(bases_aslist);
1545 0 : return NULL;
1546 : }
1547 437 : PyList_SET_ITEM(to_merge, n, bases_aslist);
1548 :
1549 437 : result = Py_BuildValue("[O]", (PyObject *)type);
1550 437 : if (result == NULL) {
1551 0 : Py_DECREF(to_merge);
1552 0 : return NULL;
1553 : }
1554 :
1555 437 : ok = pmerge(result, to_merge);
1556 437 : Py_DECREF(to_merge);
1557 437 : if (ok < 0) {
1558 0 : Py_DECREF(result);
1559 0 : return NULL;
1560 : }
1561 :
1562 437 : return result;
1563 : }
1564 :
1565 : static PyObject *
1566 29 : mro_external(PyObject *self)
1567 : {
1568 29 : PyTypeObject *type = (PyTypeObject *)self;
1569 :
1570 29 : return mro_implementation(type);
1571 : }
1572 :
1573 : static int
1574 437 : mro_internal(PyTypeObject *type)
1575 : {
1576 : PyObject *mro, *result, *tuple;
1577 437 : int checkit = 0;
1578 :
1579 437 : if (Py_TYPE(type) == &PyType_Type) {
1580 408 : result = mro_implementation(type);
1581 : }
1582 : else {
1583 : _Py_IDENTIFIER(mro);
1584 29 : checkit = 1;
1585 29 : mro = lookup_method((PyObject *)type, &PyId_mro);
1586 29 : if (mro == NULL)
1587 0 : return -1;
1588 29 : result = PyObject_CallObject(mro, NULL);
1589 29 : Py_DECREF(mro);
1590 : }
1591 437 : if (result == NULL)
1592 0 : return -1;
1593 437 : tuple = PySequence_Tuple(result);
1594 437 : Py_DECREF(result);
1595 437 : if (tuple == NULL)
1596 0 : return -1;
1597 437 : if (checkit) {
1598 : Py_ssize_t i, len;
1599 : PyObject *cls;
1600 : PyTypeObject *solid;
1601 :
1602 29 : solid = solid_base(type);
1603 :
1604 29 : len = PyTuple_GET_SIZE(tuple);
1605 :
1606 174 : for (i = 0; i < len; i++) {
1607 : PyTypeObject *t;
1608 145 : cls = PyTuple_GET_ITEM(tuple, i);
1609 145 : if (!PyType_Check(cls)) {
1610 0 : PyErr_Format(PyExc_TypeError,
1611 : "mro() returned a non-class ('%.500s')",
1612 0 : Py_TYPE(cls)->tp_name);
1613 0 : Py_DECREF(tuple);
1614 0 : return -1;
1615 : }
1616 145 : t = (PyTypeObject*)cls;
1617 145 : if (!PyType_IsSubtype(solid, solid_base(t))) {
1618 0 : PyErr_Format(PyExc_TypeError,
1619 : "mro() returned base with unsuitable layout ('%.500s')",
1620 : t->tp_name);
1621 0 : Py_DECREF(tuple);
1622 0 : return -1;
1623 : }
1624 : }
1625 : }
1626 437 : type->tp_mro = tuple;
1627 :
1628 437 : type_mro_modified(type, type->tp_mro);
1629 : /* corner case: the super class might have been hidden
1630 : from the custom MRO */
1631 437 : type_mro_modified(type, type->tp_bases);
1632 :
1633 437 : PyType_Modified(type);
1634 :
1635 437 : return 0;
1636 : }
1637 :
1638 :
1639 : /* Calculate the best base amongst multiple base classes.
1640 : This is the first one that's on the path to the "solid base". */
1641 :
1642 : static PyTypeObject *
1643 245 : best_base(PyObject *bases)
1644 : {
1645 : Py_ssize_t i, n;
1646 : PyTypeObject *base, *winner, *candidate, *base_i;
1647 : PyObject *base_proto;
1648 :
1649 : assert(PyTuple_Check(bases));
1650 245 : n = PyTuple_GET_SIZE(bases);
1651 : assert(n > 0);
1652 245 : base = NULL;
1653 245 : winner = NULL;
1654 522 : for (i = 0; i < n; i++) {
1655 277 : base_proto = PyTuple_GET_ITEM(bases, i);
1656 277 : if (!PyType_Check(base_proto)) {
1657 0 : PyErr_SetString(
1658 : PyExc_TypeError,
1659 : "bases must be types");
1660 0 : return NULL;
1661 : }
1662 277 : base_i = (PyTypeObject *)base_proto;
1663 277 : if (base_i->tp_dict == NULL) {
1664 2 : if (PyType_Ready(base_i) < 0)
1665 0 : return NULL;
1666 : }
1667 277 : candidate = solid_base(base_i);
1668 277 : if (winner == NULL) {
1669 245 : winner = candidate;
1670 245 : base = base_i;
1671 : }
1672 32 : else if (PyType_IsSubtype(winner, candidate))
1673 : ;
1674 1 : else if (PyType_IsSubtype(candidate, winner)) {
1675 1 : winner = candidate;
1676 1 : base = base_i;
1677 : }
1678 : else {
1679 0 : PyErr_SetString(
1680 : PyExc_TypeError,
1681 : "multiple bases have "
1682 : "instance lay-out conflict");
1683 0 : return NULL;
1684 : }
1685 : }
1686 : assert (base != NULL);
1687 :
1688 245 : return base;
1689 : }
1690 :
1691 : static int
1692 1141 : extra_ivars(PyTypeObject *type, PyTypeObject *base)
1693 : {
1694 1141 : size_t t_size = type->tp_basicsize;
1695 1141 : size_t b_size = base->tp_basicsize;
1696 :
1697 : assert(t_size >= b_size); /* Else type smaller than base! */
1698 1141 : if (type->tp_itemsize || base->tp_itemsize) {
1699 : /* If itemsize is involved, stricter rules */
1700 7 : return t_size != b_size ||
1701 1 : type->tp_itemsize != base->tp_itemsize;
1702 : }
1703 1377 : if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1704 484 : type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1705 242 : type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1706 210 : t_size -= sizeof(PyObject *);
1707 1411 : if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1708 503 : type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1709 227 : type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1710 121 : t_size -= sizeof(PyObject *);
1711 :
1712 1135 : return t_size != b_size;
1713 : }
1714 :
1715 : static PyTypeObject *
1716 1141 : solid_base(PyTypeObject *type)
1717 : {
1718 : PyTypeObject *base;
1719 :
1720 1141 : if (type->tp_base)
1721 690 : base = solid_base(type->tp_base);
1722 : else
1723 451 : base = &PyBaseObject_Type;
1724 1141 : if (extra_ivars(type, base))
1725 178 : return type;
1726 : else
1727 963 : return base;
1728 : }
1729 :
1730 : static void object_dealloc(PyObject *);
1731 : static int object_init(PyObject *, PyObject *, PyObject *);
1732 : static int update_slot(PyTypeObject *, PyObject *);
1733 : static void fixup_slot_dispatchers(PyTypeObject *);
1734 :
1735 : /*
1736 : * Helpers for __dict__ descriptor. We don't want to expose the dicts
1737 : * inherited from various builtin types. The builtin base usually provides
1738 : * its own __dict__ descriptor, so we use that when we can.
1739 : */
1740 : static PyTypeObject *
1741 469 : get_builtin_base_with_dict(PyTypeObject *type)
1742 : {
1743 1407 : while (type->tp_base != NULL) {
1744 938 : if (type->tp_dictoffset != 0 &&
1745 469 : !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1746 0 : return type;
1747 469 : type = type->tp_base;
1748 : }
1749 469 : return NULL;
1750 : }
1751 :
1752 : static PyObject *
1753 0 : get_dict_descriptor(PyTypeObject *type)
1754 : {
1755 : PyObject *descr;
1756 :
1757 0 : descr = _PyType_LookupId(type, &PyId___dict__);
1758 0 : if (descr == NULL || !PyDescr_IsData(descr))
1759 0 : return NULL;
1760 :
1761 0 : return descr;
1762 : }
1763 :
1764 : static void
1765 0 : raise_dict_descr_error(PyObject *obj)
1766 : {
1767 0 : PyErr_Format(PyExc_TypeError,
1768 : "this __dict__ descriptor does not support "
1769 0 : "'%.200s' objects", Py_TYPE(obj)->tp_name);
1770 0 : }
1771 :
1772 : static PyObject *
1773 469 : subtype_dict(PyObject *obj, void *context)
1774 : {
1775 : PyTypeObject *base;
1776 :
1777 469 : base = get_builtin_base_with_dict(Py_TYPE(obj));
1778 469 : if (base != NULL) {
1779 : descrgetfunc func;
1780 0 : PyObject *descr = get_dict_descriptor(base);
1781 0 : if (descr == NULL) {
1782 0 : raise_dict_descr_error(obj);
1783 0 : return NULL;
1784 : }
1785 0 : func = Py_TYPE(descr)->tp_descr_get;
1786 0 : if (func == NULL) {
1787 0 : raise_dict_descr_error(obj);
1788 0 : return NULL;
1789 : }
1790 0 : return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
1791 : }
1792 469 : return PyObject_GenericGetDict(obj, context);
1793 : }
1794 :
1795 : static int
1796 0 : subtype_setdict(PyObject *obj, PyObject *value, void *context)
1797 : {
1798 : PyObject *dict, **dictptr;
1799 : PyTypeObject *base;
1800 :
1801 0 : base = get_builtin_base_with_dict(Py_TYPE(obj));
1802 0 : if (base != NULL) {
1803 : descrsetfunc func;
1804 0 : PyObject *descr = get_dict_descriptor(base);
1805 0 : if (descr == NULL) {
1806 0 : raise_dict_descr_error(obj);
1807 0 : return -1;
1808 : }
1809 0 : func = Py_TYPE(descr)->tp_descr_set;
1810 0 : if (func == NULL) {
1811 0 : raise_dict_descr_error(obj);
1812 0 : return -1;
1813 : }
1814 0 : return func(descr, obj, value);
1815 : }
1816 : /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
1817 0 : dictptr = _PyObject_GetDictPtr(obj);
1818 0 : if (dictptr == NULL) {
1819 0 : PyErr_SetString(PyExc_AttributeError,
1820 : "This object has no __dict__");
1821 0 : return -1;
1822 : }
1823 0 : if (value != NULL && !PyDict_Check(value)) {
1824 0 : PyErr_Format(PyExc_TypeError,
1825 : "__dict__ must be set to a dictionary, "
1826 0 : "not a '%.200s'", Py_TYPE(value)->tp_name);
1827 0 : return -1;
1828 : }
1829 0 : dict = *dictptr;
1830 0 : Py_XINCREF(value);
1831 0 : *dictptr = value;
1832 0 : Py_XDECREF(dict);
1833 0 : return 0;
1834 : }
1835 :
1836 : static PyObject *
1837 0 : subtype_getweakref(PyObject *obj, void *context)
1838 : {
1839 : PyObject **weaklistptr;
1840 : PyObject *result;
1841 :
1842 0 : if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1843 0 : PyErr_SetString(PyExc_AttributeError,
1844 : "This object has no __weakref__");
1845 0 : return NULL;
1846 : }
1847 : assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1848 : assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1849 : (size_t)(Py_TYPE(obj)->tp_basicsize));
1850 0 : weaklistptr = (PyObject **)
1851 0 : ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1852 0 : if (*weaklistptr == NULL)
1853 0 : result = Py_None;
1854 : else
1855 0 : result = *weaklistptr;
1856 0 : Py_INCREF(result);
1857 0 : return result;
1858 : }
1859 :
1860 : /* Three variants on the subtype_getsets list. */
1861 :
1862 : static PyGetSetDef subtype_getsets_full[] = {
1863 : {"__dict__", subtype_dict, subtype_setdict,
1864 : PyDoc_STR("dictionary for instance variables (if defined)")},
1865 : {"__weakref__", subtype_getweakref, NULL,
1866 : PyDoc_STR("list of weak references to the object (if defined)")},
1867 : {0}
1868 : };
1869 :
1870 : static PyGetSetDef subtype_getsets_dict_only[] = {
1871 : {"__dict__", subtype_dict, subtype_setdict,
1872 : PyDoc_STR("dictionary for instance variables (if defined)")},
1873 : {0}
1874 : };
1875 :
1876 : static PyGetSetDef subtype_getsets_weakref_only[] = {
1877 : {"__weakref__", subtype_getweakref, NULL,
1878 : PyDoc_STR("list of weak references to the object (if defined)")},
1879 : {0}
1880 : };
1881 :
1882 : static int
1883 9 : valid_identifier(PyObject *s)
1884 : {
1885 9 : if (!PyUnicode_Check(s)) {
1886 0 : PyErr_Format(PyExc_TypeError,
1887 : "__slots__ items must be strings, not '%.200s'",
1888 0 : Py_TYPE(s)->tp_name);
1889 0 : return 0;
1890 : }
1891 9 : if (!PyUnicode_IsIdentifier(s)) {
1892 0 : PyErr_SetString(PyExc_TypeError,
1893 : "__slots__ must be identifiers");
1894 0 : return 0;
1895 : }
1896 9 : return 1;
1897 : }
1898 :
1899 : /* Forward */
1900 : static int
1901 : object_init(PyObject *self, PyObject *args, PyObject *kwds);
1902 :
1903 : static int
1904 245 : type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1905 : {
1906 : int res;
1907 :
1908 : assert(args != NULL && PyTuple_Check(args));
1909 : assert(kwds == NULL || PyDict_Check(kwds));
1910 :
1911 245 : if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1912 0 : PyErr_SetString(PyExc_TypeError,
1913 : "type.__init__() takes no keyword arguments");
1914 0 : return -1;
1915 : }
1916 :
1917 490 : if (args != NULL && PyTuple_Check(args) &&
1918 490 : (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1919 0 : PyErr_SetString(PyExc_TypeError,
1920 : "type.__init__() takes 1 or 3 arguments");
1921 0 : return -1;
1922 : }
1923 :
1924 : /* Call object.__init__(self) now. */
1925 : /* XXX Could call super(type, cls).__init__() but what's the point? */
1926 245 : args = PyTuple_GetSlice(args, 0, 0);
1927 245 : res = object_init(cls, args, NULL);
1928 245 : Py_DECREF(args);
1929 245 : return res;
1930 : }
1931 :
1932 : long
1933 0 : PyType_GetFlags(PyTypeObject *type)
1934 : {
1935 0 : return type->tp_flags;
1936 : }
1937 :
1938 : /* Determine the most derived metatype. */
1939 : PyTypeObject *
1940 362 : _PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
1941 : {
1942 : Py_ssize_t i, nbases;
1943 : PyTypeObject *winner;
1944 : PyObject *tmp;
1945 : PyTypeObject *tmptype;
1946 :
1947 : /* Determine the proper metatype to deal with this,
1948 : and check for metatype conflicts while we're at it.
1949 : Note that if some other metatype wins to contract,
1950 : it's possible that its instances are not types. */
1951 :
1952 362 : nbases = PyTuple_GET_SIZE(bases);
1953 362 : winner = metatype;
1954 702 : for (i = 0; i < nbases; i++) {
1955 340 : tmp = PyTuple_GET_ITEM(bases, i);
1956 340 : tmptype = Py_TYPE(tmp);
1957 340 : if (PyType_IsSubtype(winner, tmptype))
1958 337 : continue;
1959 3 : if (PyType_IsSubtype(tmptype, winner)) {
1960 3 : winner = tmptype;
1961 3 : continue;
1962 : }
1963 : /* else: */
1964 0 : PyErr_SetString(PyExc_TypeError,
1965 : "metaclass conflict: "
1966 : "the metaclass of a derived class "
1967 : "must be a (non-strict) subclass "
1968 : "of the metaclasses of all its bases");
1969 0 : return NULL;
1970 : }
1971 362 : return winner;
1972 : }
1973 :
1974 : static PyObject *
1975 618 : type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1976 : {
1977 618 : PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
1978 : static char *kwlist[] = {"name", "bases", "dict", 0};
1979 618 : PyObject *qualname, *slots = NULL, *tmp, *newslots;
1980 618 : PyTypeObject *type = NULL, *base, *tmptype, *winner;
1981 : PyHeapTypeObject *et;
1982 : PyMemberDef *mp;
1983 : Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
1984 : int j, may_add_dict, may_add_weak;
1985 : _Py_IDENTIFIER(__qualname__);
1986 : _Py_IDENTIFIER(__slots__);
1987 :
1988 : assert(args != NULL && PyTuple_Check(args));
1989 : assert(kwds == NULL || PyDict_Check(kwds));
1990 :
1991 : /* Special case: type(x) should return x->ob_type */
1992 : {
1993 618 : const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1994 618 : const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1995 :
1996 618 : if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1997 373 : PyObject *x = PyTuple_GET_ITEM(args, 0);
1998 373 : Py_INCREF(Py_TYPE(x));
1999 373 : return (PyObject *) Py_TYPE(x);
2000 : }
2001 :
2002 : /* SF bug 475327 -- if that didn't trigger, we need 3
2003 : arguments. but PyArg_ParseTupleAndKeywords below may give
2004 : a msg saying type() needs exactly 3. */
2005 245 : if (nargs + nkwds != 3) {
2006 0 : PyErr_SetString(PyExc_TypeError,
2007 : "type() takes 1 or 3 arguments");
2008 0 : return NULL;
2009 : }
2010 : }
2011 :
2012 : /* Check arguments: (name, bases, dict) */
2013 245 : if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
2014 : &name,
2015 : &PyTuple_Type, &bases,
2016 : &PyDict_Type, &orig_dict))
2017 0 : return NULL;
2018 :
2019 : /* Determine the proper metatype to deal with this: */
2020 245 : winner = _PyType_CalculateMetaclass(metatype, bases);
2021 245 : if (winner == NULL) {
2022 0 : return NULL;
2023 : }
2024 :
2025 245 : if (winner != metatype) {
2026 0 : if (winner->tp_new != type_new) /* Pass it to the winner */
2027 0 : return winner->tp_new(winner, args, kwds);
2028 0 : metatype = winner;
2029 : }
2030 :
2031 : /* Adjust for empty tuple bases */
2032 245 : nbases = PyTuple_GET_SIZE(bases);
2033 245 : if (nbases == 0) {
2034 45 : bases = PyTuple_Pack(1, &PyBaseObject_Type);
2035 45 : if (bases == NULL)
2036 0 : goto error;
2037 45 : nbases = 1;
2038 : }
2039 : else
2040 200 : Py_INCREF(bases);
2041 :
2042 : /* Calculate best base, and check that all bases are type objects */
2043 245 : base = best_base(bases);
2044 245 : if (base == NULL) {
2045 0 : goto error;
2046 : }
2047 245 : if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2048 0 : PyErr_Format(PyExc_TypeError,
2049 : "type '%.100s' is not an acceptable base type",
2050 : base->tp_name);
2051 0 : goto error;
2052 : }
2053 :
2054 245 : dict = PyDict_Copy(orig_dict);
2055 245 : if (dict == NULL)
2056 0 : goto error;
2057 :
2058 : /* Check for a __slots__ sequence variable in dict, and count it */
2059 245 : slots = _PyDict_GetItemId(dict, &PyId___slots__);
2060 245 : nslots = 0;
2061 245 : add_dict = 0;
2062 245 : add_weak = 0;
2063 245 : may_add_dict = base->tp_dictoffset == 0;
2064 245 : may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2065 245 : if (slots == NULL) {
2066 226 : if (may_add_dict) {
2067 61 : add_dict++;
2068 : }
2069 226 : if (may_add_weak) {
2070 91 : add_weak++;
2071 : }
2072 : }
2073 : else {
2074 : /* Have slots */
2075 :
2076 : /* Make it into a tuple */
2077 19 : if (PyUnicode_Check(slots))
2078 1 : slots = PyTuple_Pack(1, slots);
2079 : else
2080 18 : slots = PySequence_Tuple(slots);
2081 19 : if (slots == NULL)
2082 0 : goto error;
2083 : assert(PyTuple_Check(slots));
2084 :
2085 : /* Are slots allowed? */
2086 19 : nslots = PyTuple_GET_SIZE(slots);
2087 19 : if (nslots > 0 && base->tp_itemsize != 0) {
2088 0 : PyErr_Format(PyExc_TypeError,
2089 : "nonempty __slots__ "
2090 : "not supported for subtype of '%s'",
2091 : base->tp_name);
2092 0 : goto error;
2093 : }
2094 :
2095 : /* Check for valid slot names and two special cases */
2096 28 : for (i = 0; i < nslots; i++) {
2097 9 : PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2098 9 : if (!valid_identifier(tmp))
2099 0 : goto error;
2100 : assert(PyUnicode_Check(tmp));
2101 9 : if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
2102 0 : if (!may_add_dict || add_dict) {
2103 0 : PyErr_SetString(PyExc_TypeError,
2104 : "__dict__ slot disallowed: "
2105 : "we already got one");
2106 0 : goto error;
2107 : }
2108 0 : add_dict++;
2109 : }
2110 9 : if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
2111 2 : if (!may_add_weak || add_weak) {
2112 0 : PyErr_SetString(PyExc_TypeError,
2113 : "__weakref__ slot disallowed: "
2114 : "either we already got one, "
2115 : "or __itemsize__ != 0");
2116 0 : goto error;
2117 : }
2118 2 : add_weak++;
2119 : }
2120 : }
2121 :
2122 : /* Copy slots into a list, mangle names and sort them.
2123 : Sorted names are needed for __class__ assignment.
2124 : Convert them back to tuple at the end.
2125 : */
2126 19 : newslots = PyList_New(nslots - add_dict - add_weak);
2127 19 : if (newslots == NULL)
2128 0 : goto error;
2129 28 : for (i = j = 0; i < nslots; i++) {
2130 9 : tmp = PyTuple_GET_ITEM(slots, i);
2131 9 : if ((add_dict &&
2132 9 : PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2133 7 : (add_weak &&
2134 7 : PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
2135 2 : continue;
2136 7 : tmp =_Py_Mangle(name, tmp);
2137 7 : if (!tmp) {
2138 0 : Py_DECREF(newslots);
2139 0 : goto error;
2140 : }
2141 7 : PyList_SET_ITEM(newslots, j, tmp);
2142 7 : if (PyDict_GetItem(dict, tmp)) {
2143 0 : PyErr_Format(PyExc_ValueError,
2144 : "%R in __slots__ conflicts with class variable",
2145 : tmp);
2146 0 : Py_DECREF(newslots);
2147 0 : goto error;
2148 : }
2149 7 : j++;
2150 : }
2151 : assert(j == nslots - add_dict - add_weak);
2152 19 : nslots = j;
2153 19 : Py_CLEAR(slots);
2154 19 : if (PyList_Sort(newslots) == -1) {
2155 0 : Py_DECREF(newslots);
2156 0 : goto error;
2157 : }
2158 19 : slots = PyList_AsTuple(newslots);
2159 19 : Py_DECREF(newslots);
2160 19 : if (slots == NULL)
2161 0 : goto error;
2162 :
2163 : /* Secondary bases may provide weakrefs or dict */
2164 19 : if (nbases > 1 &&
2165 3 : ((may_add_dict && !add_dict) ||
2166 0 : (may_add_weak && !add_weak))) {
2167 12 : for (i = 0; i < nbases; i++) {
2168 9 : tmp = PyTuple_GET_ITEM(bases, i);
2169 9 : if (tmp == (PyObject *)base)
2170 3 : continue; /* Skip primary base */
2171 : assert(PyType_Check(tmp));
2172 6 : tmptype = (PyTypeObject *)tmp;
2173 12 : if (may_add_dict && !add_dict &&
2174 6 : tmptype->tp_dictoffset != 0)
2175 0 : add_dict++;
2176 12 : if (may_add_weak && !add_weak &&
2177 6 : tmptype->tp_weaklistoffset != 0)
2178 0 : add_weak++;
2179 6 : if (may_add_dict && !add_dict)
2180 6 : continue;
2181 0 : if (may_add_weak && !add_weak)
2182 0 : continue;
2183 : /* Nothing more to check */
2184 0 : break;
2185 : }
2186 : }
2187 : }
2188 :
2189 : /* Allocate the type object */
2190 245 : type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2191 245 : if (type == NULL)
2192 0 : goto error;
2193 :
2194 : /* Keep name and slots alive in the extended type object */
2195 245 : et = (PyHeapTypeObject *)type;
2196 245 : Py_INCREF(name);
2197 245 : et->ht_name = name;
2198 245 : et->ht_slots = slots;
2199 245 : slots = NULL;
2200 :
2201 : /* Initialize tp_flags */
2202 245 : type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2203 : Py_TPFLAGS_BASETYPE;
2204 245 : if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2205 174 : type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2206 :
2207 : /* Initialize essential fields */
2208 245 : type->tp_as_number = &et->as_number;
2209 245 : type->tp_as_sequence = &et->as_sequence;
2210 245 : type->tp_as_mapping = &et->as_mapping;
2211 245 : type->tp_as_buffer = &et->as_buffer;
2212 245 : type->tp_name = _PyUnicode_AsString(name);
2213 245 : if (!type->tp_name)
2214 0 : goto error;
2215 :
2216 : /* Set tp_base and tp_bases */
2217 245 : type->tp_bases = bases;
2218 245 : bases = NULL;
2219 245 : Py_INCREF(base);
2220 245 : type->tp_base = base;
2221 :
2222 : /* Initialize tp_dict from passed-in dict */
2223 245 : Py_INCREF(dict);
2224 245 : type->tp_dict = dict;
2225 :
2226 : /* Set __module__ in the dict */
2227 245 : if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
2228 18 : tmp = PyEval_GetGlobals();
2229 18 : if (tmp != NULL) {
2230 18 : tmp = _PyDict_GetItemId(tmp, &PyId___name__);
2231 18 : if (tmp != NULL) {
2232 18 : if (_PyDict_SetItemId(dict, &PyId___module__,
2233 : tmp) < 0)
2234 0 : goto error;
2235 : }
2236 : }
2237 : }
2238 :
2239 : /* Set ht_qualname to dict['__qualname__'] if available, else to
2240 : __name__. The __qualname__ accessor will look for ht_qualname.
2241 : */
2242 245 : qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
2243 245 : if (qualname != NULL) {
2244 117 : if (!PyUnicode_Check(qualname)) {
2245 0 : PyErr_Format(PyExc_TypeError,
2246 : "type __qualname__ must be a str, not %s",
2247 0 : Py_TYPE(qualname)->tp_name);
2248 0 : goto error;
2249 : }
2250 : }
2251 : else {
2252 128 : qualname = et->ht_name;
2253 : }
2254 245 : Py_INCREF(qualname);
2255 245 : et->ht_qualname = qualname;
2256 :
2257 : /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2258 : and is a string. The __doc__ accessor will first look for tp_doc;
2259 : if that fails, it will still look into __dict__.
2260 : */
2261 : {
2262 245 : PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
2263 245 : if (doc != NULL && PyUnicode_Check(doc)) {
2264 : Py_ssize_t len;
2265 : char *doc_str;
2266 : char *tp_doc;
2267 :
2268 54 : doc_str = _PyUnicode_AsString(doc);
2269 54 : if (doc_str == NULL)
2270 0 : goto error;
2271 : /* Silently truncate the docstring if it contains null bytes. */
2272 54 : len = strlen(doc_str);
2273 54 : tp_doc = (char *)PyObject_MALLOC(len + 1);
2274 54 : if (tp_doc == NULL)
2275 0 : goto error;
2276 54 : memcpy(tp_doc, doc_str, len + 1);
2277 54 : type->tp_doc = tp_doc;
2278 : }
2279 : }
2280 :
2281 : /* Special-case __new__: if it's a plain function,
2282 : make it a static function */
2283 245 : tmp = _PyDict_GetItemId(dict, &PyId___new__);
2284 245 : if (tmp != NULL && PyFunction_Check(tmp)) {
2285 6 : tmp = PyStaticMethod_New(tmp);
2286 6 : if (tmp == NULL)
2287 0 : goto error;
2288 6 : if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0)
2289 0 : goto error;
2290 6 : Py_DECREF(tmp);
2291 : }
2292 :
2293 : /* Add descriptors for custom slots from __slots__, or for __dict__ */
2294 245 : mp = PyHeapType_GET_MEMBERS(et);
2295 245 : slotoffset = base->tp_basicsize;
2296 245 : if (et->ht_slots != NULL) {
2297 26 : for (i = 0; i < nslots; i++, mp++) {
2298 7 : mp->name = _PyUnicode_AsString(
2299 7 : PyTuple_GET_ITEM(et->ht_slots, i));
2300 7 : if (mp->name == NULL)
2301 0 : goto error;
2302 7 : mp->type = T_OBJECT_EX;
2303 7 : mp->offset = slotoffset;
2304 :
2305 : /* __dict__ and __weakref__ are already filtered out */
2306 : assert(strcmp(mp->name, "__dict__") != 0);
2307 : assert(strcmp(mp->name, "__weakref__") != 0);
2308 :
2309 7 : slotoffset += sizeof(PyObject *);
2310 : }
2311 : }
2312 245 : if (add_dict) {
2313 61 : if (base->tp_itemsize)
2314 2 : type->tp_dictoffset = -(long)sizeof(PyObject *);
2315 : else
2316 59 : type->tp_dictoffset = slotoffset;
2317 61 : slotoffset += sizeof(PyObject *);
2318 : }
2319 245 : if (type->tp_dictoffset) {
2320 61 : et->ht_cached_keys = _PyDict_NewKeysForClass();
2321 : }
2322 245 : if (add_weak) {
2323 : assert(!base->tp_itemsize);
2324 93 : type->tp_weaklistoffset = slotoffset;
2325 93 : slotoffset += sizeof(PyObject *);
2326 : }
2327 245 : type->tp_basicsize = slotoffset;
2328 245 : type->tp_itemsize = base->tp_itemsize;
2329 245 : type->tp_members = PyHeapType_GET_MEMBERS(et);
2330 :
2331 245 : if (type->tp_weaklistoffset && type->tp_dictoffset)
2332 59 : type->tp_getset = subtype_getsets_full;
2333 186 : else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2334 34 : type->tp_getset = subtype_getsets_weakref_only;
2335 152 : else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2336 2 : type->tp_getset = subtype_getsets_dict_only;
2337 : else
2338 150 : type->tp_getset = NULL;
2339 :
2340 : /* Special case some slots */
2341 245 : if (type->tp_dictoffset != 0 || nslots > 0) {
2342 65 : if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2343 0 : type->tp_getattro = PyObject_GenericGetAttr;
2344 65 : if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2345 0 : type->tp_setattro = PyObject_GenericSetAttr;
2346 : }
2347 245 : type->tp_dealloc = subtype_dealloc;
2348 :
2349 : /* Enable GC unless there are really no instance variables possible */
2350 258 : if (!(type->tp_basicsize == sizeof(PyObject) &&
2351 13 : type->tp_itemsize == 0))
2352 232 : type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2353 :
2354 : /* Always override allocation strategy to use regular heap */
2355 245 : type->tp_alloc = PyType_GenericAlloc;
2356 245 : if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2357 232 : type->tp_free = PyObject_GC_Del;
2358 232 : type->tp_traverse = subtype_traverse;
2359 232 : type->tp_clear = subtype_clear;
2360 : }
2361 : else
2362 13 : type->tp_free = PyObject_Del;
2363 :
2364 : /* Initialize the rest */
2365 245 : if (PyType_Ready(type) < 0)
2366 0 : goto error;
2367 :
2368 : /* Put the proper slots in place */
2369 245 : fixup_slot_dispatchers(type);
2370 :
2371 245 : Py_DECREF(dict);
2372 245 : return (PyObject *)type;
2373 :
2374 : error:
2375 0 : Py_XDECREF(dict);
2376 0 : Py_XDECREF(bases);
2377 0 : Py_XDECREF(slots);
2378 0 : Py_XDECREF(type);
2379 0 : return NULL;
2380 : }
2381 :
2382 : static short slotoffsets[] = {
2383 : -1, /* invalid slot */
2384 : #include "typeslots.inc"
2385 : };
2386 :
2387 : PyObject *
2388 0 : PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
2389 : {
2390 0 : PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2391 : PyTypeObject *type, *base;
2392 : char *s;
2393 0 : char *res_start = (char*)res;
2394 : PyType_Slot *slot;
2395 :
2396 : /* Set the type name and qualname */
2397 0 : s = strrchr(spec->name, '.');
2398 0 : if (s == NULL)
2399 0 : s = (char*)spec->name;
2400 : else
2401 0 : s++;
2402 :
2403 0 : if (res == NULL)
2404 0 : return NULL;
2405 0 : type = &res->ht_type;
2406 : /* The flags must be initialized early, before the GC traverses us */
2407 0 : type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
2408 0 : res->ht_name = PyUnicode_FromString(s);
2409 0 : if (!res->ht_name)
2410 0 : goto fail;
2411 0 : res->ht_qualname = res->ht_name;
2412 0 : Py_INCREF(res->ht_qualname);
2413 0 : type->tp_name = spec->name;
2414 0 : if (!type->tp_name)
2415 0 : goto fail;
2416 :
2417 : /* Adjust for empty tuple bases */
2418 0 : if (!bases) {
2419 0 : base = &PyBaseObject_Type;
2420 : /* See whether Py_tp_base(s) was specified */
2421 0 : for (slot = spec->slots; slot->slot; slot++) {
2422 0 : if (slot->slot == Py_tp_base)
2423 0 : base = slot->pfunc;
2424 0 : else if (slot->slot == Py_tp_bases) {
2425 0 : bases = slot->pfunc;
2426 0 : Py_INCREF(bases);
2427 : }
2428 : }
2429 0 : if (!bases)
2430 0 : bases = PyTuple_Pack(1, base);
2431 0 : if (!bases)
2432 0 : goto fail;
2433 : }
2434 : else
2435 0 : Py_INCREF(bases);
2436 :
2437 : /* Calculate best base, and check that all bases are type objects */
2438 0 : base = best_base(bases);
2439 0 : if (base == NULL) {
2440 0 : goto fail;
2441 : }
2442 0 : if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2443 0 : PyErr_Format(PyExc_TypeError,
2444 : "type '%.100s' is not an acceptable base type",
2445 : base->tp_name);
2446 0 : goto fail;
2447 : }
2448 :
2449 : /* Initialize essential fields */
2450 0 : type->tp_as_number = &res->as_number;
2451 0 : type->tp_as_sequence = &res->as_sequence;
2452 0 : type->tp_as_mapping = &res->as_mapping;
2453 0 : type->tp_as_buffer = &res->as_buffer;
2454 : /* Set tp_base and tp_bases */
2455 0 : type->tp_bases = bases;
2456 0 : bases = NULL;
2457 0 : Py_INCREF(base);
2458 0 : type->tp_base = base;
2459 :
2460 0 : type->tp_basicsize = spec->basicsize;
2461 0 : type->tp_itemsize = spec->itemsize;
2462 :
2463 0 : for (slot = spec->slots; slot->slot; slot++) {
2464 0 : if (slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
2465 0 : PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2466 0 : goto fail;
2467 : }
2468 0 : if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2469 : /* Processed above */
2470 0 : continue;
2471 0 : *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
2472 :
2473 : /* need to make a copy of the docstring slot, which usually
2474 : points to a static string literal */
2475 0 : if (slot->slot == Py_tp_doc) {
2476 0 : size_t len = strlen(slot->pfunc)+1;
2477 0 : char *tp_doc = PyObject_MALLOC(len);
2478 0 : if (tp_doc == NULL)
2479 0 : goto fail;
2480 0 : memcpy(tp_doc, slot->pfunc, len);
2481 0 : type->tp_doc = tp_doc;
2482 : }
2483 : }
2484 0 : if (type->tp_dictoffset) {
2485 0 : res->ht_cached_keys = _PyDict_NewKeysForClass();
2486 : }
2487 0 : if (type->tp_dealloc == NULL) {
2488 : /* It's a heap type, so needs the heap types' dealloc.
2489 : subtype_dealloc will call the base type's tp_dealloc, if
2490 : necessary. */
2491 0 : type->tp_dealloc = subtype_dealloc;
2492 : }
2493 :
2494 0 : if (PyType_Ready(type) < 0)
2495 0 : goto fail;
2496 :
2497 : /* Set type.__module__ */
2498 0 : s = strrchr(spec->name, '.');
2499 0 : if (s != NULL)
2500 0 : _PyDict_SetItemId(type->tp_dict, &PyId___module__,
2501 : PyUnicode_FromStringAndSize(
2502 0 : spec->name, (Py_ssize_t)(s - spec->name)));
2503 :
2504 0 : return (PyObject*)res;
2505 :
2506 : fail:
2507 0 : Py_DECREF(res);
2508 0 : return NULL;
2509 : }
2510 :
2511 : PyObject *
2512 0 : PyType_FromSpec(PyType_Spec *spec)
2513 : {
2514 0 : return PyType_FromSpecWithBases(spec, NULL);
2515 : }
2516 :
2517 :
2518 : /* Internal API to look for a name through the MRO.
2519 : This returns a borrowed reference, and doesn't set an exception! */
2520 : PyObject *
2521 153971 : _PyType_Lookup(PyTypeObject *type, PyObject *name)
2522 : {
2523 : Py_ssize_t i, n;
2524 : PyObject *mro, *res, *base, *dict;
2525 : unsigned int h;
2526 :
2527 307942 : if (MCACHE_CACHEABLE_NAME(name) &&
2528 153971 : PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2529 : /* fast path */
2530 153600 : h = MCACHE_HASH_METHOD(type, name);
2531 285653 : if (method_cache[h].version == type->tp_version_tag &&
2532 132053 : method_cache[h].name == name)
2533 130342 : return method_cache[h].value;
2534 : }
2535 :
2536 : /* Look in tp_dict of types in MRO */
2537 23629 : mro = type->tp_mro;
2538 :
2539 : /* If mro is NULL, the type is either not yet initialized
2540 : by PyType_Ready(), or already cleared by type_clear().
2541 : Either way the safest thing to do is to return NULL. */
2542 23629 : if (mro == NULL)
2543 0 : return NULL;
2544 :
2545 23629 : res = NULL;
2546 : /* keep a strong reference to mro because type->tp_mro can be replaced
2547 : during PyDict_GetItem(dict, name) */
2548 23629 : Py_INCREF(mro);
2549 : assert(PyTuple_Check(mro));
2550 23629 : n = PyTuple_GET_SIZE(mro);
2551 92063 : for (i = 0; i < n; i++) {
2552 74781 : base = PyTuple_GET_ITEM(mro, i);
2553 : assert(PyType_Check(base));
2554 74781 : dict = ((PyTypeObject *)base)->tp_dict;
2555 : assert(dict && PyDict_Check(dict));
2556 74781 : res = PyDict_GetItem(dict, name);
2557 74781 : if (res != NULL)
2558 6347 : break;
2559 : }
2560 23629 : Py_DECREF(mro);
2561 :
2562 23629 : if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2563 23629 : h = MCACHE_HASH_METHOD(type, name);
2564 23629 : method_cache[h].version = type->tp_version_tag;
2565 23629 : method_cache[h].value = res; /* borrowed */
2566 23629 : Py_INCREF(name);
2567 23629 : Py_DECREF(method_cache[h].name);
2568 23629 : method_cache[h].name = name;
2569 : }
2570 23629 : return res;
2571 : }
2572 :
2573 : static PyObject *
2574 13313 : _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2575 : {
2576 : PyObject *oname;
2577 13313 : oname = _PyUnicode_FromId(name); /* borrowed */
2578 13313 : if (oname == NULL)
2579 0 : return NULL;
2580 13313 : return _PyType_Lookup(type, oname);
2581 : }
2582 :
2583 : /* This is similar to PyObject_GenericGetAttr(),
2584 : but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2585 : static PyObject *
2586 1637 : type_getattro(PyTypeObject *type, PyObject *name)
2587 : {
2588 1637 : PyTypeObject *metatype = Py_TYPE(type);
2589 : PyObject *meta_attribute, *attribute;
2590 : descrgetfunc meta_get;
2591 :
2592 1637 : if (!PyUnicode_Check(name)) {
2593 0 : PyErr_Format(PyExc_TypeError,
2594 : "attribute name must be string, not '%.200s'",
2595 0 : name->ob_type->tp_name);
2596 0 : return NULL;
2597 : }
2598 :
2599 : /* Initialize this type (we'll assume the metatype is initialized) */
2600 1637 : if (type->tp_dict == NULL) {
2601 14 : if (PyType_Ready(type) < 0)
2602 0 : return NULL;
2603 : }
2604 :
2605 : /* No readable descriptor found yet */
2606 1637 : meta_get = NULL;
2607 :
2608 : /* Look for the attribute in the metatype */
2609 1637 : meta_attribute = _PyType_Lookup(metatype, name);
2610 :
2611 1637 : if (meta_attribute != NULL) {
2612 385 : meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
2613 :
2614 385 : if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2615 : /* Data descriptors implement tp_descr_set to intercept
2616 : * writes. Assume the attribute is not overridden in
2617 : * type's tp_dict (and bases): call the descriptor now.
2618 : */
2619 142 : return meta_get(meta_attribute, (PyObject *)type,
2620 : (PyObject *)metatype);
2621 : }
2622 243 : Py_INCREF(meta_attribute);
2623 : }
2624 :
2625 : /* No data descriptor found on metatype. Look in tp_dict of this
2626 : * type and its bases */
2627 1495 : attribute = _PyType_Lookup(type, name);
2628 1495 : if (attribute != NULL) {
2629 : /* Implement descriptor functionality, if any */
2630 1401 : descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
2631 :
2632 1401 : Py_XDECREF(meta_attribute);
2633 :
2634 1401 : if (local_get != NULL) {
2635 : /* NULL 2nd argument indicates the descriptor was
2636 : * found on the target object itself (or a base) */
2637 942 : return local_get(attribute, (PyObject *)NULL,
2638 : (PyObject *)type);
2639 : }
2640 :
2641 459 : Py_INCREF(attribute);
2642 459 : return attribute;
2643 : }
2644 :
2645 : /* No attribute found in local __dict__ (or bases): use the
2646 : * descriptor from the metatype, if any */
2647 94 : if (meta_get != NULL) {
2648 : PyObject *res;
2649 56 : res = meta_get(meta_attribute, (PyObject *)type,
2650 : (PyObject *)metatype);
2651 56 : Py_DECREF(meta_attribute);
2652 56 : return res;
2653 : }
2654 :
2655 : /* If an ordinary attribute was found on the metatype, return it now */
2656 38 : if (meta_attribute != NULL) {
2657 0 : return meta_attribute;
2658 : }
2659 :
2660 : /* Give up */
2661 38 : PyErr_Format(PyExc_AttributeError,
2662 : "type object '%.50s' has no attribute '%U'",
2663 : type->tp_name, name);
2664 38 : return NULL;
2665 : }
2666 :
2667 : static int
2668 280 : type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2669 : {
2670 280 : if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2671 0 : PyErr_Format(
2672 : PyExc_TypeError,
2673 : "can't set attributes of built-in/extension type '%s'",
2674 : type->tp_name);
2675 0 : return -1;
2676 : }
2677 280 : if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2678 0 : return -1;
2679 280 : return update_slot(type, name);
2680 : }
2681 :
2682 : extern void
2683 : _PyDictKeys_DecRef(PyDictKeysObject *keys);
2684 :
2685 : static void
2686 0 : type_dealloc(PyTypeObject *type)
2687 : {
2688 : PyHeapTypeObject *et;
2689 :
2690 : /* Assert this is a heap-allocated type object */
2691 : assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2692 0 : _PyObject_GC_UNTRACK(type);
2693 0 : PyObject_ClearWeakRefs((PyObject *)type);
2694 0 : et = (PyHeapTypeObject *)type;
2695 0 : Py_XDECREF(type->tp_base);
2696 0 : Py_XDECREF(type->tp_dict);
2697 0 : Py_XDECREF(type->tp_bases);
2698 0 : Py_XDECREF(type->tp_mro);
2699 0 : Py_XDECREF(type->tp_cache);
2700 0 : Py_XDECREF(type->tp_subclasses);
2701 : /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2702 : * of most other objects. It's okay to cast it to char *.
2703 : */
2704 0 : PyObject_Free((char *)type->tp_doc);
2705 0 : Py_XDECREF(et->ht_name);
2706 0 : Py_XDECREF(et->ht_qualname);
2707 0 : Py_XDECREF(et->ht_slots);
2708 0 : if (et->ht_cached_keys)
2709 0 : _PyDictKeys_DecRef(et->ht_cached_keys);
2710 0 : Py_TYPE(type)->tp_free((PyObject *)type);
2711 0 : }
2712 :
2713 : static PyObject *
2714 22 : type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2715 : {
2716 : PyObject *list, *raw, *ref;
2717 : Py_ssize_t i, n;
2718 :
2719 22 : list = PyList_New(0);
2720 22 : if (list == NULL)
2721 0 : return NULL;
2722 22 : raw = type->tp_subclasses;
2723 22 : if (raw == NULL)
2724 22 : return list;
2725 : assert(PyList_Check(raw));
2726 0 : n = PyList_GET_SIZE(raw);
2727 0 : for (i = 0; i < n; i++) {
2728 0 : ref = PyList_GET_ITEM(raw, i);
2729 : assert(PyWeakref_CheckRef(ref));
2730 0 : ref = PyWeakref_GET_OBJECT(ref);
2731 0 : if (ref != Py_None) {
2732 0 : if (PyList_Append(list, ref) < 0) {
2733 0 : Py_DECREF(list);
2734 0 : return NULL;
2735 : }
2736 : }
2737 : }
2738 0 : return list;
2739 : }
2740 :
2741 : static PyObject *
2742 117 : type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2743 : {
2744 117 : return PyDict_New();
2745 : }
2746 :
2747 : /*
2748 : Merge the __dict__ of aclass into dict, and recursively also all
2749 : the __dict__s of aclass's base classes. The order of merging isn't
2750 : defined, as it's expected that only the final set of dict keys is
2751 : interesting.
2752 : Return 0 on success, -1 on error.
2753 : */
2754 :
2755 : static int
2756 0 : merge_class_dict(PyObject *dict, PyObject *aclass)
2757 : {
2758 : PyObject *classdict;
2759 : PyObject *bases;
2760 : _Py_IDENTIFIER(__bases__);
2761 :
2762 : assert(PyDict_Check(dict));
2763 : assert(aclass);
2764 :
2765 : /* Merge in the type's dict (if any). */
2766 0 : classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
2767 0 : if (classdict == NULL)
2768 0 : PyErr_Clear();
2769 : else {
2770 0 : int status = PyDict_Update(dict, classdict);
2771 0 : Py_DECREF(classdict);
2772 0 : if (status < 0)
2773 0 : return -1;
2774 : }
2775 :
2776 : /* Recursively merge in the base types' (if any) dicts. */
2777 0 : bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
2778 0 : if (bases == NULL)
2779 0 : PyErr_Clear();
2780 : else {
2781 : /* We have no guarantee that bases is a real tuple */
2782 : Py_ssize_t i, n;
2783 0 : n = PySequence_Size(bases); /* This better be right */
2784 0 : if (n < 0)
2785 0 : PyErr_Clear();
2786 : else {
2787 0 : for (i = 0; i < n; i++) {
2788 : int status;
2789 0 : PyObject *base = PySequence_GetItem(bases, i);
2790 0 : if (base == NULL) {
2791 0 : Py_DECREF(bases);
2792 0 : return -1;
2793 : }
2794 0 : status = merge_class_dict(dict, base);
2795 0 : Py_DECREF(base);
2796 0 : if (status < 0) {
2797 0 : Py_DECREF(bases);
2798 0 : return -1;
2799 : }
2800 : }
2801 : }
2802 0 : Py_DECREF(bases);
2803 : }
2804 0 : return 0;
2805 : }
2806 :
2807 : /* __dir__ for type objects: returns __dict__ and __bases__.
2808 : We deliberately don't suck up its __class__, as methods belonging to the
2809 : metaclass would probably be more confusing than helpful.
2810 : */
2811 : static PyObject *
2812 0 : type_dir(PyObject *self, PyObject *args)
2813 : {
2814 0 : PyObject *result = NULL;
2815 0 : PyObject *dict = PyDict_New();
2816 :
2817 0 : if (dict != NULL && merge_class_dict(dict, self) == 0)
2818 0 : result = PyDict_Keys(dict);
2819 :
2820 0 : Py_XDECREF(dict);
2821 0 : return result;
2822 : }
2823 :
2824 : static PyObject*
2825 0 : type_sizeof(PyObject *self, PyObject *args_unused)
2826 : {
2827 : Py_ssize_t size;
2828 0 : PyTypeObject *type = (PyTypeObject*)self;
2829 0 : if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
2830 0 : PyHeapTypeObject* et = (PyHeapTypeObject*)type;
2831 0 : size = sizeof(PyHeapTypeObject);
2832 0 : if (et->ht_cached_keys)
2833 0 : size += _PyDict_KeysSize(et->ht_cached_keys);
2834 : }
2835 : else
2836 0 : size = sizeof(PyTypeObject);
2837 0 : return PyLong_FromSsize_t(size);
2838 : }
2839 :
2840 : static PyMethodDef type_methods[] = {
2841 : {"mro", (PyCFunction)mro_external, METH_NOARGS,
2842 : PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2843 : {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2844 : PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2845 : {"__prepare__", (PyCFunction)type_prepare,
2846 : METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2847 : PyDoc_STR("__prepare__() -> dict\n"
2848 : "used to create the namespace for the class statement")},
2849 : {"__instancecheck__", type___instancecheck__, METH_O,
2850 : PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
2851 : {"__subclasscheck__", type___subclasscheck__, METH_O,
2852 : PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
2853 : {"__dir__", type_dir, METH_NOARGS,
2854 : PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
2855 : {"__sizeof__", type_sizeof, METH_NOARGS,
2856 : "__sizeof__() -> int\nreturn memory consumption of the type object"},
2857 : {0}
2858 : };
2859 :
2860 : PyDoc_STRVAR(type_doc,
2861 : "type(object) -> the object's type\n"
2862 : "type(name, bases, dict) -> a new type");
2863 :
2864 : static int
2865 646 : type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2866 : {
2867 : /* Because of type_is_gc(), the collector only calls this
2868 : for heaptypes. */
2869 646 : if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2870 : char msg[200];
2871 0 : sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
2872 : type->tp_name);
2873 0 : Py_FatalError(msg);
2874 : }
2875 :
2876 646 : Py_VISIT(type->tp_dict);
2877 646 : Py_VISIT(type->tp_cache);
2878 646 : Py_VISIT(type->tp_mro);
2879 646 : Py_VISIT(type->tp_bases);
2880 646 : Py_VISIT(type->tp_base);
2881 :
2882 : /* There's no need to visit type->tp_subclasses or
2883 : ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2884 : in cycles; tp_subclasses is a list of weak references,
2885 : and slots is a tuple of strings. */
2886 :
2887 646 : return 0;
2888 : }
2889 :
2890 : static int
2891 0 : type_clear(PyTypeObject *type)
2892 : {
2893 : PyDictKeysObject *cached_keys;
2894 : /* Because of type_is_gc(), the collector only calls this
2895 : for heaptypes. */
2896 : assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2897 :
2898 : /* We need to invalidate the method cache carefully before clearing
2899 : the dict, so that other objects caught in a reference cycle
2900 : don't start calling destroyed methods.
2901 :
2902 : Otherwise, the only field we need to clear is tp_mro, which is
2903 : part of a hard cycle (its first element is the class itself) that
2904 : won't be broken otherwise (it's a tuple and tuples don't have a
2905 : tp_clear handler). None of the other fields need to be
2906 : cleared, and here's why:
2907 :
2908 : tp_cache:
2909 : Not used; if it were, it would be a dict.
2910 :
2911 : tp_bases, tp_base:
2912 : If these are involved in a cycle, there must be at least
2913 : one other, mutable object in the cycle, e.g. a base
2914 : class's dict; the cycle will be broken that way.
2915 :
2916 : tp_subclasses:
2917 : A list of weak references can't be part of a cycle; and
2918 : lists have their own tp_clear.
2919 :
2920 : slots (in PyHeapTypeObject):
2921 : A tuple of strings can't be part of a cycle.
2922 : */
2923 :
2924 0 : PyType_Modified(type);
2925 0 : cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
2926 0 : if (cached_keys != NULL) {
2927 0 : ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
2928 0 : _PyDictKeys_DecRef(cached_keys);
2929 : }
2930 0 : if (type->tp_dict)
2931 0 : PyDict_Clear(type->tp_dict);
2932 0 : Py_CLEAR(type->tp_mro);
2933 :
2934 0 : return 0;
2935 : }
2936 :
2937 : static int
2938 18324 : type_is_gc(PyTypeObject *type)
2939 : {
2940 18324 : return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2941 : }
2942 :
2943 : PyTypeObject PyType_Type = {
2944 : PyVarObject_HEAD_INIT(&PyType_Type, 0)
2945 : "type", /* tp_name */
2946 : sizeof(PyHeapTypeObject), /* tp_basicsize */
2947 : sizeof(PyMemberDef), /* tp_itemsize */
2948 : (destructor)type_dealloc, /* tp_dealloc */
2949 : 0, /* tp_print */
2950 : 0, /* tp_getattr */
2951 : 0, /* tp_setattr */
2952 : 0, /* tp_reserved */
2953 : (reprfunc)type_repr, /* tp_repr */
2954 : 0, /* tp_as_number */
2955 : 0, /* tp_as_sequence */
2956 : 0, /* tp_as_mapping */
2957 : 0, /* tp_hash */
2958 : (ternaryfunc)type_call, /* tp_call */
2959 : 0, /* tp_str */
2960 : (getattrofunc)type_getattro, /* tp_getattro */
2961 : (setattrofunc)type_setattro, /* tp_setattro */
2962 : 0, /* tp_as_buffer */
2963 : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2964 : Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2965 : type_doc, /* tp_doc */
2966 : (traverseproc)type_traverse, /* tp_traverse */
2967 : (inquiry)type_clear, /* tp_clear */
2968 : 0, /* tp_richcompare */
2969 : offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2970 : 0, /* tp_iter */
2971 : 0, /* tp_iternext */
2972 : type_methods, /* tp_methods */
2973 : type_members, /* tp_members */
2974 : type_getsets, /* tp_getset */
2975 : 0, /* tp_base */
2976 : 0, /* tp_dict */
2977 : 0, /* tp_descr_get */
2978 : 0, /* tp_descr_set */
2979 : offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2980 : type_init, /* tp_init */
2981 : 0, /* tp_alloc */
2982 : type_new, /* tp_new */
2983 : PyObject_GC_Del, /* tp_free */
2984 : (inquiry)type_is_gc, /* tp_is_gc */
2985 : };
2986 :
2987 :
2988 : /* The base type of all types (eventually)... except itself. */
2989 :
2990 : /* You may wonder why object.__new__() only complains about arguments
2991 : when object.__init__() is not overridden, and vice versa.
2992 :
2993 : Consider the use cases:
2994 :
2995 : 1. When neither is overridden, we want to hear complaints about
2996 : excess (i.e., any) arguments, since their presence could
2997 : indicate there's a bug.
2998 :
2999 : 2. When defining an Immutable type, we are likely to override only
3000 : __new__(), since __init__() is called too late to initialize an
3001 : Immutable object. Since __new__() defines the signature for the
3002 : type, it would be a pain to have to override __init__() just to
3003 : stop it from complaining about excess arguments.
3004 :
3005 : 3. When defining a Mutable type, we are likely to override only
3006 : __init__(). So here the converse reasoning applies: we don't
3007 : want to have to override __new__() just to stop it from
3008 : complaining.
3009 :
3010 : 4. When __init__() is overridden, and the subclass __init__() calls
3011 : object.__init__(), the latter should complain about excess
3012 : arguments; ditto for __new__().
3013 :
3014 : Use cases 2 and 3 make it unattractive to unconditionally check for
3015 : excess arguments. The best solution that addresses all four use
3016 : cases is as follows: __init__() complains about excess arguments
3017 : unless __new__() is overridden and __init__() is not overridden
3018 : (IOW, if __init__() is overridden or __new__() is not overridden);
3019 : symmetrically, __new__() complains about excess arguments unless
3020 : __init__() is overridden and __new__() is not overridden
3021 : (IOW, if __new__() is overridden or __init__() is not overridden).
3022 :
3023 : However, for backwards compatibility, this breaks too much code.
3024 : Therefore, in 2.6, we'll *warn* about excess arguments when both
3025 : methods are overridden; for all other cases we'll use the above
3026 : rules.
3027 :
3028 : */
3029 :
3030 : /* Forward */
3031 : static PyObject *
3032 : object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3033 :
3034 : static int
3035 17298 : excess_args(PyObject *args, PyObject *kwds)
3036 : {
3037 33691 : return PyTuple_GET_SIZE(args) ||
3038 31 : (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
3039 : }
3040 :
3041 : static int
3042 15770 : object_init(PyObject *self, PyObject *args, PyObject *kwds)
3043 : {
3044 15770 : int err = 0;
3045 15770 : PyTypeObject *type = Py_TYPE(self);
3046 31067 : if (excess_args(args, kwds) &&
3047 30594 : (type->tp_new == object_new || type->tp_init != object_init)) {
3048 0 : PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3049 0 : err = -1;
3050 : }
3051 15770 : return err;
3052 : }
3053 :
3054 : static PyObject *
3055 1528 : object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3056 : {
3057 2624 : if (excess_args(args, kwds) &&
3058 2192 : (type->tp_init == object_init || type->tp_new != object_new)) {
3059 0 : PyErr_SetString(PyExc_TypeError, "object.__new__() takes no parameters");
3060 0 : return NULL;
3061 : }
3062 :
3063 1528 : if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
3064 0 : PyObject *abstract_methods = NULL;
3065 : PyObject *builtins;
3066 : PyObject *sorted;
3067 0 : PyObject *sorted_methods = NULL;
3068 0 : PyObject *joined = NULL;
3069 : PyObject *comma;
3070 : _Py_static_string(comma_id, ", ");
3071 : _Py_IDENTIFIER(sorted);
3072 :
3073 : /* Compute ", ".join(sorted(type.__abstractmethods__))
3074 : into joined. */
3075 0 : abstract_methods = type_abstractmethods(type, NULL);
3076 0 : if (abstract_methods == NULL)
3077 0 : goto error;
3078 0 : builtins = PyEval_GetBuiltins();
3079 0 : if (builtins == NULL)
3080 0 : goto error;
3081 0 : sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
3082 0 : if (sorted == NULL)
3083 0 : goto error;
3084 0 : sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3085 : abstract_methods,
3086 : NULL);
3087 0 : if (sorted_methods == NULL)
3088 0 : goto error;
3089 0 : comma = _PyUnicode_FromId(&comma_id);
3090 0 : if (comma == NULL)
3091 0 : goto error;
3092 0 : joined = PyUnicode_Join(comma, sorted_methods);
3093 0 : if (joined == NULL)
3094 0 : goto error;
3095 :
3096 0 : PyErr_Format(PyExc_TypeError,
3097 : "Can't instantiate abstract class %s "
3098 : "with abstract methods %U",
3099 : type->tp_name,
3100 : joined);
3101 : error:
3102 0 : Py_XDECREF(joined);
3103 0 : Py_XDECREF(sorted_methods);
3104 0 : Py_XDECREF(abstract_methods);
3105 0 : return NULL;
3106 : }
3107 1528 : return type->tp_alloc(type, 0);
3108 : }
3109 :
3110 : static void
3111 1333 : object_dealloc(PyObject *self)
3112 : {
3113 1333 : Py_TYPE(self)->tp_free(self);
3114 1333 : }
3115 :
3116 : static PyObject *
3117 1890 : object_repr(PyObject *self)
3118 : {
3119 : PyTypeObject *type;
3120 : PyObject *mod, *name, *rtn;
3121 :
3122 1890 : type = Py_TYPE(self);
3123 1890 : mod = type_module(type, NULL);
3124 1890 : if (mod == NULL)
3125 0 : PyErr_Clear();
3126 1890 : else if (!PyUnicode_Check(mod)) {
3127 0 : Py_DECREF(mod);
3128 0 : mod = NULL;
3129 : }
3130 1890 : name = type_qualname(type, NULL);
3131 1890 : if (name == NULL)
3132 0 : return NULL;
3133 1890 : if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
3134 1890 : rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3135 : else
3136 0 : rtn = PyUnicode_FromFormat("<%s object at %p>",
3137 : type->tp_name, self);
3138 1890 : Py_XDECREF(mod);
3139 1890 : Py_DECREF(name);
3140 1890 : return rtn;
3141 : }
3142 :
3143 : static PyObject *
3144 1890 : object_str(PyObject *self)
3145 : {
3146 : unaryfunc f;
3147 :
3148 1890 : f = Py_TYPE(self)->tp_repr;
3149 1890 : if (f == NULL)
3150 0 : f = object_repr;
3151 1890 : return f(self);
3152 : }
3153 :
3154 : static PyObject *
3155 333 : object_richcompare(PyObject *self, PyObject *other, int op)
3156 : {
3157 : PyObject *res;
3158 :
3159 333 : switch (op) {
3160 :
3161 : case Py_EQ:
3162 : /* Return NotImplemented instead of False, so if two
3163 : objects are compared, both get a chance at the
3164 : comparison. See issue #1393. */
3165 330 : res = (self == other) ? Py_True : Py_NotImplemented;
3166 330 : Py_INCREF(res);
3167 330 : break;
3168 :
3169 : case Py_NE:
3170 : /* By default, != returns the opposite of ==,
3171 : unless the latter returns NotImplemented. */
3172 3 : res = PyObject_RichCompare(self, other, Py_EQ);
3173 3 : if (res != NULL && res != Py_NotImplemented) {
3174 3 : int ok = PyObject_IsTrue(res);
3175 3 : Py_DECREF(res);
3176 3 : if (ok < 0)
3177 0 : res = NULL;
3178 : else {
3179 3 : if (ok)
3180 0 : res = Py_False;
3181 : else
3182 3 : res = Py_True;
3183 3 : Py_INCREF(res);
3184 : }
3185 : }
3186 3 : break;
3187 :
3188 : default:
3189 0 : res = Py_NotImplemented;
3190 0 : Py_INCREF(res);
3191 0 : break;
3192 : }
3193 :
3194 333 : return res;
3195 : }
3196 :
3197 : static PyObject *
3198 3386 : object_get_class(PyObject *self, void *closure)
3199 : {
3200 3386 : Py_INCREF(Py_TYPE(self));
3201 3386 : return (PyObject *)(Py_TYPE(self));
3202 : }
3203 :
3204 : static int
3205 0 : equiv_structs(PyTypeObject *a, PyTypeObject *b)
3206 : {
3207 0 : return a == b ||
3208 0 : (a != NULL &&
3209 0 : b != NULL &&
3210 0 : a->tp_basicsize == b->tp_basicsize &&
3211 0 : a->tp_itemsize == b->tp_itemsize &&
3212 0 : a->tp_dictoffset == b->tp_dictoffset &&
3213 0 : a->tp_weaklistoffset == b->tp_weaklistoffset &&
3214 0 : ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3215 0 : (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
3216 : }
3217 :
3218 : static int
3219 0 : same_slots_added(PyTypeObject *a, PyTypeObject *b)
3220 : {
3221 0 : PyTypeObject *base = a->tp_base;
3222 : Py_ssize_t size;
3223 : PyObject *slots_a, *slots_b;
3224 :
3225 : assert(base == b->tp_base);
3226 0 : size = base->tp_basicsize;
3227 0 : if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3228 0 : size += sizeof(PyObject *);
3229 0 : if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3230 0 : size += sizeof(PyObject *);
3231 :
3232 : /* Check slots compliance */
3233 0 : slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3234 0 : slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3235 0 : if (slots_a && slots_b) {
3236 0 : if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3237 0 : return 0;
3238 0 : size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3239 : }
3240 0 : return size == a->tp_basicsize && size == b->tp_basicsize;
3241 : }
3242 :
3243 : static int
3244 0 : compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
3245 : {
3246 : PyTypeObject *newbase, *oldbase;
3247 :
3248 0 : if (newto->tp_dealloc != oldto->tp_dealloc ||
3249 0 : newto->tp_free != oldto->tp_free)
3250 : {
3251 0 : PyErr_Format(PyExc_TypeError,
3252 : "%s assignment: "
3253 : "'%s' deallocator differs from '%s'",
3254 : attr,
3255 : newto->tp_name,
3256 : oldto->tp_name);
3257 0 : return 0;
3258 : }
3259 0 : newbase = newto;
3260 0 : oldbase = oldto;
3261 0 : while (equiv_structs(newbase, newbase->tp_base))
3262 0 : newbase = newbase->tp_base;
3263 0 : while (equiv_structs(oldbase, oldbase->tp_base))
3264 0 : oldbase = oldbase->tp_base;
3265 0 : if (newbase != oldbase &&
3266 0 : (newbase->tp_base != oldbase->tp_base ||
3267 0 : !same_slots_added(newbase, oldbase))) {
3268 0 : PyErr_Format(PyExc_TypeError,
3269 : "%s assignment: "
3270 : "'%s' object layout differs from '%s'",
3271 : attr,
3272 : newto->tp_name,
3273 : oldto->tp_name);
3274 0 : return 0;
3275 : }
3276 :
3277 0 : return 1;
3278 : }
3279 :
3280 : static int
3281 0 : object_set_class(PyObject *self, PyObject *value, void *closure)
3282 : {
3283 0 : PyTypeObject *oldto = Py_TYPE(self);
3284 : PyTypeObject *newto;
3285 :
3286 0 : if (value == NULL) {
3287 0 : PyErr_SetString(PyExc_TypeError,
3288 : "can't delete __class__ attribute");
3289 0 : return -1;
3290 : }
3291 0 : if (!PyType_Check(value)) {
3292 0 : PyErr_Format(PyExc_TypeError,
3293 : "__class__ must be set to a class, not '%s' object",
3294 0 : Py_TYPE(value)->tp_name);
3295 0 : return -1;
3296 : }
3297 0 : newto = (PyTypeObject *)value;
3298 0 : if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3299 0 : !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3300 : {
3301 0 : PyErr_Format(PyExc_TypeError,
3302 : "__class__ assignment: only for heap types");
3303 0 : return -1;
3304 : }
3305 0 : if (compatible_for_assignment(newto, oldto, "__class__")) {
3306 0 : Py_INCREF(newto);
3307 0 : Py_TYPE(self) = newto;
3308 0 : Py_DECREF(oldto);
3309 0 : return 0;
3310 : }
3311 : else {
3312 0 : return -1;
3313 : }
3314 : }
3315 :
3316 : static PyGetSetDef object_getsets[] = {
3317 : {"__class__", object_get_class, object_set_class,
3318 : PyDoc_STR("the object's class")},
3319 : {0}
3320 : };
3321 :
3322 :
3323 : /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3324 : We fall back to helpers in copyreg for:
3325 : - pickle protocols < 2
3326 : - calculating the list of slot names (done only once per class)
3327 : - the __newobj__ function (which is used as a token but never called)
3328 : */
3329 :
3330 : static PyObject *
3331 0 : import_copyreg(void)
3332 : {
3333 : static PyObject *copyreg_str;
3334 : static PyObject *mod_copyreg = NULL;
3335 :
3336 0 : if (!copyreg_str) {
3337 0 : copyreg_str = PyUnicode_InternFromString("copyreg");
3338 0 : if (copyreg_str == NULL)
3339 0 : return NULL;
3340 : }
3341 0 : if (!mod_copyreg) {
3342 0 : mod_copyreg = PyImport_Import(copyreg_str);
3343 : }
3344 :
3345 0 : Py_XINCREF(mod_copyreg);
3346 0 : return mod_copyreg;
3347 : }
3348 :
3349 : static PyObject *
3350 0 : slotnames(PyObject *cls)
3351 : {
3352 : PyObject *clsdict;
3353 : PyObject *copyreg;
3354 : PyObject *slotnames;
3355 : _Py_IDENTIFIER(__slotnames__);
3356 : _Py_IDENTIFIER(_slotnames);
3357 :
3358 0 : clsdict = ((PyTypeObject *)cls)->tp_dict;
3359 0 : slotnames = _PyDict_GetItemId(clsdict, &PyId___slotnames__);
3360 0 : if (slotnames != NULL && PyList_Check(slotnames)) {
3361 0 : Py_INCREF(slotnames);
3362 0 : return slotnames;
3363 : }
3364 :
3365 0 : copyreg = import_copyreg();
3366 0 : if (copyreg == NULL)
3367 0 : return NULL;
3368 :
3369 0 : slotnames = _PyObject_CallMethodId(copyreg, &PyId__slotnames, "O", cls);
3370 0 : Py_DECREF(copyreg);
3371 0 : if (slotnames != NULL &&
3372 0 : slotnames != Py_None &&
3373 0 : !PyList_Check(slotnames))
3374 : {
3375 0 : PyErr_SetString(PyExc_TypeError,
3376 : "copyreg._slotnames didn't return a list or None");
3377 0 : Py_DECREF(slotnames);
3378 0 : slotnames = NULL;
3379 : }
3380 :
3381 0 : return slotnames;
3382 : }
3383 :
3384 : static PyObject *
3385 0 : reduce_2(PyObject *obj)
3386 : {
3387 : PyObject *cls, *getnewargs;
3388 0 : PyObject *args = NULL, *args2 = NULL;
3389 0 : PyObject *getstate = NULL, *state = NULL, *names = NULL;
3390 0 : PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3391 0 : PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3392 : Py_ssize_t i, n;
3393 : _Py_IDENTIFIER(__getnewargs__);
3394 : _Py_IDENTIFIER(__getstate__);
3395 : _Py_IDENTIFIER(__newobj__);
3396 :
3397 0 : cls = (PyObject *) Py_TYPE(obj);
3398 :
3399 0 : getnewargs = _PyObject_GetAttrId(obj, &PyId___getnewargs__);
3400 0 : if (getnewargs != NULL) {
3401 0 : args = PyObject_CallObject(getnewargs, NULL);
3402 0 : Py_DECREF(getnewargs);
3403 0 : if (args != NULL && !PyTuple_Check(args)) {
3404 0 : PyErr_Format(PyExc_TypeError,
3405 : "__getnewargs__ should return a tuple, "
3406 0 : "not '%.200s'", Py_TYPE(args)->tp_name);
3407 0 : goto end;
3408 : }
3409 : }
3410 : else {
3411 0 : PyErr_Clear();
3412 0 : args = PyTuple_New(0);
3413 : }
3414 0 : if (args == NULL)
3415 0 : goto end;
3416 :
3417 0 : getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
3418 0 : if (getstate != NULL) {
3419 0 : state = PyObject_CallObject(getstate, NULL);
3420 0 : Py_DECREF(getstate);
3421 0 : if (state == NULL)
3422 0 : goto end;
3423 : }
3424 : else {
3425 : PyObject **dict;
3426 0 : PyErr_Clear();
3427 0 : dict = _PyObject_GetDictPtr(obj);
3428 0 : if (dict && *dict)
3429 0 : state = *dict;
3430 : else
3431 0 : state = Py_None;
3432 0 : Py_INCREF(state);
3433 0 : names = slotnames(cls);
3434 0 : if (names == NULL)
3435 0 : goto end;
3436 0 : if (names != Py_None && PyList_GET_SIZE(names) > 0) {
3437 : assert(PyList_Check(names));
3438 0 : slots = PyDict_New();
3439 0 : if (slots == NULL)
3440 0 : goto end;
3441 0 : n = 0;
3442 : /* Can't pre-compute the list size; the list
3443 : is stored on the class so accessible to other
3444 : threads, which may be run by DECREF */
3445 0 : for (i = 0; i < PyList_GET_SIZE(names); i++) {
3446 : PyObject *name, *value;
3447 0 : name = PyList_GET_ITEM(names, i);
3448 0 : value = PyObject_GetAttr(obj, name);
3449 0 : if (value == NULL)
3450 0 : PyErr_Clear();
3451 : else {
3452 0 : int err = PyDict_SetItem(slots, name,
3453 : value);
3454 0 : Py_DECREF(value);
3455 0 : if (err)
3456 0 : goto end;
3457 0 : n++;
3458 : }
3459 : }
3460 0 : if (n) {
3461 0 : state = Py_BuildValue("(NO)", state, slots);
3462 0 : if (state == NULL)
3463 0 : goto end;
3464 : }
3465 : }
3466 : }
3467 :
3468 0 : if (!PyList_Check(obj)) {
3469 0 : listitems = Py_None;
3470 0 : Py_INCREF(listitems);
3471 : }
3472 : else {
3473 0 : listitems = PyObject_GetIter(obj);
3474 0 : if (listitems == NULL)
3475 0 : goto end;
3476 : }
3477 :
3478 0 : if (!PyDict_Check(obj)) {
3479 0 : dictitems = Py_None;
3480 0 : Py_INCREF(dictitems);
3481 : }
3482 : else {
3483 : _Py_IDENTIFIER(items);
3484 0 : PyObject *items = _PyObject_CallMethodId(obj, &PyId_items, "");
3485 0 : if (items == NULL)
3486 0 : goto end;
3487 0 : dictitems = PyObject_GetIter(items);
3488 0 : Py_DECREF(items);
3489 0 : if (dictitems == NULL)
3490 0 : goto end;
3491 : }
3492 :
3493 0 : copyreg = import_copyreg();
3494 0 : if (copyreg == NULL)
3495 0 : goto end;
3496 0 : newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
3497 0 : if (newobj == NULL)
3498 0 : goto end;
3499 :
3500 0 : n = PyTuple_GET_SIZE(args);
3501 0 : args2 = PyTuple_New(n+1);
3502 0 : if (args2 == NULL)
3503 0 : goto end;
3504 0 : Py_INCREF(cls);
3505 0 : PyTuple_SET_ITEM(args2, 0, cls);
3506 0 : for (i = 0; i < n; i++) {
3507 0 : PyObject *v = PyTuple_GET_ITEM(args, i);
3508 0 : Py_INCREF(v);
3509 0 : PyTuple_SET_ITEM(args2, i+1, v);
3510 : }
3511 :
3512 0 : res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
3513 :
3514 : end:
3515 0 : Py_XDECREF(args);
3516 0 : Py_XDECREF(args2);
3517 0 : Py_XDECREF(slots);
3518 0 : Py_XDECREF(state);
3519 0 : Py_XDECREF(names);
3520 0 : Py_XDECREF(listitems);
3521 0 : Py_XDECREF(dictitems);
3522 0 : Py_XDECREF(copyreg);
3523 0 : Py_XDECREF(newobj);
3524 0 : return res;
3525 : }
3526 :
3527 : /*
3528 : * There were two problems when object.__reduce__ and object.__reduce_ex__
3529 : * were implemented in the same function:
3530 : * - trying to pickle an object with a custom __reduce__ method that
3531 : * fell back to object.__reduce__ in certain circumstances led to
3532 : * infinite recursion at Python level and eventual RuntimeError.
3533 : * - Pickling objects that lied about their type by overwriting the
3534 : * __class__ descriptor could lead to infinite recursion at C level
3535 : * and eventual segfault.
3536 : *
3537 : * Because of backwards compatibility, the two methods still have to
3538 : * behave in the same way, even if this is not required by the pickle
3539 : * protocol. This common functionality was moved to the _common_reduce
3540 : * function.
3541 : */
3542 : static PyObject *
3543 0 : _common_reduce(PyObject *self, int proto)
3544 : {
3545 : PyObject *copyreg, *res;
3546 :
3547 0 : if (proto >= 2)
3548 0 : return reduce_2(self);
3549 :
3550 0 : copyreg = import_copyreg();
3551 0 : if (!copyreg)
3552 0 : return NULL;
3553 :
3554 0 : res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3555 0 : Py_DECREF(copyreg);
3556 :
3557 0 : return res;
3558 : }
3559 :
3560 : static PyObject *
3561 0 : object_reduce(PyObject *self, PyObject *args)
3562 : {
3563 0 : int proto = 0;
3564 :
3565 0 : if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3566 0 : return NULL;
3567 :
3568 0 : return _common_reduce(self, proto);
3569 : }
3570 :
3571 : static PyObject *
3572 0 : object_reduce_ex(PyObject *self, PyObject *args)
3573 : {
3574 : static PyObject *objreduce;
3575 : PyObject *reduce, *res;
3576 0 : int proto = 0;
3577 : _Py_IDENTIFIER(__reduce__);
3578 :
3579 0 : if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3580 0 : return NULL;
3581 :
3582 0 : if (objreduce == NULL) {
3583 0 : objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
3584 : &PyId___reduce__);
3585 0 : if (objreduce == NULL)
3586 0 : return NULL;
3587 : }
3588 :
3589 0 : reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
3590 0 : if (reduce == NULL)
3591 0 : PyErr_Clear();
3592 : else {
3593 : PyObject *cls, *clsreduce;
3594 : int override;
3595 :
3596 0 : cls = (PyObject *) Py_TYPE(self);
3597 0 : clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
3598 0 : if (clsreduce == NULL) {
3599 0 : Py_DECREF(reduce);
3600 0 : return NULL;
3601 : }
3602 0 : override = (clsreduce != objreduce);
3603 0 : Py_DECREF(clsreduce);
3604 0 : if (override) {
3605 0 : res = PyObject_CallObject(reduce, NULL);
3606 0 : Py_DECREF(reduce);
3607 0 : return res;
3608 : }
3609 : else
3610 0 : Py_DECREF(reduce);
3611 : }
3612 :
3613 0 : return _common_reduce(self, proto);
3614 : }
3615 :
3616 : static PyObject *
3617 8 : object_subclasshook(PyObject *cls, PyObject *args)
3618 : {
3619 8 : Py_RETURN_NOTIMPLEMENTED;
3620 : }
3621 :
3622 : PyDoc_STRVAR(object_subclasshook_doc,
3623 : "Abstract classes can override this to customize issubclass().\n"
3624 : "\n"
3625 : "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3626 : "It should return True, False or NotImplemented. If it returns\n"
3627 : "NotImplemented, the normal algorithm is used. Otherwise, it\n"
3628 : "overrides the normal algorithm (and the outcome is cached).\n");
3629 :
3630 : /*
3631 : from PEP 3101, this code implements:
3632 :
3633 : class object:
3634 : def __format__(self, format_spec):
3635 : return format(str(self), format_spec)
3636 : */
3637 : static PyObject *
3638 0 : object_format(PyObject *self, PyObject *args)
3639 : {
3640 : PyObject *format_spec;
3641 0 : PyObject *self_as_str = NULL;
3642 0 : PyObject *result = NULL;
3643 :
3644 0 : if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3645 0 : return NULL;
3646 :
3647 0 : self_as_str = PyObject_Str(self);
3648 0 : if (self_as_str != NULL) {
3649 : /* Issue 7994: If we're converting to a string, we
3650 : should reject format specifications */
3651 0 : if (PyUnicode_GET_LENGTH(format_spec) > 0) {
3652 0 : if (PyErr_WarnEx(PyExc_DeprecationWarning,
3653 : "object.__format__ with a non-empty format "
3654 : "string is deprecated", 1) < 0) {
3655 0 : goto done;
3656 : }
3657 : /* Eventually this will become an error:
3658 : PyErr_Format(PyExc_TypeError,
3659 : "non-empty format string passed to object.__format__");
3660 : goto done;
3661 : */
3662 : }
3663 :
3664 0 : result = PyObject_Format(self_as_str, format_spec);
3665 : }
3666 :
3667 : done:
3668 0 : Py_XDECREF(self_as_str);
3669 :
3670 0 : return result;
3671 : }
3672 :
3673 : static PyObject *
3674 0 : object_sizeof(PyObject *self, PyObject *args)
3675 : {
3676 : Py_ssize_t res, isize;
3677 :
3678 0 : res = 0;
3679 0 : isize = self->ob_type->tp_itemsize;
3680 0 : if (isize > 0)
3681 0 : res = Py_SIZE(self->ob_type) * isize;
3682 0 : res += self->ob_type->tp_basicsize;
3683 :
3684 0 : return PyLong_FromSsize_t(res);
3685 : }
3686 :
3687 : /* __dir__ for generic objects: returns __dict__, __class__,
3688 : and recursively up the __class__.__bases__ chain.
3689 : */
3690 : static PyObject *
3691 0 : object_dir(PyObject *self, PyObject *args)
3692 : {
3693 0 : PyObject *result = NULL;
3694 0 : PyObject *dict = NULL;
3695 0 : PyObject *itsclass = NULL;
3696 :
3697 : /* Get __dict__ (which may or may not be a real dict...) */
3698 0 : dict = _PyObject_GetAttrId(self, &PyId___dict__);
3699 0 : if (dict == NULL) {
3700 0 : PyErr_Clear();
3701 0 : dict = PyDict_New();
3702 : }
3703 0 : else if (!PyDict_Check(dict)) {
3704 0 : Py_DECREF(dict);
3705 0 : dict = PyDict_New();
3706 : }
3707 : else {
3708 : /* Copy __dict__ to avoid mutating it. */
3709 0 : PyObject *temp = PyDict_Copy(dict);
3710 0 : Py_DECREF(dict);
3711 0 : dict = temp;
3712 : }
3713 :
3714 0 : if (dict == NULL)
3715 0 : goto error;
3716 :
3717 : /* Merge in attrs reachable from its class. */
3718 0 : itsclass = _PyObject_GetAttrId(self, &PyId___class__);
3719 0 : if (itsclass == NULL)
3720 : /* XXX(tomer): Perhaps fall back to obj->ob_type if no
3721 : __class__ exists? */
3722 0 : PyErr_Clear();
3723 0 : else if (merge_class_dict(dict, itsclass) != 0)
3724 0 : goto error;
3725 :
3726 0 : result = PyDict_Keys(dict);
3727 : /* fall through */
3728 : error:
3729 0 : Py_XDECREF(itsclass);
3730 0 : Py_XDECREF(dict);
3731 0 : return result;
3732 : }
3733 :
3734 : static PyMethodDef object_methods[] = {
3735 : {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3736 : PyDoc_STR("helper for pickle")},
3737 : {"__reduce__", object_reduce, METH_VARARGS,
3738 : PyDoc_STR("helper for pickle")},
3739 : {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3740 : object_subclasshook_doc},
3741 : {"__format__", object_format, METH_VARARGS,
3742 : PyDoc_STR("default object formatter")},
3743 : {"__sizeof__", object_sizeof, METH_NOARGS,
3744 : PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
3745 : {"__dir__", object_dir, METH_NOARGS,
3746 : PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
3747 : {0}
3748 : };
3749 :
3750 :
3751 : PyTypeObject PyBaseObject_Type = {
3752 : PyVarObject_HEAD_INIT(&PyType_Type, 0)
3753 : "object", /* tp_name */
3754 : sizeof(PyObject), /* tp_basicsize */
3755 : 0, /* tp_itemsize */
3756 : object_dealloc, /* tp_dealloc */
3757 : 0, /* tp_print */
3758 : 0, /* tp_getattr */
3759 : 0, /* tp_setattr */
3760 : 0, /* tp_reserved */
3761 : object_repr, /* tp_repr */
3762 : 0, /* tp_as_number */
3763 : 0, /* tp_as_sequence */
3764 : 0, /* tp_as_mapping */
3765 : (hashfunc)_Py_HashPointer, /* tp_hash */
3766 : 0, /* tp_call */
3767 : object_str, /* tp_str */
3768 : PyObject_GenericGetAttr, /* tp_getattro */
3769 : PyObject_GenericSetAttr, /* tp_setattro */
3770 : 0, /* tp_as_buffer */
3771 : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3772 : PyDoc_STR("The most base type"), /* tp_doc */
3773 : 0, /* tp_traverse */
3774 : 0, /* tp_clear */
3775 : object_richcompare, /* tp_richcompare */
3776 : 0, /* tp_weaklistoffset */
3777 : 0, /* tp_iter */
3778 : 0, /* tp_iternext */
3779 : object_methods, /* tp_methods */
3780 : 0, /* tp_members */
3781 : object_getsets, /* tp_getset */
3782 : 0, /* tp_base */
3783 : 0, /* tp_dict */
3784 : 0, /* tp_descr_get */
3785 : 0, /* tp_descr_set */
3786 : 0, /* tp_dictoffset */
3787 : object_init, /* tp_init */
3788 : PyType_GenericAlloc, /* tp_alloc */
3789 : object_new, /* tp_new */
3790 : PyObject_Del, /* tp_free */
3791 : };
3792 :
3793 :
3794 : /* Add the methods from tp_methods to the __dict__ in a type object */
3795 :
3796 : static int
3797 109 : add_methods(PyTypeObject *type, PyMethodDef *meth)
3798 : {
3799 109 : PyObject *dict = type->tp_dict;
3800 :
3801 756 : for (; meth->ml_name != NULL; meth++) {
3802 : PyObject *descr;
3803 : int err;
3804 652 : if (PyDict_GetItemString(dict, meth->ml_name) &&
3805 5 : !(meth->ml_flags & METH_COEXIST))
3806 0 : continue;
3807 647 : if (meth->ml_flags & METH_CLASS) {
3808 10 : if (meth->ml_flags & METH_STATIC) {
3809 0 : PyErr_SetString(PyExc_ValueError,
3810 : "method cannot be both class and static");
3811 0 : return -1;
3812 : }
3813 10 : descr = PyDescr_NewClassMethod(type, meth);
3814 : }
3815 637 : else if (meth->ml_flags & METH_STATIC) {
3816 3 : PyObject *cfunc = PyCFunction_New(meth, (PyObject*)type);
3817 3 : if (cfunc == NULL)
3818 0 : return -1;
3819 3 : descr = PyStaticMethod_New(cfunc);
3820 3 : Py_DECREF(cfunc);
3821 : }
3822 : else {
3823 634 : descr = PyDescr_NewMethod(type, meth);
3824 : }
3825 647 : if (descr == NULL)
3826 0 : return -1;
3827 647 : err = PyDict_SetItemString(dict, meth->ml_name, descr);
3828 647 : Py_DECREF(descr);
3829 647 : if (err < 0)
3830 0 : return -1;
3831 : }
3832 109 : return 0;
3833 : }
3834 :
3835 : static int
3836 300 : add_members(PyTypeObject *type, PyMemberDef *memb)
3837 : {
3838 300 : PyObject *dict = type->tp_dict;
3839 :
3840 519 : for (; memb->name != NULL; memb++) {
3841 : PyObject *descr;
3842 219 : if (PyDict_GetItemString(dict, memb->name))
3843 0 : continue;
3844 219 : descr = PyDescr_NewMember(type, memb);
3845 219 : if (descr == NULL)
3846 0 : return -1;
3847 219 : if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3848 0 : return -1;
3849 219 : Py_DECREF(descr);
3850 : }
3851 300 : return 0;
3852 : }
3853 :
3854 : static int
3855 131 : add_getset(PyTypeObject *type, PyGetSetDef *gsp)
3856 : {
3857 131 : PyObject *dict = type->tp_dict;
3858 :
3859 387 : for (; gsp->name != NULL; gsp++) {
3860 : PyObject *descr;
3861 256 : if (PyDict_GetItemString(dict, gsp->name))
3862 0 : continue;
3863 256 : descr = PyDescr_NewGetSet(type, gsp);
3864 :
3865 256 : if (descr == NULL)
3866 0 : return -1;
3867 256 : if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3868 0 : return -1;
3869 256 : Py_DECREF(descr);
3870 : }
3871 131 : return 0;
3872 : }
3873 :
3874 : static void
3875 436 : inherit_special(PyTypeObject *type, PyTypeObject *base)
3876 : {
3877 :
3878 : /* Copying basicsize is connected to the GC flags */
3879 492 : if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3880 73 : (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3881 34 : (!type->tp_traverse && !type->tp_clear)) {
3882 17 : type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3883 17 : if (type->tp_traverse == NULL)
3884 17 : type->tp_traverse = base->tp_traverse;
3885 17 : if (type->tp_clear == NULL)
3886 17 : type->tp_clear = base->tp_clear;
3887 : }
3888 : {
3889 : /* The condition below could use some explanation.
3890 : It appears that tp_new is not inherited for static types
3891 : whose base class is 'object'; this seems to be a precaution
3892 : so that old extension types don't suddenly become
3893 : callable (object.__new__ wouldn't insure the invariants
3894 : that the extension type's own factory function ensures).
3895 : Heap types, of course, are under our control, so they do
3896 : inherit tp_new; static extension types that specify some
3897 : other built-in type as the default also
3898 : inherit object.__new__. */
3899 594 : if (base != &PyBaseObject_Type ||
3900 158 : (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3901 332 : if (type->tp_new == NULL)
3902 271 : type->tp_new = base->tp_new;
3903 : }
3904 : }
3905 436 : if (type->tp_basicsize == 0)
3906 6 : type->tp_basicsize = base->tp_basicsize;
3907 :
3908 : /* Copy other non-function slots */
3909 :
3910 : #undef COPYVAL
3911 : #define COPYVAL(SLOT) \
3912 : if (type->SLOT == 0) type->SLOT = base->SLOT
3913 :
3914 436 : COPYVAL(tp_itemsize);
3915 436 : COPYVAL(tp_weaklistoffset);
3916 436 : COPYVAL(tp_dictoffset);
3917 :
3918 : /* Setup fast subclass flags */
3919 436 : if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3920 75 : type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3921 361 : else if (PyType_IsSubtype(base, &PyType_Type))
3922 1 : type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3923 360 : else if (PyType_IsSubtype(base, &PyLong_Type))
3924 1 : type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3925 359 : else if (PyType_IsSubtype(base, &PyBytes_Type))
3926 0 : type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
3927 359 : else if (PyType_IsSubtype(base, &PyUnicode_Type))
3928 0 : type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3929 359 : else if (PyType_IsSubtype(base, &PyTuple_Type))
3930 18 : type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3931 341 : else if (PyType_IsSubtype(base, &PyList_Type))
3932 1 : type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3933 340 : else if (PyType_IsSubtype(base, &PyDict_Type))
3934 3 : type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
3935 436 : }
3936 :
3937 : static int
3938 427 : overrides_hash(PyTypeObject *type)
3939 : {
3940 427 : PyObject *dict = type->tp_dict;
3941 : _Py_IDENTIFIER(__eq__);
3942 :
3943 : assert(dict != NULL);
3944 427 : if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
3945 26 : return 1;
3946 401 : if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
3947 3 : return 1;
3948 398 : return 0;
3949 : }
3950 :
3951 : static void
3952 1048 : inherit_slots(PyTypeObject *type, PyTypeObject *base)
3953 : {
3954 : PyTypeObject *basebase;
3955 :
3956 : #undef SLOTDEFINED
3957 : #undef COPYSLOT
3958 : #undef COPYNUM
3959 : #undef COPYSEQ
3960 : #undef COPYMAP
3961 : #undef COPYBUF
3962 :
3963 : #define SLOTDEFINED(SLOT) \
3964 : (base->SLOT != 0 && \
3965 : (basebase == NULL || base->SLOT != basebase->SLOT))
3966 :
3967 : #define COPYSLOT(SLOT) \
3968 : if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
3969 :
3970 : #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3971 : #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3972 : #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
3973 : #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
3974 :
3975 : /* This won't inherit indirect slots (from tp_as_number etc.)
3976 : if type doesn't provide the space. */
3977 :
3978 1048 : if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3979 250 : basebase = base->tp_base;
3980 250 : if (basebase->tp_as_number == NULL)
3981 188 : basebase = NULL;
3982 250 : COPYNUM(nb_add);
3983 250 : COPYNUM(nb_subtract);
3984 250 : COPYNUM(nb_multiply);
3985 250 : COPYNUM(nb_remainder);
3986 250 : COPYNUM(nb_divmod);
3987 250 : COPYNUM(nb_power);
3988 250 : COPYNUM(nb_negative);
3989 250 : COPYNUM(nb_positive);
3990 250 : COPYNUM(nb_absolute);
3991 250 : COPYNUM(nb_bool);
3992 250 : COPYNUM(nb_invert);
3993 250 : COPYNUM(nb_lshift);
3994 250 : COPYNUM(nb_rshift);
3995 250 : COPYNUM(nb_and);
3996 250 : COPYNUM(nb_xor);
3997 250 : COPYNUM(nb_or);
3998 250 : COPYNUM(nb_int);
3999 250 : COPYNUM(nb_float);
4000 250 : COPYNUM(nb_inplace_add);
4001 250 : COPYNUM(nb_inplace_subtract);
4002 250 : COPYNUM(nb_inplace_multiply);
4003 250 : COPYNUM(nb_inplace_remainder);
4004 250 : COPYNUM(nb_inplace_power);
4005 250 : COPYNUM(nb_inplace_lshift);
4006 250 : COPYNUM(nb_inplace_rshift);
4007 250 : COPYNUM(nb_inplace_and);
4008 250 : COPYNUM(nb_inplace_xor);
4009 250 : COPYNUM(nb_inplace_or);
4010 250 : COPYNUM(nb_true_divide);
4011 250 : COPYNUM(nb_floor_divide);
4012 250 : COPYNUM(nb_inplace_true_divide);
4013 250 : COPYNUM(nb_inplace_floor_divide);
4014 250 : COPYNUM(nb_index);
4015 : }
4016 :
4017 1048 : if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4018 256 : basebase = base->tp_base;
4019 256 : if (basebase->tp_as_sequence == NULL)
4020 193 : basebase = NULL;
4021 256 : COPYSEQ(sq_length);
4022 256 : COPYSEQ(sq_concat);
4023 256 : COPYSEQ(sq_repeat);
4024 256 : COPYSEQ(sq_item);
4025 256 : COPYSEQ(sq_ass_item);
4026 256 : COPYSEQ(sq_contains);
4027 256 : COPYSEQ(sq_inplace_concat);
4028 256 : COPYSEQ(sq_inplace_repeat);
4029 : }
4030 :
4031 1048 : if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4032 256 : basebase = base->tp_base;
4033 256 : if (basebase->tp_as_mapping == NULL)
4034 193 : basebase = NULL;
4035 256 : COPYMAP(mp_length);
4036 256 : COPYMAP(mp_subscript);
4037 256 : COPYMAP(mp_ass_subscript);
4038 : }
4039 :
4040 1048 : if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4041 249 : basebase = base->tp_base;
4042 249 : if (basebase->tp_as_buffer == NULL)
4043 187 : basebase = NULL;
4044 249 : COPYBUF(bf_getbuffer);
4045 249 : COPYBUF(bf_releasebuffer);
4046 : }
4047 :
4048 1048 : basebase = base->tp_base;
4049 :
4050 1048 : COPYSLOT(tp_dealloc);
4051 1048 : if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4052 348 : type->tp_getattr = base->tp_getattr;
4053 348 : type->tp_getattro = base->tp_getattro;
4054 : }
4055 1048 : if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4056 425 : type->tp_setattr = base->tp_setattr;
4057 425 : type->tp_setattro = base->tp_setattro;
4058 : }
4059 : /* tp_reserved is ignored */
4060 1048 : COPYSLOT(tp_repr);
4061 : /* tp_hash see tp_richcompare */
4062 1048 : COPYSLOT(tp_call);
4063 1048 : COPYSLOT(tp_str);
4064 : {
4065 : /* Copy comparison-related slots only when
4066 : not overriding them anywhere */
4067 1475 : if (type->tp_richcompare == NULL &&
4068 854 : type->tp_hash == NULL &&
4069 427 : !overrides_hash(type))
4070 : {
4071 398 : type->tp_richcompare = base->tp_richcompare;
4072 398 : type->tp_hash = base->tp_hash;
4073 : }
4074 : }
4075 : {
4076 1048 : COPYSLOT(tp_iter);
4077 1048 : COPYSLOT(tp_iternext);
4078 : }
4079 : {
4080 1048 : COPYSLOT(tp_descr_get);
4081 1048 : COPYSLOT(tp_descr_set);
4082 1048 : COPYSLOT(tp_dictoffset);
4083 1048 : COPYSLOT(tp_init);
4084 1048 : COPYSLOT(tp_alloc);
4085 1048 : COPYSLOT(tp_is_gc);
4086 2096 : if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4087 1048 : (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4088 : /* They agree about gc. */
4089 606 : COPYSLOT(tp_free);
4090 : }
4091 884 : else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4092 479 : type->tp_free == NULL &&
4093 37 : base->tp_free == PyObject_Free) {
4094 : /* A bit of magic to plug in the correct default
4095 : * tp_free function when a derived class adds gc,
4096 : * didn't define tp_free, and the base uses the
4097 : * default non-gc tp_free.
4098 : */
4099 37 : type->tp_free = PyObject_GC_Del;
4100 : }
4101 : /* else they didn't agree about gc, and there isn't something
4102 : * obvious to be done -- the type is on its own.
4103 : */
4104 : }
4105 1048 : }
4106 :
4107 : static int add_operators(PyTypeObject *);
4108 :
4109 : int
4110 464 : PyType_Ready(PyTypeObject *type)
4111 : {
4112 : PyObject *dict, *bases;
4113 : PyTypeObject *base;
4114 : Py_ssize_t i, n;
4115 :
4116 464 : if (type->tp_flags & Py_TPFLAGS_READY) {
4117 : assert(type->tp_dict != NULL);
4118 27 : return 0;
4119 : }
4120 : assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
4121 :
4122 437 : type->tp_flags |= Py_TPFLAGS_READYING;
4123 :
4124 : #ifdef Py_TRACE_REFS
4125 : /* PyType_Ready is the closest thing we have to a choke point
4126 : * for type objects, so is the best place I can think of to try
4127 : * to get type objects into the doubly-linked list of all objects.
4128 : * Still, not all type objects go thru PyType_Ready.
4129 : */
4130 : _Py_AddToAllObjects((PyObject *)type, 0);
4131 : #endif
4132 :
4133 : /* Initialize tp_base (defaults to BaseObject unless that's us) */
4134 437 : base = type->tp_base;
4135 437 : if (base == NULL && type != &PyBaseObject_Type) {
4136 102 : base = type->tp_base = &PyBaseObject_Type;
4137 102 : Py_INCREF(base);
4138 : }
4139 :
4140 : /* Now the only way base can still be NULL is if type is
4141 : * &PyBaseObject_Type.
4142 : */
4143 :
4144 : /* Initialize the base class */
4145 437 : if (base != NULL && base->tp_dict == NULL) {
4146 2 : if (PyType_Ready(base) < 0)
4147 0 : goto error;
4148 : }
4149 :
4150 : /* Initialize ob_type if NULL. This means extensions that want to be
4151 : compilable separately on Windows can call PyType_Ready() instead of
4152 : initializing the ob_type field of their type objects. */
4153 : /* The test for base != NULL is really unnecessary, since base is only
4154 : NULL when type is &PyBaseObject_Type, and we know its ob_type is
4155 : not NULL (it's initialized to &PyType_Type). But coverity doesn't
4156 : know that. */
4157 437 : if (Py_TYPE(type) == NULL && base != NULL)
4158 110 : Py_TYPE(type) = Py_TYPE(base);
4159 :
4160 : /* Initialize tp_bases */
4161 437 : bases = type->tp_bases;
4162 437 : if (bases == NULL) {
4163 192 : if (base == NULL)
4164 1 : bases = PyTuple_New(0);
4165 : else
4166 191 : bases = PyTuple_Pack(1, base);
4167 192 : if (bases == NULL)
4168 0 : goto error;
4169 192 : type->tp_bases = bases;
4170 : }
4171 :
4172 : /* Initialize tp_dict */
4173 437 : dict = type->tp_dict;
4174 437 : if (dict == NULL) {
4175 192 : dict = PyDict_New();
4176 192 : if (dict == NULL)
4177 0 : goto error;
4178 192 : type->tp_dict = dict;
4179 : }
4180 :
4181 : /* Add type-specific descriptors to tp_dict */
4182 437 : if (add_operators(type) < 0)
4183 0 : goto error;
4184 437 : if (type->tp_methods != NULL) {
4185 109 : if (add_methods(type, type->tp_methods) < 0)
4186 0 : goto error;
4187 : }
4188 437 : if (type->tp_members != NULL) {
4189 300 : if (add_members(type, type->tp_members) < 0)
4190 0 : goto error;
4191 : }
4192 437 : if (type->tp_getset != NULL) {
4193 131 : if (add_getset(type, type->tp_getset) < 0)
4194 0 : goto error;
4195 : }
4196 :
4197 : /* Calculate method resolution order */
4198 437 : if (mro_internal(type) < 0) {
4199 0 : goto error;
4200 : }
4201 :
4202 : /* Inherit special flags from dominant base */
4203 437 : if (type->tp_base != NULL)
4204 436 : inherit_special(type, type->tp_base);
4205 :
4206 : /* Initialize tp_dict properly */
4207 437 : bases = type->tp_mro;
4208 : assert(bases != NULL);
4209 : assert(PyTuple_Check(bases));
4210 437 : n = PyTuple_GET_SIZE(bases);
4211 1485 : for (i = 1; i < n; i++) {
4212 1048 : PyObject *b = PyTuple_GET_ITEM(bases, i);
4213 1048 : if (PyType_Check(b))
4214 1048 : inherit_slots(type, (PyTypeObject *)b);
4215 : }
4216 :
4217 : /* Sanity check for tp_free. */
4218 783 : if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4219 692 : (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4220 : /* This base class needs to call tp_free, but doesn't have
4221 : * one, or its tp_free is for non-gc'ed objects.
4222 : */
4223 0 : PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4224 : "gc and is a base type but has inappropriate "
4225 : "tp_free slot",
4226 : type->tp_name);
4227 0 : goto error;
4228 : }
4229 :
4230 : /* if the type dictionary doesn't contain a __doc__, set it from
4231 : the tp_doc slot.
4232 : */
4233 437 : if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
4234 374 : if (type->tp_doc != NULL) {
4235 146 : PyObject *doc = PyUnicode_FromString(type->tp_doc);
4236 146 : if (doc == NULL)
4237 0 : goto error;
4238 146 : _PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc);
4239 146 : Py_DECREF(doc);
4240 : } else {
4241 228 : _PyDict_SetItemId(type->tp_dict,
4242 : &PyId___doc__, Py_None);
4243 : }
4244 : }
4245 :
4246 : /* Hack for tp_hash and __hash__.
4247 : If after all that, tp_hash is still NULL, and __hash__ is not in
4248 : tp_dict, set tp_hash to PyObject_HashNotImplemented and
4249 : tp_dict['__hash__'] equal to None.
4250 : This signals that __hash__ is not inherited.
4251 : */
4252 437 : if (type->tp_hash == NULL) {
4253 19 : if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4254 14 : if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
4255 0 : goto error;
4256 14 : type->tp_hash = PyObject_HashNotImplemented;
4257 : }
4258 : }
4259 :
4260 : /* Some more special stuff */
4261 437 : base = type->tp_base;
4262 437 : if (base != NULL) {
4263 436 : if (type->tp_as_number == NULL)
4264 179 : type->tp_as_number = base->tp_as_number;
4265 436 : if (type->tp_as_sequence == NULL)
4266 173 : type->tp_as_sequence = base->tp_as_sequence;
4267 436 : if (type->tp_as_mapping == NULL)
4268 179 : type->tp_as_mapping = base->tp_as_mapping;
4269 436 : if (type->tp_as_buffer == NULL)
4270 186 : type->tp_as_buffer = base->tp_as_buffer;
4271 : }
4272 :
4273 : /* Link into each base class's list of subclasses */
4274 437 : bases = type->tp_bases;
4275 437 : n = PyTuple_GET_SIZE(bases);
4276 905 : for (i = 0; i < n; i++) {
4277 468 : PyObject *b = PyTuple_GET_ITEM(bases, i);
4278 936 : if (PyType_Check(b) &&
4279 468 : add_subclass((PyTypeObject *)b, type) < 0)
4280 0 : goto error;
4281 : }
4282 :
4283 : /* Warn for a type that implements tp_compare (now known as
4284 : tp_reserved) but not tp_richcompare. */
4285 437 : if (type->tp_reserved && !type->tp_richcompare) {
4286 : int error;
4287 0 : error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4288 : "Type %.100s defines tp_reserved (formerly tp_compare) "
4289 : "but not tp_richcompare. Comparisons may not behave as intended.",
4290 : type->tp_name);
4291 0 : if (error == -1)
4292 0 : goto error;
4293 : }
4294 :
4295 : /* All done -- set the ready flag */
4296 : assert(type->tp_dict != NULL);
4297 437 : type->tp_flags =
4298 437 : (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4299 437 : return 0;
4300 :
4301 : error:
4302 0 : type->tp_flags &= ~Py_TPFLAGS_READYING;
4303 0 : return -1;
4304 : }
4305 :
4306 : static int
4307 468 : add_subclass(PyTypeObject *base, PyTypeObject *type)
4308 : {
4309 : Py_ssize_t i;
4310 : int result;
4311 : PyObject *list, *ref, *newobj;
4312 :
4313 468 : list = base->tp_subclasses;
4314 468 : if (list == NULL) {
4315 81 : base->tp_subclasses = list = PyList_New(0);
4316 81 : if (list == NULL)
4317 0 : return -1;
4318 : }
4319 : assert(PyList_Check(list));
4320 468 : newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4321 468 : i = PyList_GET_SIZE(list);
4322 14842 : while (--i >= 0) {
4323 13906 : ref = PyList_GET_ITEM(list, i);
4324 : assert(PyWeakref_CheckRef(ref));
4325 13906 : if (PyWeakref_GET_OBJECT(ref) == Py_None)
4326 0 : return PyList_SetItem(list, i, newobj);
4327 : }
4328 468 : result = PyList_Append(list, newobj);
4329 468 : Py_DECREF(newobj);
4330 468 : return result;
4331 : }
4332 :
4333 : static void
4334 0 : remove_subclass(PyTypeObject *base, PyTypeObject *type)
4335 : {
4336 : Py_ssize_t i;
4337 : PyObject *list, *ref;
4338 :
4339 0 : list = base->tp_subclasses;
4340 0 : if (list == NULL) {
4341 0 : return;
4342 : }
4343 : assert(PyList_Check(list));
4344 0 : i = PyList_GET_SIZE(list);
4345 0 : while (--i >= 0) {
4346 0 : ref = PyList_GET_ITEM(list, i);
4347 : assert(PyWeakref_CheckRef(ref));
4348 0 : if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4349 : /* this can't fail, right? */
4350 0 : PySequence_DelItem(list, i);
4351 0 : return;
4352 : }
4353 : }
4354 : }
4355 :
4356 : static int
4357 0 : check_num_args(PyObject *ob, int n)
4358 : {
4359 0 : if (!PyTuple_CheckExact(ob)) {
4360 0 : PyErr_SetString(PyExc_SystemError,
4361 : "PyArg_UnpackTuple() argument list is not a tuple");
4362 0 : return 0;
4363 : }
4364 0 : if (n == PyTuple_GET_SIZE(ob))
4365 0 : return 1;
4366 0 : PyErr_Format(
4367 : PyExc_TypeError,
4368 : "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4369 0 : return 0;
4370 : }
4371 :
4372 : /* Generic wrappers for overloadable 'operators' such as __getitem__ */
4373 :
4374 : /* There's a wrapper *function* for each distinct function typedef used
4375 : for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
4376 : wrapper *table* for each distinct operation (e.g. __len__, __add__).
4377 : Most tables have only one entry; the tables for binary operators have two
4378 : entries, one regular and one with reversed arguments. */
4379 :
4380 : static PyObject *
4381 0 : wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
4382 : {
4383 0 : lenfunc func = (lenfunc)wrapped;
4384 : Py_ssize_t res;
4385 :
4386 0 : if (!check_num_args(args, 0))
4387 0 : return NULL;
4388 0 : res = (*func)(self);
4389 0 : if (res == -1 && PyErr_Occurred())
4390 0 : return NULL;
4391 0 : return PyLong_FromLong((long)res);
4392 : }
4393 :
4394 : static PyObject *
4395 0 : wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4396 : {
4397 0 : inquiry func = (inquiry)wrapped;
4398 : int res;
4399 :
4400 0 : if (!check_num_args(args, 0))
4401 0 : return NULL;
4402 0 : res = (*func)(self);
4403 0 : if (res == -1 && PyErr_Occurred())
4404 0 : return NULL;
4405 0 : return PyBool_FromLong((long)res);
4406 : }
4407 :
4408 : static PyObject *
4409 0 : wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4410 : {
4411 0 : binaryfunc func = (binaryfunc)wrapped;
4412 : PyObject *other;
4413 :
4414 0 : if (!check_num_args(args, 1))
4415 0 : return NULL;
4416 0 : other = PyTuple_GET_ITEM(args, 0);
4417 0 : return (*func)(self, other);
4418 : }
4419 :
4420 : static PyObject *
4421 0 : wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4422 : {
4423 0 : binaryfunc func = (binaryfunc)wrapped;
4424 : PyObject *other;
4425 :
4426 0 : if (!check_num_args(args, 1))
4427 0 : return NULL;
4428 0 : other = PyTuple_GET_ITEM(args, 0);
4429 0 : return (*func)(self, other);
4430 : }
4431 :
4432 : static PyObject *
4433 0 : wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4434 : {
4435 0 : binaryfunc func = (binaryfunc)wrapped;
4436 : PyObject *other;
4437 :
4438 0 : if (!check_num_args(args, 1))
4439 0 : return NULL;
4440 0 : other = PyTuple_GET_ITEM(args, 0);
4441 0 : return (*func)(other, self);
4442 : }
4443 :
4444 : static PyObject *
4445 0 : wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4446 : {
4447 0 : ternaryfunc func = (ternaryfunc)wrapped;
4448 : PyObject *other;
4449 0 : PyObject *third = Py_None;
4450 :
4451 : /* Note: This wrapper only works for __pow__() */
4452 :
4453 0 : if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4454 0 : return NULL;
4455 0 : return (*func)(self, other, third);
4456 : }
4457 :
4458 : static PyObject *
4459 0 : wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4460 : {
4461 0 : ternaryfunc func = (ternaryfunc)wrapped;
4462 : PyObject *other;
4463 0 : PyObject *third = Py_None;
4464 :
4465 : /* Note: This wrapper only works for __pow__() */
4466 :
4467 0 : if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4468 0 : return NULL;
4469 0 : return (*func)(other, self, third);
4470 : }
4471 :
4472 : static PyObject *
4473 0 : wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4474 : {
4475 0 : unaryfunc func = (unaryfunc)wrapped;
4476 :
4477 0 : if (!check_num_args(args, 0))
4478 0 : return NULL;
4479 0 : return (*func)(self);
4480 : }
4481 :
4482 : static PyObject *
4483 0 : wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
4484 : {
4485 0 : ssizeargfunc func = (ssizeargfunc)wrapped;
4486 : PyObject* o;
4487 : Py_ssize_t i;
4488 :
4489 0 : if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4490 0 : return NULL;
4491 0 : i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4492 0 : if (i == -1 && PyErr_Occurred())
4493 0 : return NULL;
4494 0 : return (*func)(self, i);
4495 : }
4496 :
4497 : static Py_ssize_t
4498 0 : getindex(PyObject *self, PyObject *arg)
4499 : {
4500 : Py_ssize_t i;
4501 :
4502 0 : i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4503 0 : if (i == -1 && PyErr_Occurred())
4504 0 : return -1;
4505 0 : if (i < 0) {
4506 0 : PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4507 0 : if (sq && sq->sq_length) {
4508 0 : Py_ssize_t n = (*sq->sq_length)(self);
4509 0 : if (n < 0)
4510 0 : return -1;
4511 0 : i += n;
4512 : }
4513 : }
4514 0 : return i;
4515 : }
4516 :
4517 : static PyObject *
4518 0 : wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4519 : {
4520 0 : ssizeargfunc func = (ssizeargfunc)wrapped;
4521 : PyObject *arg;
4522 : Py_ssize_t i;
4523 :
4524 0 : if (PyTuple_GET_SIZE(args) == 1) {
4525 0 : arg = PyTuple_GET_ITEM(args, 0);
4526 0 : i = getindex(self, arg);
4527 0 : if (i == -1 && PyErr_Occurred())
4528 0 : return NULL;
4529 0 : return (*func)(self, i);
4530 : }
4531 0 : check_num_args(args, 1);
4532 : assert(PyErr_Occurred());
4533 0 : return NULL;
4534 : }
4535 :
4536 : static PyObject *
4537 0 : wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
4538 : {
4539 0 : ssizeobjargproc func = (ssizeobjargproc)wrapped;
4540 : Py_ssize_t i;
4541 : int res;
4542 : PyObject *arg, *value;
4543 :
4544 0 : if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4545 0 : return NULL;
4546 0 : i = getindex(self, arg);
4547 0 : if (i == -1 && PyErr_Occurred())
4548 0 : return NULL;
4549 0 : res = (*func)(self, i, value);
4550 0 : if (res == -1 && PyErr_Occurred())
4551 0 : return NULL;
4552 0 : Py_INCREF(Py_None);
4553 0 : return Py_None;
4554 : }
4555 :
4556 : static PyObject *
4557 0 : wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
4558 : {
4559 0 : ssizeobjargproc func = (ssizeobjargproc)wrapped;
4560 : Py_ssize_t i;
4561 : int res;
4562 : PyObject *arg;
4563 :
4564 0 : if (!check_num_args(args, 1))
4565 0 : return NULL;
4566 0 : arg = PyTuple_GET_ITEM(args, 0);
4567 0 : i = getindex(self, arg);
4568 0 : if (i == -1 && PyErr_Occurred())
4569 0 : return NULL;
4570 0 : res = (*func)(self, i, NULL);
4571 0 : if (res == -1 && PyErr_Occurred())
4572 0 : return NULL;
4573 0 : Py_INCREF(Py_None);
4574 0 : return Py_None;
4575 : }
4576 :
4577 : /* XXX objobjproc is a misnomer; should be objargpred */
4578 : static PyObject *
4579 0 : wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4580 : {
4581 0 : objobjproc func = (objobjproc)wrapped;
4582 : int res;
4583 : PyObject *value;
4584 :
4585 0 : if (!check_num_args(args, 1))
4586 0 : return NULL;
4587 0 : value = PyTuple_GET_ITEM(args, 0);
4588 0 : res = (*func)(self, value);
4589 0 : if (res == -1 && PyErr_Occurred())
4590 0 : return NULL;
4591 : else
4592 0 : return PyBool_FromLong(res);
4593 : }
4594 :
4595 : static PyObject *
4596 0 : wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4597 : {
4598 0 : objobjargproc func = (objobjargproc)wrapped;
4599 : int res;
4600 : PyObject *key, *value;
4601 :
4602 0 : if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4603 0 : return NULL;
4604 0 : res = (*func)(self, key, value);
4605 0 : if (res == -1 && PyErr_Occurred())
4606 0 : return NULL;
4607 0 : Py_INCREF(Py_None);
4608 0 : return Py_None;
4609 : }
4610 :
4611 : static PyObject *
4612 0 : wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4613 : {
4614 0 : objobjargproc func = (objobjargproc)wrapped;
4615 : int res;
4616 : PyObject *key;
4617 :
4618 0 : if (!check_num_args(args, 1))
4619 0 : return NULL;
4620 0 : key = PyTuple_GET_ITEM(args, 0);
4621 0 : res = (*func)(self, key, NULL);
4622 0 : if (res == -1 && PyErr_Occurred())
4623 0 : return NULL;
4624 0 : Py_INCREF(Py_None);
4625 0 : return Py_None;
4626 : }
4627 :
4628 : /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
4629 : This is called the Carlo Verre hack after its discoverer. */
4630 : static int
4631 0 : hackcheck(PyObject *self, setattrofunc func, char *what)
4632 : {
4633 0 : PyTypeObject *type = Py_TYPE(self);
4634 0 : while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4635 0 : type = type->tp_base;
4636 : /* If type is NULL now, this is a really weird type.
4637 : In the spirit of backwards compatibility (?), just shut up. */
4638 0 : if (type && type->tp_setattro != func) {
4639 0 : PyErr_Format(PyExc_TypeError,
4640 : "can't apply this %s to %s object",
4641 : what,
4642 : type->tp_name);
4643 0 : return 0;
4644 : }
4645 0 : return 1;
4646 : }
4647 :
4648 : static PyObject *
4649 0 : wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4650 : {
4651 0 : setattrofunc func = (setattrofunc)wrapped;
4652 : int res;
4653 : PyObject *name, *value;
4654 :
4655 0 : if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4656 0 : return NULL;
4657 0 : if (!hackcheck(self, func, "__setattr__"))
4658 0 : return NULL;
4659 0 : res = (*func)(self, name, value);
4660 0 : if (res < 0)
4661 0 : return NULL;
4662 0 : Py_INCREF(Py_None);
4663 0 : return Py_None;
4664 : }
4665 :
4666 : static PyObject *
4667 0 : wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4668 : {
4669 0 : setattrofunc func = (setattrofunc)wrapped;
4670 : int res;
4671 : PyObject *name;
4672 :
4673 0 : if (!check_num_args(args, 1))
4674 0 : return NULL;
4675 0 : name = PyTuple_GET_ITEM(args, 0);
4676 0 : if (!hackcheck(self, func, "__delattr__"))
4677 0 : return NULL;
4678 0 : res = (*func)(self, name, NULL);
4679 0 : if (res < 0)
4680 0 : return NULL;
4681 0 : Py_INCREF(Py_None);
4682 0 : return Py_None;
4683 : }
4684 :
4685 : static PyObject *
4686 0 : wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4687 : {
4688 0 : hashfunc func = (hashfunc)wrapped;
4689 : Py_hash_t res;
4690 :
4691 0 : if (!check_num_args(args, 0))
4692 0 : return NULL;
4693 0 : res = (*func)(self);
4694 0 : if (res == -1 && PyErr_Occurred())
4695 0 : return NULL;
4696 0 : return PyLong_FromSsize_t(res);
4697 : }
4698 :
4699 : static PyObject *
4700 0 : wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4701 : {
4702 0 : ternaryfunc func = (ternaryfunc)wrapped;
4703 :
4704 0 : return (*func)(self, args, kwds);
4705 : }
4706 :
4707 : static PyObject *
4708 0 : wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4709 : {
4710 0 : richcmpfunc func = (richcmpfunc)wrapped;
4711 : PyObject *other;
4712 :
4713 0 : if (!check_num_args(args, 1))
4714 0 : return NULL;
4715 0 : other = PyTuple_GET_ITEM(args, 0);
4716 0 : return (*func)(self, other, op);
4717 : }
4718 :
4719 : #undef RICHCMP_WRAPPER
4720 : #define RICHCMP_WRAPPER(NAME, OP) \
4721 : static PyObject * \
4722 : richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4723 : { \
4724 : return wrap_richcmpfunc(self, args, wrapped, OP); \
4725 : }
4726 :
4727 0 : RICHCMP_WRAPPER(lt, Py_LT)
4728 0 : RICHCMP_WRAPPER(le, Py_LE)
4729 0 : RICHCMP_WRAPPER(eq, Py_EQ)
4730 0 : RICHCMP_WRAPPER(ne, Py_NE)
4731 0 : RICHCMP_WRAPPER(gt, Py_GT)
4732 0 : RICHCMP_WRAPPER(ge, Py_GE)
4733 :
4734 : static PyObject *
4735 0 : wrap_next(PyObject *self, PyObject *args, void *wrapped)
4736 : {
4737 0 : unaryfunc func = (unaryfunc)wrapped;
4738 : PyObject *res;
4739 :
4740 0 : if (!check_num_args(args, 0))
4741 0 : return NULL;
4742 0 : res = (*func)(self);
4743 0 : if (res == NULL && !PyErr_Occurred())
4744 0 : PyErr_SetNone(PyExc_StopIteration);
4745 0 : return res;
4746 : }
4747 :
4748 : static PyObject *
4749 0 : wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4750 : {
4751 0 : descrgetfunc func = (descrgetfunc)wrapped;
4752 : PyObject *obj;
4753 0 : PyObject *type = NULL;
4754 :
4755 0 : if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4756 0 : return NULL;
4757 0 : if (obj == Py_None)
4758 0 : obj = NULL;
4759 0 : if (type == Py_None)
4760 0 : type = NULL;
4761 0 : if (type == NULL &&obj == NULL) {
4762 0 : PyErr_SetString(PyExc_TypeError,
4763 : "__get__(None, None) is invalid");
4764 0 : return NULL;
4765 : }
4766 0 : return (*func)(self, obj, type);
4767 : }
4768 :
4769 : static PyObject *
4770 0 : wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
4771 : {
4772 0 : descrsetfunc func = (descrsetfunc)wrapped;
4773 : PyObject *obj, *value;
4774 : int ret;
4775 :
4776 0 : if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4777 0 : return NULL;
4778 0 : ret = (*func)(self, obj, value);
4779 0 : if (ret < 0)
4780 0 : return NULL;
4781 0 : Py_INCREF(Py_None);
4782 0 : return Py_None;
4783 : }
4784 :
4785 : static PyObject *
4786 0 : wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4787 : {
4788 0 : descrsetfunc func = (descrsetfunc)wrapped;
4789 : PyObject *obj;
4790 : int ret;
4791 :
4792 0 : if (!check_num_args(args, 1))
4793 0 : return NULL;
4794 0 : obj = PyTuple_GET_ITEM(args, 0);
4795 0 : ret = (*func)(self, obj, NULL);
4796 0 : if (ret < 0)
4797 0 : return NULL;
4798 0 : Py_INCREF(Py_None);
4799 0 : return Py_None;
4800 : }
4801 :
4802 : static PyObject *
4803 0 : wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4804 : {
4805 0 : initproc func = (initproc)wrapped;
4806 :
4807 0 : if (func(self, args, kwds) < 0)
4808 0 : return NULL;
4809 0 : Py_INCREF(Py_None);
4810 0 : return Py_None;
4811 : }
4812 :
4813 : static PyObject *
4814 30 : tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
4815 : {
4816 : PyTypeObject *type, *subtype, *staticbase;
4817 : PyObject *arg0, *res;
4818 :
4819 30 : if (self == NULL || !PyType_Check(self))
4820 0 : Py_FatalError("__new__() called with non-type 'self'");
4821 30 : type = (PyTypeObject *)self;
4822 30 : if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4823 0 : PyErr_Format(PyExc_TypeError,
4824 : "%s.__new__(): not enough arguments",
4825 : type->tp_name);
4826 0 : return NULL;
4827 : }
4828 30 : arg0 = PyTuple_GET_ITEM(args, 0);
4829 30 : if (!PyType_Check(arg0)) {
4830 0 : PyErr_Format(PyExc_TypeError,
4831 : "%s.__new__(X): X is not a type object (%s)",
4832 : type->tp_name,
4833 0 : Py_TYPE(arg0)->tp_name);
4834 0 : return NULL;
4835 : }
4836 30 : subtype = (PyTypeObject *)arg0;
4837 30 : if (!PyType_IsSubtype(subtype, type)) {
4838 0 : PyErr_Format(PyExc_TypeError,
4839 : "%s.__new__(%s): %s is not a subtype of %s",
4840 : type->tp_name,
4841 : subtype->tp_name,
4842 : subtype->tp_name,
4843 : type->tp_name);
4844 0 : return NULL;
4845 : }
4846 :
4847 : /* Check that the use doesn't do something silly and unsafe like
4848 : object.__new__(dict). To do this, we check that the
4849 : most derived base that's not a heap type is this type. */
4850 30 : staticbase = subtype;
4851 90 : while (staticbase && (staticbase->tp_new == slot_tp_new))
4852 30 : staticbase = staticbase->tp_base;
4853 : /* If staticbase is NULL now, it is a really weird type.
4854 : In the spirit of backwards compatibility (?), just shut up. */
4855 30 : if (staticbase && staticbase->tp_new != type->tp_new) {
4856 0 : PyErr_Format(PyExc_TypeError,
4857 : "%s.__new__(%s) is not safe, use %s.__new__()",
4858 : type->tp_name,
4859 : subtype->tp_name,
4860 : staticbase == NULL ? "?" : staticbase->tp_name);
4861 0 : return NULL;
4862 : }
4863 :
4864 30 : args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4865 30 : if (args == NULL)
4866 0 : return NULL;
4867 30 : res = type->tp_new(subtype, args, kwds);
4868 30 : Py_DECREF(args);
4869 30 : return res;
4870 : }
4871 :
4872 : static struct PyMethodDef tp_new_methoddef[] = {
4873 : {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4874 : PyDoc_STR("T.__new__(S, ...) -> "
4875 : "a new object with type S, a subtype of T")},
4876 : {0}
4877 : };
4878 :
4879 : static int
4880 134 : add_tp_new_wrapper(PyTypeObject *type)
4881 : {
4882 : PyObject *func;
4883 :
4884 134 : if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
4885 0 : return 0;
4886 134 : func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4887 134 : if (func == NULL)
4888 0 : return -1;
4889 134 : if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
4890 0 : Py_DECREF(func);
4891 0 : return -1;
4892 : }
4893 134 : Py_DECREF(func);
4894 134 : return 0;
4895 : }
4896 :
4897 : /* Slot wrappers that call the corresponding __foo__ slot. See comments
4898 : below at override_slots() for more explanation. */
4899 :
4900 : #define SLOT0(FUNCNAME, OPSTR) \
4901 : static PyObject * \
4902 : FUNCNAME(PyObject *self) \
4903 : { \
4904 : _Py_static_string(id, OPSTR); \
4905 : return call_method(self, &id, "()"); \
4906 : }
4907 :
4908 : #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4909 : static PyObject * \
4910 : FUNCNAME(PyObject *self, ARG1TYPE arg1) \
4911 : { \
4912 : _Py_static_string(id, OPSTR); \
4913 : return call_method(self, &id, "(" ARGCODES ")", arg1); \
4914 : }
4915 :
4916 : /* Boolean helper for SLOT1BINFULL().
4917 : right.__class__ is a nontrivial subclass of left.__class__. */
4918 : static int
4919 0 : method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
4920 : {
4921 : PyObject *a, *b;
4922 : int ok;
4923 :
4924 0 : b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
4925 0 : if (b == NULL) {
4926 0 : PyErr_Clear();
4927 : /* If right doesn't have it, it's not overloaded */
4928 0 : return 0;
4929 : }
4930 :
4931 0 : a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
4932 0 : if (a == NULL) {
4933 0 : PyErr_Clear();
4934 0 : Py_DECREF(b);
4935 : /* If right has it but left doesn't, it's overloaded */
4936 0 : return 1;
4937 : }
4938 :
4939 0 : ok = PyObject_RichCompareBool(a, b, Py_NE);
4940 0 : Py_DECREF(a);
4941 0 : Py_DECREF(b);
4942 0 : if (ok < 0) {
4943 0 : PyErr_Clear();
4944 0 : return 0;
4945 : }
4946 :
4947 0 : return ok;
4948 : }
4949 :
4950 :
4951 : #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4952 : static PyObject * \
4953 : FUNCNAME(PyObject *self, PyObject *other) \
4954 : { \
4955 : _Py_static_string(op_id, OPSTR); \
4956 : _Py_static_string(rop_id, ROPSTR); \
4957 : int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4958 : Py_TYPE(other)->tp_as_number != NULL && \
4959 : Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4960 : if (Py_TYPE(self)->tp_as_number != NULL && \
4961 : Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4962 : PyObject *r; \
4963 : if (do_other && \
4964 : PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4965 : method_is_overloaded(self, other, &rop_id)) { \
4966 : r = call_maybe(other, &rop_id, "(O)", self); \
4967 : if (r != Py_NotImplemented) \
4968 : return r; \
4969 : Py_DECREF(r); \
4970 : do_other = 0; \
4971 : } \
4972 : r = call_maybe(self, &op_id, "(O)", other); \
4973 : if (r != Py_NotImplemented || \
4974 : Py_TYPE(other) == Py_TYPE(self)) \
4975 : return r; \
4976 : Py_DECREF(r); \
4977 : } \
4978 : if (do_other) { \
4979 : return call_maybe(other, &rop_id, "(O)", self); \
4980 : } \
4981 : Py_RETURN_NOTIMPLEMENTED; \
4982 : }
4983 :
4984 : #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4985 : SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4986 :
4987 : #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4988 : static PyObject * \
4989 : FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4990 : { \
4991 : _Py_static_string(id, #OPSTR); \
4992 : return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
4993 : }
4994 :
4995 : static Py_ssize_t
4996 714 : slot_sq_length(PyObject *self)
4997 : {
4998 : _Py_IDENTIFIER(__len__);
4999 714 : PyObject *res = call_method(self, &PyId___len__, "()");
5000 : Py_ssize_t len;
5001 :
5002 714 : if (res == NULL)
5003 0 : return -1;
5004 714 : len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5005 714 : Py_DECREF(res);
5006 714 : if (len < 0) {
5007 0 : if (!PyErr_Occurred())
5008 0 : PyErr_SetString(PyExc_ValueError,
5009 : "__len__() should return >= 0");
5010 0 : return -1;
5011 : }
5012 714 : return len;
5013 : }
5014 :
5015 : /* Super-optimized version of slot_sq_item.
5016 : Other slots could do the same... */
5017 : static PyObject *
5018 1568 : slot_sq_item(PyObject *self, Py_ssize_t i)
5019 : {
5020 1568 : PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
5021 : descrgetfunc f;
5022 :
5023 1568 : func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
5024 1568 : if (func != NULL) {
5025 1568 : if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5026 0 : Py_INCREF(func);
5027 : else {
5028 1568 : func = f(func, self, (PyObject *)(Py_TYPE(self)));
5029 1568 : if (func == NULL) {
5030 0 : return NULL;
5031 : }
5032 : }
5033 1568 : ival = PyLong_FromSsize_t(i);
5034 1568 : if (ival != NULL) {
5035 1568 : args = PyTuple_New(1);
5036 1568 : if (args != NULL) {
5037 1568 : PyTuple_SET_ITEM(args, 0, ival);
5038 1568 : retval = PyObject_Call(func, args, NULL);
5039 1568 : Py_XDECREF(args);
5040 1568 : Py_XDECREF(func);
5041 1568 : return retval;
5042 : }
5043 : }
5044 : }
5045 : else {
5046 0 : PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
5047 0 : PyErr_SetObject(PyExc_AttributeError, getitem_str);
5048 : }
5049 0 : Py_XDECREF(args);
5050 0 : Py_XDECREF(ival);
5051 0 : Py_XDECREF(func);
5052 0 : return NULL;
5053 : }
5054 :
5055 : static int
5056 0 : slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
5057 : {
5058 : PyObject *res;
5059 : _Py_IDENTIFIER(__delitem__);
5060 : _Py_IDENTIFIER(__setitem__);
5061 :
5062 0 : if (value == NULL)
5063 0 : res = call_method(self, &PyId___delitem__, "(n)", index);
5064 : else
5065 0 : res = call_method(self, &PyId___setitem__, "(nO)", index, value);
5066 0 : if (res == NULL)
5067 0 : return -1;
5068 0 : Py_DECREF(res);
5069 0 : return 0;
5070 : }
5071 :
5072 : static int
5073 59 : slot_sq_contains(PyObject *self, PyObject *value)
5074 : {
5075 : PyObject *func, *res, *args;
5076 59 : int result = -1;
5077 : _Py_IDENTIFIER(__contains__);
5078 :
5079 59 : func = lookup_maybe(self, &PyId___contains__);
5080 59 : if (func != NULL) {
5081 59 : args = PyTuple_Pack(1, value);
5082 59 : if (args == NULL)
5083 0 : res = NULL;
5084 : else {
5085 59 : res = PyObject_Call(func, args, NULL);
5086 59 : Py_DECREF(args);
5087 : }
5088 59 : Py_DECREF(func);
5089 59 : if (res != NULL) {
5090 59 : result = PyObject_IsTrue(res);
5091 59 : Py_DECREF(res);
5092 : }
5093 : }
5094 0 : else if (! PyErr_Occurred()) {
5095 : /* Possible results: -1 and 1 */
5096 0 : result = (int)_PySequence_IterSearch(self, value,
5097 : PY_ITERSEARCH_CONTAINS);
5098 : }
5099 59 : return result;
5100 : }
5101 :
5102 : #define slot_mp_length slot_sq_length
5103 :
5104 845 : SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
5105 :
5106 : static int
5107 198 : slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5108 : {
5109 : PyObject *res;
5110 : _Py_IDENTIFIER(__delitem__);
5111 : _Py_IDENTIFIER(__setitem__);
5112 :
5113 198 : if (value == NULL)
5114 10 : res = call_method(self, &PyId___delitem__, "(O)", key);
5115 : else
5116 188 : res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5117 :
5118 198 : if (res == NULL)
5119 0 : return -1;
5120 198 : Py_DECREF(res);
5121 198 : return 0;
5122 : }
5123 :
5124 0 : SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5125 0 : SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5126 0 : SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5127 0 : SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5128 0 : SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5129 :
5130 : static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
5131 :
5132 0 : SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
5133 : nb_power, "__pow__", "__rpow__")
5134 :
5135 : static PyObject *
5136 0 : slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5137 : {
5138 : _Py_IDENTIFIER(__pow__);
5139 :
5140 0 : if (modulus == Py_None)
5141 0 : return slot_nb_power_binary(self, other);
5142 : /* Three-arg power doesn't use __rpow__. But ternary_op
5143 : can call this when the second argument's type uses
5144 : slot_nb_power, so check before calling self.__pow__. */
5145 0 : if (Py_TYPE(self)->tp_as_number != NULL &&
5146 0 : Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5147 0 : return call_method(self, &PyId___pow__, "(OO)", other, modulus);
5148 : }
5149 0 : Py_RETURN_NOTIMPLEMENTED;
5150 : }
5151 :
5152 0 : SLOT0(slot_nb_negative, "__neg__")
5153 0 : SLOT0(slot_nb_positive, "__pos__")
5154 0 : SLOT0(slot_nb_absolute, "__abs__")
5155 :
5156 : static int
5157 0 : slot_nb_bool(PyObject *self)
5158 : {
5159 : PyObject *func, *args;
5160 0 : int result = -1;
5161 0 : int using_len = 0;
5162 : _Py_IDENTIFIER(__len__);
5163 : _Py_IDENTIFIER(__bool__);
5164 :
5165 0 : func = lookup_maybe(self, &PyId___bool__);
5166 0 : if (func == NULL) {
5167 0 : if (PyErr_Occurred())
5168 0 : return -1;
5169 0 : func = lookup_maybe(self, &PyId___len__);
5170 0 : if (func == NULL)
5171 0 : return PyErr_Occurred() ? -1 : 1;
5172 0 : using_len = 1;
5173 : }
5174 0 : args = PyTuple_New(0);
5175 0 : if (args != NULL) {
5176 0 : PyObject *temp = PyObject_Call(func, args, NULL);
5177 0 : Py_DECREF(args);
5178 0 : if (temp != NULL) {
5179 0 : if (using_len) {
5180 : /* enforced by slot_nb_len */
5181 0 : result = PyObject_IsTrue(temp);
5182 : }
5183 0 : else if (PyBool_Check(temp)) {
5184 0 : result = PyObject_IsTrue(temp);
5185 : }
5186 : else {
5187 0 : PyErr_Format(PyExc_TypeError,
5188 : "__bool__ should return "
5189 : "bool, returned %s",
5190 0 : Py_TYPE(temp)->tp_name);
5191 0 : result = -1;
5192 : }
5193 0 : Py_DECREF(temp);
5194 : }
5195 : }
5196 0 : Py_DECREF(func);
5197 0 : return result;
5198 : }
5199 :
5200 :
5201 : static PyObject *
5202 0 : slot_nb_index(PyObject *self)
5203 : {
5204 : _Py_IDENTIFIER(__index__);
5205 0 : return call_method(self, &PyId___index__, "()");
5206 : }
5207 :
5208 :
5209 0 : SLOT0(slot_nb_invert, "__invert__")
5210 0 : SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5211 0 : SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5212 0 : SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5213 0 : SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5214 0 : SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
5215 :
5216 0 : SLOT0(slot_nb_int, "__int__")
5217 0 : SLOT0(slot_nb_float, "__float__")
5218 0 : SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5219 0 : SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5220 0 : SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5221 0 : SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
5222 : /* Can't use SLOT1 here, because nb_inplace_power is ternary */
5223 : static PyObject *
5224 0 : slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5225 : {
5226 : _Py_IDENTIFIER(__ipow__);
5227 0 : return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
5228 : }
5229 0 : SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5230 0 : SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5231 0 : SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5232 0 : SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5233 0 : SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5234 0 : SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5235 : "__floordiv__", "__rfloordiv__")
5236 0 : SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5237 0 : SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5238 0 : SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
5239 :
5240 : static PyObject *
5241 0 : slot_tp_repr(PyObject *self)
5242 : {
5243 : PyObject *func, *res;
5244 : _Py_IDENTIFIER(__repr__);
5245 :
5246 0 : func = lookup_method(self, &PyId___repr__);
5247 0 : if (func != NULL) {
5248 0 : res = PyEval_CallObject(func, NULL);
5249 0 : Py_DECREF(func);
5250 0 : return res;
5251 : }
5252 0 : PyErr_Clear();
5253 0 : return PyUnicode_FromFormat("<%s object at %p>",
5254 0 : Py_TYPE(self)->tp_name, self);
5255 : }
5256 :
5257 : static PyObject *
5258 0 : slot_tp_str(PyObject *self)
5259 : {
5260 : PyObject *func, *res;
5261 : _Py_IDENTIFIER(__str__);
5262 :
5263 0 : func = lookup_method(self, &PyId___str__);
5264 0 : if (func != NULL) {
5265 0 : res = PyEval_CallObject(func, NULL);
5266 0 : Py_DECREF(func);
5267 0 : return res;
5268 : }
5269 : else {
5270 : /* PyObject *ress; */
5271 0 : PyErr_Clear();
5272 0 : res = slot_tp_repr(self);
5273 0 : if (!res)
5274 0 : return NULL;
5275 : /* XXX this is non-sensical. Why should we return
5276 : a bytes object from __str__. Is this code even
5277 : used? - mvl */
5278 : assert(0);
5279 0 : return res;
5280 : /*
5281 : ress = _PyUnicode_AsDefaultEncodedString(res);
5282 : Py_DECREF(res);
5283 : return ress;
5284 : */
5285 : }
5286 : }
5287 :
5288 : static Py_hash_t
5289 302 : slot_tp_hash(PyObject *self)
5290 : {
5291 : PyObject *func, *res;
5292 : Py_ssize_t h;
5293 :
5294 302 : func = lookup_method(self, &PyId___hash__);
5295 :
5296 302 : if (func == Py_None) {
5297 0 : Py_DECREF(func);
5298 0 : func = NULL;
5299 : }
5300 :
5301 302 : if (func == NULL) {
5302 0 : return PyObject_HashNotImplemented(self);
5303 : }
5304 :
5305 302 : res = PyEval_CallObject(func, NULL);
5306 302 : Py_DECREF(func);
5307 302 : if (res == NULL)
5308 0 : return -1;
5309 :
5310 302 : if (!PyLong_Check(res)) {
5311 0 : PyErr_SetString(PyExc_TypeError,
5312 : "__hash__ method should return an integer");
5313 0 : return -1;
5314 : }
5315 : /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing
5316 : hashable Python object x, hash(x) will always lie within the range of
5317 : Py_hash_t. Therefore our transformation must preserve values that
5318 : already lie within this range, to ensure that if x.__hash__() returns
5319 : hash(y) then hash(x) == hash(y). */
5320 302 : h = PyLong_AsSsize_t(res);
5321 302 : if (h == -1 && PyErr_Occurred()) {
5322 : /* res was not within the range of a Py_hash_t, so we're free to
5323 : use any sufficiently bit-mixing transformation;
5324 : long.__hash__ will do nicely. */
5325 0 : PyErr_Clear();
5326 0 : h = PyLong_Type.tp_hash(res);
5327 : }
5328 : /* -1 is reserved for errors. */
5329 302 : if (h == -1)
5330 0 : h = -2;
5331 302 : Py_DECREF(res);
5332 302 : return h;
5333 : }
5334 :
5335 : static PyObject *
5336 0 : slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5337 : {
5338 : _Py_IDENTIFIER(__call__);
5339 0 : PyObject *meth = lookup_method(self, &PyId___call__);
5340 : PyObject *res;
5341 :
5342 0 : if (meth == NULL)
5343 0 : return NULL;
5344 :
5345 0 : res = PyObject_Call(meth, args, kwds);
5346 :
5347 0 : Py_DECREF(meth);
5348 0 : return res;
5349 : }
5350 :
5351 : /* There are two slot dispatch functions for tp_getattro.
5352 :
5353 : - slot_tp_getattro() is used when __getattribute__ is overridden
5354 : but no __getattr__ hook is present;
5355 :
5356 : - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5357 :
5358 : The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5359 : detects the absence of __getattr__ and then installs the simpler slot if
5360 : necessary. */
5361 :
5362 : static PyObject *
5363 0 : slot_tp_getattro(PyObject *self, PyObject *name)
5364 : {
5365 0 : return call_method(self, &PyId___getattribute__, "(O)", name);
5366 : }
5367 :
5368 : static PyObject *
5369 81 : call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5370 : {
5371 81 : PyObject *res, *descr = NULL;
5372 81 : descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
5373 :
5374 81 : if (f != NULL) {
5375 81 : descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5376 81 : if (descr == NULL)
5377 0 : return NULL;
5378 : else
5379 81 : attr = descr;
5380 : }
5381 81 : res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5382 81 : Py_XDECREF(descr);
5383 81 : return res;
5384 : }
5385 :
5386 : static PyObject *
5387 1188 : slot_tp_getattr_hook(PyObject *self, PyObject *name)
5388 : {
5389 1188 : PyTypeObject *tp = Py_TYPE(self);
5390 : PyObject *getattr, *getattribute, *res;
5391 : _Py_IDENTIFIER(__getattr__);
5392 :
5393 : /* speed hack: we could use lookup_maybe, but that would resolve the
5394 : method fully for each attribute lookup for classes with
5395 : __getattr__, even when the attribute is present. So we use
5396 : _PyType_Lookup and create the method only when needed, with
5397 : call_attribute. */
5398 1188 : getattr = _PyType_LookupId(tp, &PyId___getattr__);
5399 1188 : if (getattr == NULL) {
5400 : /* No __getattr__ hook: use a simpler dispatcher */
5401 0 : tp->tp_getattro = slot_tp_getattro;
5402 0 : return slot_tp_getattro(self, name);
5403 : }
5404 1188 : Py_INCREF(getattr);
5405 : /* speed hack: we could use lookup_maybe, but that would resolve the
5406 : method fully for each attribute lookup for classes with
5407 : __getattr__, even when self has the default __getattribute__
5408 : method. So we use _PyType_Lookup and create the method only when
5409 : needed, with call_attribute. */
5410 1188 : getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
5411 2376 : if (getattribute == NULL ||
5412 2376 : (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5413 1188 : ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5414 : (void *)PyObject_GenericGetAttr))
5415 1188 : res = PyObject_GenericGetAttr(self, name);
5416 : else {
5417 0 : Py_INCREF(getattribute);
5418 0 : res = call_attribute(self, getattribute, name);
5419 0 : Py_DECREF(getattribute);
5420 : }
5421 1188 : if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5422 81 : PyErr_Clear();
5423 81 : res = call_attribute(self, getattr, name);
5424 : }
5425 1188 : Py_DECREF(getattr);
5426 1188 : return res;
5427 : }
5428 :
5429 : static int
5430 304 : slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5431 : {
5432 : PyObject *res;
5433 : _Py_IDENTIFIER(__delattr__);
5434 : _Py_IDENTIFIER(__setattr__);
5435 :
5436 304 : if (value == NULL)
5437 0 : res = call_method(self, &PyId___delattr__, "(O)", name);
5438 : else
5439 304 : res = call_method(self, &PyId___setattr__, "(OO)", name, value);
5440 304 : if (res == NULL)
5441 28 : return -1;
5442 276 : Py_DECREF(res);
5443 276 : return 0;
5444 : }
5445 :
5446 : static _Py_Identifier name_op[] = {
5447 : {0, "__lt__", 0},
5448 : {0, "__le__", 0},
5449 : {0, "__eq__", 0},
5450 : {0, "__ne__", 0},
5451 : {0, "__gt__", 0},
5452 : {0, "__ge__", 0}
5453 : };
5454 :
5455 : static PyObject *
5456 3 : slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5457 : {
5458 : PyObject *func, *args, *res;
5459 :
5460 3 : func = lookup_method(self, &name_op[op]);
5461 3 : if (func == NULL) {
5462 0 : PyErr_Clear();
5463 0 : Py_RETURN_NOTIMPLEMENTED;
5464 : }
5465 3 : args = PyTuple_Pack(1, other);
5466 3 : if (args == NULL)
5467 0 : res = NULL;
5468 : else {
5469 3 : res = PyObject_Call(func, args, NULL);
5470 3 : Py_DECREF(args);
5471 : }
5472 3 : Py_DECREF(func);
5473 3 : return res;
5474 : }
5475 :
5476 : static PyObject *
5477 22 : slot_tp_iter(PyObject *self)
5478 : {
5479 : PyObject *func, *res;
5480 : _Py_IDENTIFIER(__iter__);
5481 :
5482 22 : func = lookup_method(self, &PyId___iter__);
5483 22 : if (func != NULL) {
5484 : PyObject *args;
5485 22 : args = res = PyTuple_New(0);
5486 22 : if (args != NULL) {
5487 22 : res = PyObject_Call(func, args, NULL);
5488 22 : Py_DECREF(args);
5489 : }
5490 22 : Py_DECREF(func);
5491 22 : return res;
5492 : }
5493 0 : PyErr_Clear();
5494 0 : func = lookup_method(self, &PyId___getitem__);
5495 0 : if (func == NULL) {
5496 0 : PyErr_Format(PyExc_TypeError,
5497 : "'%.200s' object is not iterable",
5498 0 : Py_TYPE(self)->tp_name);
5499 0 : return NULL;
5500 : }
5501 0 : Py_DECREF(func);
5502 0 : return PySeqIter_New(self);
5503 : }
5504 :
5505 : static PyObject *
5506 0 : slot_tp_iternext(PyObject *self)
5507 : {
5508 : _Py_IDENTIFIER(__next__);
5509 0 : return call_method(self, &PyId___next__, "()");
5510 : }
5511 :
5512 : static PyObject *
5513 0 : slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5514 : {
5515 0 : PyTypeObject *tp = Py_TYPE(self);
5516 : PyObject *get;
5517 : _Py_IDENTIFIER(__get__);
5518 :
5519 0 : get = _PyType_LookupId(tp, &PyId___get__);
5520 0 : if (get == NULL) {
5521 : /* Avoid further slowdowns */
5522 0 : if (tp->tp_descr_get == slot_tp_descr_get)
5523 0 : tp->tp_descr_get = NULL;
5524 0 : Py_INCREF(self);
5525 0 : return self;
5526 : }
5527 0 : if (obj == NULL)
5528 0 : obj = Py_None;
5529 0 : if (type == NULL)
5530 0 : type = Py_None;
5531 0 : return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
5532 : }
5533 :
5534 : static int
5535 0 : slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5536 : {
5537 : PyObject *res;
5538 : _Py_IDENTIFIER(__delete__);
5539 : _Py_IDENTIFIER(__set__);
5540 :
5541 0 : if (value == NULL)
5542 0 : res = call_method(self, &PyId___delete__, "(O)", target);
5543 : else
5544 0 : res = call_method(self, &PyId___set__, "(OO)", target, value);
5545 0 : if (res == NULL)
5546 0 : return -1;
5547 0 : Py_DECREF(res);
5548 0 : return 0;
5549 : }
5550 :
5551 : static int
5552 1483 : slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5553 : {
5554 : _Py_IDENTIFIER(__init__);
5555 1483 : PyObject *meth = lookup_method(self, &PyId___init__);
5556 : PyObject *res;
5557 :
5558 1483 : if (meth == NULL)
5559 0 : return -1;
5560 1483 : res = PyObject_Call(meth, args, kwds);
5561 1483 : Py_DECREF(meth);
5562 1483 : if (res == NULL)
5563 12 : return -1;
5564 1471 : if (res != Py_None) {
5565 0 : PyErr_Format(PyExc_TypeError,
5566 : "__init__() should return None, not '%.200s'",
5567 0 : Py_TYPE(res)->tp_name);
5568 0 : Py_DECREF(res);
5569 0 : return -1;
5570 : }
5571 1471 : Py_DECREF(res);
5572 1471 : return 0;
5573 : }
5574 :
5575 : static PyObject *
5576 30 : slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5577 : {
5578 : PyObject *func;
5579 : PyObject *newargs, *x;
5580 : Py_ssize_t i, n;
5581 : _Py_IDENTIFIER(__new__);
5582 :
5583 30 : func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
5584 30 : if (func == NULL)
5585 0 : return NULL;
5586 : assert(PyTuple_Check(args));
5587 30 : n = PyTuple_GET_SIZE(args);
5588 30 : newargs = PyTuple_New(n+1);
5589 30 : if (newargs == NULL)
5590 0 : return NULL;
5591 30 : Py_INCREF(type);
5592 30 : PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5593 117 : for (i = 0; i < n; i++) {
5594 87 : x = PyTuple_GET_ITEM(args, i);
5595 87 : Py_INCREF(x);
5596 87 : PyTuple_SET_ITEM(newargs, i+1, x);
5597 : }
5598 30 : x = PyObject_Call(func, newargs, kwds);
5599 30 : Py_DECREF(newargs);
5600 30 : Py_DECREF(func);
5601 30 : return x;
5602 : }
5603 :
5604 : static void
5605 0 : slot_tp_del(PyObject *self)
5606 : {
5607 : _Py_IDENTIFIER(__del__);
5608 : PyObject *del, *res;
5609 : PyObject *error_type, *error_value, *error_traceback;
5610 :
5611 : /* Temporarily resurrect the object. */
5612 : assert(self->ob_refcnt == 0);
5613 0 : self->ob_refcnt = 1;
5614 :
5615 : /* Save the current exception, if any. */
5616 0 : PyErr_Fetch(&error_type, &error_value, &error_traceback);
5617 :
5618 : /* Execute __del__ method, if any. */
5619 0 : del = lookup_maybe(self, &PyId___del__);
5620 0 : if (del != NULL) {
5621 0 : res = PyEval_CallObject(del, NULL);
5622 0 : if (res == NULL)
5623 0 : PyErr_WriteUnraisable(del);
5624 : else
5625 0 : Py_DECREF(res);
5626 0 : Py_DECREF(del);
5627 : }
5628 :
5629 : /* Restore the saved exception. */
5630 0 : PyErr_Restore(error_type, error_value, error_traceback);
5631 :
5632 : /* Undo the temporary resurrection; can't use DECREF here, it would
5633 : * cause a recursive call.
5634 : */
5635 : assert(self->ob_refcnt > 0);
5636 0 : if (--self->ob_refcnt == 0)
5637 0 : return; /* this is the normal path out */
5638 :
5639 : /* __del__ resurrected it! Make it look like the original Py_DECREF
5640 : * never happened.
5641 : */
5642 : {
5643 0 : Py_ssize_t refcnt = self->ob_refcnt;
5644 0 : _Py_NewReference(self);
5645 0 : self->ob_refcnt = refcnt;
5646 : }
5647 : assert(!PyType_IS_GC(Py_TYPE(self)) ||
5648 : _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5649 : /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5650 : * we need to undo that. */
5651 : _Py_DEC_REFTOTAL;
5652 : /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5653 : * chain, so no more to do there.
5654 : * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5655 : * _Py_NewReference bumped tp_allocs: both of those need to be
5656 : * undone.
5657 : */
5658 : #ifdef COUNT_ALLOCS
5659 : --Py_TYPE(self)->tp_frees;
5660 : --Py_TYPE(self)->tp_allocs;
5661 : #endif
5662 : }
5663 :
5664 :
5665 : /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
5666 : functions. The offsets here are relative to the 'PyHeapTypeObject'
5667 : structure, which incorporates the additional structures used for numbers,
5668 : sequences and mappings.
5669 : Note that multiple names may map to the same slot (e.g. __eq__,
5670 : __ne__ etc. all map to tp_richcompare) and one name may map to multiple
5671 : slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5672 : terminated with an all-zero entry. (This table is further initialized and
5673 : sorted in init_slotdefs() below.) */
5674 :
5675 : typedef struct wrapperbase slotdef;
5676 :
5677 : #undef TPSLOT
5678 : #undef FLSLOT
5679 : #undef ETSLOT
5680 : #undef SQSLOT
5681 : #undef MPSLOT
5682 : #undef NBSLOT
5683 : #undef UNSLOT
5684 : #undef IBSLOT
5685 : #undef BINSLOT
5686 : #undef RBINSLOT
5687 :
5688 : #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5689 : {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5690 : PyDoc_STR(DOC)}
5691 : #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5692 : {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5693 : PyDoc_STR(DOC), FLAGS}
5694 : #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5695 : {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5696 : PyDoc_STR(DOC)}
5697 : #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5698 : ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5699 : #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5700 : ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5701 : #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5702 : ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5703 : #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5704 : ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5705 : "x." NAME "() <==> " DOC)
5706 : #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5707 : ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5708 : "x." NAME "(y) <==> x" DOC "y")
5709 : #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5710 : ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5711 : "x." NAME "(y) <==> x" DOC "y")
5712 : #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5713 : ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5714 : "x." NAME "(y) <==> y" DOC "x")
5715 : #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5716 : ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5717 : "x." NAME "(y) <==> " DOC)
5718 : #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5719 : ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5720 : "x." NAME "(y) <==> " DOC)
5721 :
5722 : static slotdef slotdefs[] = {
5723 : SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5724 : "x.__len__() <==> len(x)"),
5725 : /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5726 : The logic in abstract.c always falls back to nb_add/nb_multiply in
5727 : this case. Defining both the nb_* and the sq_* slots to call the
5728 : user-defined methods has unexpected side-effects, as shown by
5729 : test_descr.notimplemented() */
5730 : SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5731 : "x.__add__(y) <==> x+y"),
5732 : SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5733 : "x.__mul__(n) <==> x*n"),
5734 : SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5735 : "x.__rmul__(n) <==> n*x"),
5736 : SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5737 : "x.__getitem__(y) <==> x[y]"),
5738 : SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5739 : "x.__setitem__(i, y) <==> x[i]=y"),
5740 : SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5741 : "x.__delitem__(y) <==> del x[y]"),
5742 : SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5743 : "x.__contains__(y) <==> y in x"),
5744 : SQSLOT("__iadd__", sq_inplace_concat, NULL,
5745 : wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5746 : SQSLOT("__imul__", sq_inplace_repeat, NULL,
5747 : wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5748 :
5749 : MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5750 : "x.__len__() <==> len(x)"),
5751 : MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5752 : wrap_binaryfunc,
5753 : "x.__getitem__(y) <==> x[y]"),
5754 : MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5755 : wrap_objobjargproc,
5756 : "x.__setitem__(i, y) <==> x[i]=y"),
5757 : MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5758 : wrap_delitem,
5759 : "x.__delitem__(y) <==> del x[y]"),
5760 :
5761 : BINSLOT("__add__", nb_add, slot_nb_add,
5762 : "+"),
5763 : RBINSLOT("__radd__", nb_add, slot_nb_add,
5764 : "+"),
5765 : BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5766 : "-"),
5767 : RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5768 : "-"),
5769 : BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5770 : "*"),
5771 : RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5772 : "*"),
5773 : BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5774 : "%"),
5775 : RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5776 : "%"),
5777 : BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5778 : "divmod(x, y)"),
5779 : RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5780 : "divmod(y, x)"),
5781 : NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5782 : "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5783 : NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5784 : "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5785 : UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5786 : UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5787 : UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5788 : "abs(x)"),
5789 : UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
5790 : "x != 0"),
5791 : UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5792 : BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5793 : RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5794 : BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5795 : RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5796 : BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5797 : RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5798 : BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5799 : RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5800 : BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5801 : RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5802 : UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5803 : "int(x)"),
5804 : UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5805 : "float(x)"),
5806 : NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5807 : "x[y:z] <==> x[y.__index__():z.__index__()]"),
5808 : IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5809 : wrap_binaryfunc, "+="),
5810 : IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5811 : wrap_binaryfunc, "-="),
5812 : IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5813 : wrap_binaryfunc, "*="),
5814 : IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5815 : wrap_binaryfunc, "%="),
5816 : IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5817 : wrap_binaryfunc, "**="),
5818 : IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5819 : wrap_binaryfunc, "<<="),
5820 : IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5821 : wrap_binaryfunc, ">>="),
5822 : IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5823 : wrap_binaryfunc, "&="),
5824 : IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5825 : wrap_binaryfunc, "^="),
5826 : IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5827 : wrap_binaryfunc, "|="),
5828 : BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5829 : RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5830 : BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5831 : RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5832 : IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5833 : slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5834 : IBSLOT("__itruediv__", nb_inplace_true_divide,
5835 : slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
5836 :
5837 : TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5838 : "x.__str__() <==> str(x)"),
5839 : TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5840 : "x.__repr__() <==> repr(x)"),
5841 : TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5842 : "x.__hash__() <==> hash(x)"),
5843 : FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5844 : "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5845 : TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5846 : wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5847 : TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5848 : TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5849 : TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5850 : TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5851 : "x.__setattr__('name', value) <==> x.name = value"),
5852 : TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5853 : TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5854 : "x.__delattr__('name') <==> del x.name"),
5855 : TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5856 : TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5857 : "x.__lt__(y) <==> x<y"),
5858 : TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5859 : "x.__le__(y) <==> x<=y"),
5860 : TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5861 : "x.__eq__(y) <==> x==y"),
5862 : TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5863 : "x.__ne__(y) <==> x!=y"),
5864 : TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5865 : "x.__gt__(y) <==> x>y"),
5866 : TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5867 : "x.__ge__(y) <==> x>=y"),
5868 : TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5869 : "x.__iter__() <==> iter(x)"),
5870 : TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5871 : "x.__next__() <==> next(x)"),
5872 : TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5873 : "descr.__get__(obj[, type]) -> value"),
5874 : TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5875 : "descr.__set__(obj, value)"),
5876 : TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5877 : wrap_descr_delete, "descr.__delete__(obj)"),
5878 : FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5879 : "x.__init__(...) initializes x; "
5880 : "see help(type(x)) for signature",
5881 : PyWrapperFlag_KEYWORDS),
5882 : TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5883 : TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5884 : {NULL}
5885 : };
5886 :
5887 : /* Given a type pointer and an offset gotten from a slotdef entry, return a
5888 : pointer to the actual slot. This is not quite the same as simply adding
5889 : the offset to the type pointer, since it takes care to indirect through the
5890 : proper indirection pointer (as_buffer, etc.); it returns NULL if the
5891 : indirection pointer is NULL. */
5892 : static void **
5893 54692 : slotptr(PyTypeObject *type, int ioffset)
5894 : {
5895 : char *ptr;
5896 54692 : long offset = ioffset;
5897 :
5898 : /* Note: this depends on the order of the members of PyHeapTypeObject! */
5899 : assert(offset >= 0);
5900 : assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5901 54692 : if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5902 6397 : ptr = (char *)type->tp_as_sequence;
5903 6397 : offset -= offsetof(PyHeapTypeObject, as_sequence);
5904 : }
5905 48295 : else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5906 2511 : ptr = (char *)type->tp_as_mapping;
5907 2511 : offset -= offsetof(PyHeapTypeObject, as_mapping);
5908 : }
5909 45784 : else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5910 28221 : ptr = (char *)type->tp_as_number;
5911 28221 : offset -= offsetof(PyHeapTypeObject, as_number);
5912 : }
5913 : else {
5914 17563 : ptr = (char *)type;
5915 : }
5916 54692 : if (ptr != NULL)
5917 43952 : ptr += offset;
5918 54692 : return (void **)ptr;
5919 : }
5920 :
5921 : /* Length of array of slotdef pointers used to store slots with the
5922 : same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5923 : the same __name__, for any __name__. Since that's a static property, it is
5924 : appropriate to declare fixed-size arrays for this. */
5925 : #define MAX_EQUIV 10
5926 :
5927 : /* Return a slot pointer for a given name, but ONLY if the attribute has
5928 : exactly one slot function. The name must be an interned string. */
5929 : static void **
5930 3867 : resolve_slotdups(PyTypeObject *type, PyObject *name)
5931 : {
5932 : /* XXX Maybe this could be optimized more -- but is it worth it? */
5933 :
5934 : /* pname and ptrs act as a little cache */
5935 : static PyObject *pname;
5936 : static slotdef *ptrs[MAX_EQUIV];
5937 : slotdef *p, **pp;
5938 : void **res, **ptr;
5939 :
5940 3867 : if (pname != name) {
5941 : /* Collect all slotdefs that match name into ptrs. */
5942 3854 : pname = name;
5943 3854 : pp = ptrs;
5944 335298 : for (p = slotdefs; p->name_strobj; p++) {
5945 331444 : if (p->name_strobj == name)
5946 5395 : *pp++ = p;
5947 : }
5948 3854 : *pp = NULL;
5949 : }
5950 :
5951 : /* Look in all matching slots of the type; if exactly one of these has
5952 : a filled-in slot, return its value. Otherwise return NULL. */
5953 3867 : res = NULL;
5954 9265 : for (pp = ptrs; *pp; pp++) {
5955 5421 : ptr = slotptr(type, (*pp)->offset);
5956 5421 : if (ptr == NULL || *ptr == NULL)
5957 1572 : continue;
5958 3849 : if (res != NULL)
5959 23 : return NULL;
5960 3826 : res = ptr;
5961 : }
5962 3844 : return res;
5963 : }
5964 :
5965 : /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
5966 : does some incredibly complex thinking and then sticks something into the
5967 : slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5968 : interests, and then stores a generic wrapper or a specific function into
5969 : the slot.) Return a pointer to the next slotdef with a different offset,
5970 : because that's convenient for fixup_slot_dispatchers(). */
5971 : static slotdef *
5972 14748 : update_one_slot(PyTypeObject *type, slotdef *p)
5973 : {
5974 : PyObject *descr;
5975 : PyWrapperDescrObject *d;
5976 14748 : void *generic = NULL, *specific = NULL;
5977 14748 : int use_generic = 0;
5978 14748 : int offset = p->offset;
5979 14748 : void **ptr = slotptr(type, offset);
5980 :
5981 14748 : if (ptr == NULL) {
5982 : do {
5983 0 : ++p;
5984 0 : } while (p->offset == offset);
5985 0 : return p;
5986 : }
5987 : do {
5988 21172 : descr = _PyType_Lookup(type, p->name_strobj);
5989 21172 : if (descr == NULL) {
5990 16542 : if (ptr == (void**)&type->tp_iternext) {
5991 233 : specific = _PyObject_NextNotImplemented;
5992 : }
5993 16542 : continue;
5994 : }
5995 8497 : if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
5996 7734 : ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
5997 3867 : void **tptr = resolve_slotdups(type, p->name_strobj);
5998 3867 : if (tptr == NULL || tptr == ptr)
5999 3101 : generic = p->function;
6000 3867 : d = (PyWrapperDescrObject *)descr;
6001 6965 : if (d->d_base->wrapper == p->wrapper &&
6002 3098 : PyType_IsSubtype(type, PyDescr_TYPE(d)))
6003 : {
6004 4542 : if (specific == NULL ||
6005 1444 : specific == d->d_wrapped)
6006 3098 : specific = d->d_wrapped;
6007 : else
6008 0 : use_generic = 1;
6009 : }
6010 : }
6011 1001 : else if (Py_TYPE(descr) == &PyCFunction_Type &&
6012 238 : PyCFunction_GET_FUNCTION(descr) ==
6013 238 : (PyCFunction)tp_new_wrapper &&
6014 238 : ptr == (void**)&type->tp_new)
6015 : {
6016 : /* The __new__ wrapper is not a wrapper descriptor,
6017 : so must be special-cased differently.
6018 : If we don't do this, creating an instance will
6019 : always use slot_tp_new which will look up
6020 : __new__ in the MRO which will call tp_new_wrapper
6021 : which will look through the base classes looking
6022 : for a static base and call its tp_new (usually
6023 : PyType_GenericNew), after performing various
6024 : sanity checks and constructing a new argument
6025 : list. Cut all that nonsense short -- this speeds
6026 : up instance creation tremendously. */
6027 238 : specific = (void *)type->tp_new;
6028 : /* XXX I'm not 100% sure that there isn't a hole
6029 : in this reasoning that requires additional
6030 : sanity checks. I'll buy the first person to
6031 : point out a bug in this reasoning a beer. */
6032 : }
6033 542 : else if (descr == Py_None &&
6034 17 : ptr == (void**)&type->tp_hash) {
6035 : /* We specifically allow __hash__ to be set to None
6036 : to prevent inheritance of the default
6037 : implementation from object.__hash__ */
6038 17 : specific = PyObject_HashNotImplemented;
6039 : }
6040 : else {
6041 508 : use_generic = 1;
6042 508 : generic = p->function;
6043 : }
6044 21172 : } while ((++p)->offset == offset);
6045 14748 : if (specific && !use_generic)
6046 2097 : *ptr = specific;
6047 : else
6048 12651 : *ptr = generic;
6049 14748 : return p;
6050 : }
6051 :
6052 : /* In the type, update the slots whose slotdefs are gathered in the pp array.
6053 : This is a callback for update_subclasses(). */
6054 : static int
6055 36 : update_slots_callback(PyTypeObject *type, void *data)
6056 : {
6057 36 : slotdef **pp = (slotdef **)data;
6058 :
6059 84 : for (; *pp; pp++)
6060 48 : update_one_slot(type, *pp);
6061 36 : return 0;
6062 : }
6063 :
6064 : /* Comparison function for qsort() to compare slotdefs by their offset, and
6065 : for equal offset by their address (to force a stable sort). */
6066 : static int
6067 331 : slotdef_cmp(const void *aa, const void *bb)
6068 : {
6069 331 : const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6070 331 : int c = a->offset - b->offset;
6071 331 : if (c != 0)
6072 302 : return c;
6073 : else
6074 : /* Cannot use a-b, as this gives off_t,
6075 : which may lose precision when converted to int. */
6076 29 : return (a > b) ? 1 : (a < b) ? -1 : 0;
6077 : }
6078 :
6079 : /* Initialize the slotdefs table by adding interned string objects for the
6080 : names and sorting the entries. */
6081 : static void
6082 962 : init_slotdefs(void)
6083 : {
6084 : slotdef *p;
6085 : static int initialized = 0;
6086 :
6087 962 : if (initialized)
6088 1923 : return;
6089 87 : for (p = slotdefs; p->name; p++) {
6090 86 : p->name_strobj = PyUnicode_InternFromString(p->name);
6091 86 : if (!p->name_strobj)
6092 0 : Py_FatalError("Out of memory interning slotdef names");
6093 : }
6094 1 : qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6095 : slotdef_cmp);
6096 1 : initialized = 1;
6097 : }
6098 :
6099 : /* Update the slots after assignment to a class (type) attribute. */
6100 : static int
6101 280 : update_slot(PyTypeObject *type, PyObject *name)
6102 : {
6103 : slotdef *ptrs[MAX_EQUIV];
6104 : slotdef *p;
6105 : slotdef **pp;
6106 : int offset;
6107 :
6108 : /* Clear the VALID_VERSION flag of 'type' and all its
6109 : subclasses. This could possibly be unified with the
6110 : update_subclasses() recursion below, but carefully:
6111 : they each have their own conditions on which to stop
6112 : recursing into subclasses. */
6113 280 : PyType_Modified(type);
6114 :
6115 280 : init_slotdefs();
6116 280 : pp = ptrs;
6117 24360 : for (p = slotdefs; p->name; p++) {
6118 : /* XXX assume name is interned! */
6119 24080 : if (p->name_strobj == name)
6120 48 : *pp++ = p;
6121 : }
6122 280 : *pp = NULL;
6123 328 : for (pp = ptrs; *pp; pp++) {
6124 48 : p = *pp;
6125 48 : offset = p->offset;
6126 120 : while (p > slotdefs && (p-1)->offset == offset)
6127 24 : --p;
6128 48 : *pp = p;
6129 : }
6130 280 : if (ptrs[0] == NULL)
6131 244 : return 0; /* Not an attribute that affects any slots */
6132 36 : return update_subclasses(type, name,
6133 : update_slots_callback, (void *)ptrs);
6134 : }
6135 :
6136 : /* Store the proper functions in the slot dispatches at class (type)
6137 : definition time, based upon which operations the class overrides in its
6138 : dict. */
6139 : static void
6140 245 : fixup_slot_dispatchers(PyTypeObject *type)
6141 : {
6142 : slotdef *p;
6143 :
6144 245 : init_slotdefs();
6145 15190 : for (p = slotdefs; p->name; )
6146 14700 : p = update_one_slot(type, p);
6147 245 : }
6148 :
6149 : static void
6150 0 : update_all_slots(PyTypeObject* type)
6151 : {
6152 : slotdef *p;
6153 :
6154 0 : init_slotdefs();
6155 0 : for (p = slotdefs; p->name; p++) {
6156 : /* update_slot returns int but can't actually fail */
6157 0 : update_slot(type, p->name_strobj);
6158 : }
6159 0 : }
6160 :
6161 : /* recurse_down_subclasses() and update_subclasses() are mutually
6162 : recursive functions to call a callback for all subclasses,
6163 : but refraining from recursing into subclasses that define 'name'. */
6164 :
6165 : static int
6166 36 : update_subclasses(PyTypeObject *type, PyObject *name,
6167 : update_callback callback, void *data)
6168 : {
6169 36 : if (callback(type, data) < 0)
6170 0 : return -1;
6171 36 : return recurse_down_subclasses(type, name, callback, data);
6172 : }
6173 :
6174 : static int
6175 36 : recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6176 : update_callback callback, void *data)
6177 : {
6178 : PyTypeObject *subclass;
6179 : PyObject *ref, *subclasses, *dict;
6180 : Py_ssize_t i, n;
6181 :
6182 36 : subclasses = type->tp_subclasses;
6183 36 : if (subclasses == NULL)
6184 36 : return 0;
6185 : assert(PyList_Check(subclasses));
6186 0 : n = PyList_GET_SIZE(subclasses);
6187 0 : for (i = 0; i < n; i++) {
6188 0 : ref = PyList_GET_ITEM(subclasses, i);
6189 : assert(PyWeakref_CheckRef(ref));
6190 0 : subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6191 : assert(subclass != NULL);
6192 0 : if ((PyObject *)subclass == Py_None)
6193 0 : continue;
6194 : assert(PyType_Check(subclass));
6195 : /* Avoid recursing down into unaffected classes */
6196 0 : dict = subclass->tp_dict;
6197 0 : if (dict != NULL && PyDict_Check(dict) &&
6198 0 : PyDict_GetItem(dict, name) != NULL)
6199 0 : continue;
6200 0 : if (update_subclasses(subclass, name, callback, data) < 0)
6201 0 : return -1;
6202 : }
6203 0 : return 0;
6204 : }
6205 :
6206 : /* This function is called by PyType_Ready() to populate the type's
6207 : dictionary with method descriptors for function slots. For each
6208 : function slot (like tp_repr) that's defined in the type, one or more
6209 : corresponding descriptors are added in the type's tp_dict dictionary
6210 : under the appropriate name (like __repr__). Some function slots
6211 : cause more than one descriptor to be added (for example, the nb_add
6212 : slot adds both __add__ and __radd__ descriptors) and some function
6213 : slots compete for the same descriptor (for example both sq_item and
6214 : mp_subscript generate a __getitem__ descriptor).
6215 :
6216 : In the latter case, the first slotdef entry encountered wins. Since
6217 : slotdef entries are sorted by the offset of the slot in the
6218 : PyHeapTypeObject, this gives us some control over disambiguating
6219 : between competing slots: the members of PyHeapTypeObject are listed
6220 : from most general to least general, so the most general slot is
6221 : preferred. In particular, because as_mapping comes before as_sequence,
6222 : for a type that defines both mp_subscript and sq_item, mp_subscript
6223 : wins.
6224 :
6225 : This only adds new descriptors and doesn't overwrite entries in
6226 : tp_dict that were previously defined. The descriptors contain a
6227 : reference to the C function they must call, so that it's safe if they
6228 : are copied into a subtype's __dict__ and the subtype has a different
6229 : C function in its slot -- calling the method defined by the
6230 : descriptor will call the C function that was used to create it,
6231 : rather than the C function present in the slot when it is called.
6232 : (This is important because a subtype may have a C function in the
6233 : slot that calls the method from the dictionary, and we want to avoid
6234 : infinite recursion here.) */
6235 :
6236 : static int
6237 437 : add_operators(PyTypeObject *type)
6238 : {
6239 437 : PyObject *dict = type->tp_dict;
6240 : slotdef *p;
6241 : PyObject *descr;
6242 : void **ptr;
6243 :
6244 437 : init_slotdefs();
6245 38019 : for (p = slotdefs; p->name; p++) {
6246 37582 : if (p->wrapper == NULL)
6247 3059 : continue;
6248 34523 : ptr = slotptr(type, p->offset);
6249 34523 : if (!ptr || !*ptr)
6250 33596 : continue;
6251 927 : if (PyDict_GetItem(dict, p->name_strobj))
6252 23 : continue;
6253 904 : if (*ptr == PyObject_HashNotImplemented) {
6254 : /* Classes may prevent the inheritance of the tp_hash
6255 : slot by storing PyObject_HashNotImplemented in it. Make it
6256 : visible as a None value for the __hash__ attribute. */
6257 5 : if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6258 0 : return -1;
6259 : }
6260 : else {
6261 899 : descr = PyDescr_NewWrapper(type, p, *ptr);
6262 899 : if (descr == NULL)
6263 0 : return -1;
6264 899 : if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6265 0 : return -1;
6266 899 : Py_DECREF(descr);
6267 : }
6268 : }
6269 437 : if (type->tp_new != NULL) {
6270 134 : if (add_tp_new_wrapper(type) < 0)
6271 0 : return -1;
6272 : }
6273 437 : return 0;
6274 : }
6275 :
6276 :
6277 : /* Cooperative 'super' */
6278 :
6279 : typedef struct {
6280 : PyObject_HEAD
6281 : PyTypeObject *type;
6282 : PyObject *obj;
6283 : PyTypeObject *obj_type;
6284 : } superobject;
6285 :
6286 : static PyMemberDef super_members[] = {
6287 : {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6288 : "the class invoking super()"},
6289 : {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6290 : "the instance invoking super(); may be None"},
6291 : {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6292 : "the type of the instance invoking super(); may be None"},
6293 : {0}
6294 : };
6295 :
6296 : static void
6297 74 : super_dealloc(PyObject *self)
6298 : {
6299 74 : superobject *su = (superobject *)self;
6300 :
6301 74 : _PyObject_GC_UNTRACK(self);
6302 74 : Py_XDECREF(su->obj);
6303 74 : Py_XDECREF(su->type);
6304 74 : Py_XDECREF(su->obj_type);
6305 74 : Py_TYPE(self)->tp_free(self);
6306 74 : }
6307 :
6308 : static PyObject *
6309 0 : super_repr(PyObject *self)
6310 : {
6311 0 : superobject *su = (superobject *)self;
6312 :
6313 0 : if (su->obj_type)
6314 0 : return PyUnicode_FromFormat(
6315 : "<super: <class '%s'>, <%s object>>",
6316 0 : su->type ? su->type->tp_name : "NULL",
6317 0 : su->obj_type->tp_name);
6318 : else
6319 0 : return PyUnicode_FromFormat(
6320 : "<super: <class '%s'>, NULL>",
6321 0 : su->type ? su->type->tp_name : "NULL");
6322 : }
6323 :
6324 : static PyObject *
6325 74 : super_getattro(PyObject *self, PyObject *name)
6326 : {
6327 74 : superobject *su = (superobject *)self;
6328 74 : int skip = su->obj_type == NULL;
6329 :
6330 74 : if (!skip) {
6331 : /* We want __class__ to return the class of the super object
6332 : (i.e. super, or a subclass), not the class of su->obj. */
6333 222 : skip = (PyUnicode_Check(name) &&
6334 74 : PyUnicode_GET_LENGTH(name) == 9 &&
6335 0 : PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
6336 : }
6337 :
6338 74 : if (!skip) {
6339 : PyObject *mro, *res, *tmp, *dict;
6340 : PyTypeObject *starttype;
6341 : descrgetfunc f;
6342 : Py_ssize_t i, n;
6343 :
6344 74 : starttype = su->obj_type;
6345 74 : mro = starttype->tp_mro;
6346 :
6347 74 : if (mro == NULL)
6348 0 : n = 0;
6349 : else {
6350 : assert(PyTuple_Check(mro));
6351 74 : n = PyTuple_GET_SIZE(mro);
6352 : }
6353 119 : for (i = 0; i < n; i++) {
6354 119 : if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6355 74 : break;
6356 : }
6357 74 : i++;
6358 74 : res = NULL;
6359 : /* keep a strong reference to mro because starttype->tp_mro can be
6360 : replaced during PyDict_GetItem(dict, name) */
6361 74 : Py_INCREF(mro);
6362 74 : for (; i < n; i++) {
6363 74 : tmp = PyTuple_GET_ITEM(mro, i);
6364 74 : if (PyType_Check(tmp))
6365 74 : dict = ((PyTypeObject *)tmp)->tp_dict;
6366 : else
6367 0 : continue;
6368 74 : res = PyDict_GetItem(dict, name);
6369 74 : if (res != NULL) {
6370 74 : Py_INCREF(res);
6371 74 : f = Py_TYPE(res)->tp_descr_get;
6372 74 : if (f != NULL) {
6373 45 : tmp = f(res,
6374 : /* Only pass 'obj' param if
6375 : this is instance-mode super
6376 : (See SF ID #743627)
6377 : */
6378 45 : (su->obj == (PyObject *)
6379 45 : su->obj_type
6380 : ? (PyObject *)NULL
6381 : : su->obj),
6382 : (PyObject *)starttype);
6383 45 : Py_DECREF(res);
6384 45 : res = tmp;
6385 : }
6386 74 : Py_DECREF(mro);
6387 74 : return res;
6388 : }
6389 : }
6390 0 : Py_DECREF(mro);
6391 : }
6392 0 : return PyObject_GenericGetAttr(self, name);
6393 : }
6394 :
6395 : static PyTypeObject *
6396 74 : supercheck(PyTypeObject *type, PyObject *obj)
6397 : {
6398 : /* Check that a super() call makes sense. Return a type object.
6399 :
6400 : obj can be a class, or an instance of one:
6401 :
6402 : - If it is a class, it must be a subclass of 'type'. This case is
6403 : used for class methods; the return value is obj.
6404 :
6405 : - If it is an instance, it must be an instance of 'type'. This is
6406 : the normal case; the return value is obj.__class__.
6407 :
6408 : But... when obj is an instance, we want to allow for the case where
6409 : Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6410 : This will allow using super() with a proxy for obj.
6411 : */
6412 :
6413 : /* Check for first bullet above (special case) */
6414 74 : if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6415 29 : Py_INCREF(obj);
6416 29 : return (PyTypeObject *)obj;
6417 : }
6418 :
6419 : /* Normal case */
6420 45 : if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6421 45 : Py_INCREF(Py_TYPE(obj));
6422 45 : return Py_TYPE(obj);
6423 : }
6424 : else {
6425 : /* Try the slow way */
6426 : PyObject *class_attr;
6427 :
6428 0 : class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
6429 0 : if (class_attr != NULL &&
6430 0 : PyType_Check(class_attr) &&
6431 0 : (PyTypeObject *)class_attr != Py_TYPE(obj))
6432 : {
6433 0 : int ok = PyType_IsSubtype(
6434 : (PyTypeObject *)class_attr, type);
6435 0 : if (ok)
6436 0 : return (PyTypeObject *)class_attr;
6437 : }
6438 :
6439 0 : if (class_attr == NULL)
6440 0 : PyErr_Clear();
6441 : else
6442 0 : Py_DECREF(class_attr);
6443 : }
6444 :
6445 0 : PyErr_SetString(PyExc_TypeError,
6446 : "super(type, obj): "
6447 : "obj must be an instance or subtype of type");
6448 0 : return NULL;
6449 : }
6450 :
6451 : static PyObject *
6452 0 : super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6453 : {
6454 0 : superobject *su = (superobject *)self;
6455 : superobject *newobj;
6456 :
6457 0 : if (obj == NULL || obj == Py_None || su->obj != NULL) {
6458 : /* Not binding to an object, or already bound */
6459 0 : Py_INCREF(self);
6460 0 : return self;
6461 : }
6462 0 : if (Py_TYPE(su) != &PySuper_Type)
6463 : /* If su is an instance of a (strict) subclass of super,
6464 : call its type */
6465 0 : return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6466 : su->type, obj, NULL);
6467 : else {
6468 : /* Inline the common case */
6469 0 : PyTypeObject *obj_type = supercheck(su->type, obj);
6470 0 : if (obj_type == NULL)
6471 0 : return NULL;
6472 0 : newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6473 : NULL, NULL);
6474 0 : if (newobj == NULL)
6475 0 : return NULL;
6476 0 : Py_INCREF(su->type);
6477 0 : Py_INCREF(obj);
6478 0 : newobj->type = su->type;
6479 0 : newobj->obj = obj;
6480 0 : newobj->obj_type = obj_type;
6481 0 : return (PyObject *)newobj;
6482 : }
6483 : }
6484 :
6485 : static int
6486 74 : super_init(PyObject *self, PyObject *args, PyObject *kwds)
6487 : {
6488 74 : superobject *su = (superobject *)self;
6489 74 : PyTypeObject *type = NULL;
6490 74 : PyObject *obj = NULL;
6491 74 : PyTypeObject *obj_type = NULL;
6492 :
6493 74 : if (!_PyArg_NoKeywords("super", kwds))
6494 0 : return -1;
6495 74 : if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
6496 0 : return -1;
6497 :
6498 74 : if (type == NULL) {
6499 : /* Call super(), without args -- fill in from __class__
6500 : and first local variable on the stack. */
6501 29 : PyFrameObject *f = PyThreadState_GET()->frame;
6502 29 : PyCodeObject *co = f->f_code;
6503 : Py_ssize_t i, n;
6504 29 : if (co == NULL) {
6505 0 : PyErr_SetString(PyExc_SystemError,
6506 : "super(): no code object");
6507 0 : return -1;
6508 : }
6509 29 : if (co->co_argcount == 0) {
6510 0 : PyErr_SetString(PyExc_SystemError,
6511 : "super(): no arguments");
6512 0 : return -1;
6513 : }
6514 29 : obj = f->f_localsplus[0];
6515 29 : if (obj == NULL) {
6516 0 : PyErr_SetString(PyExc_SystemError,
6517 : "super(): arg[0] deleted");
6518 0 : return -1;
6519 : }
6520 29 : if (co->co_freevars == NULL)
6521 0 : n = 0;
6522 : else {
6523 : assert(PyTuple_Check(co->co_freevars));
6524 29 : n = PyTuple_GET_SIZE(co->co_freevars);
6525 : }
6526 29 : for (i = 0; i < n; i++) {
6527 29 : PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6528 : assert(PyUnicode_Check(name));
6529 29 : if (!PyUnicode_CompareWithASCIIString(name,
6530 : "__class__")) {
6531 58 : Py_ssize_t index = co->co_nlocals +
6532 29 : PyTuple_GET_SIZE(co->co_cellvars) + i;
6533 29 : PyObject *cell = f->f_localsplus[index];
6534 29 : if (cell == NULL || !PyCell_Check(cell)) {
6535 0 : PyErr_SetString(PyExc_SystemError,
6536 : "super(): bad __class__ cell");
6537 0 : return -1;
6538 : }
6539 29 : type = (PyTypeObject *) PyCell_GET(cell);
6540 29 : if (type == NULL) {
6541 0 : PyErr_SetString(PyExc_SystemError,
6542 : "super(): empty __class__ cell");
6543 0 : return -1;
6544 : }
6545 29 : if (!PyType_Check(type)) {
6546 0 : PyErr_Format(PyExc_SystemError,
6547 : "super(): __class__ is not a type (%s)",
6548 0 : Py_TYPE(type)->tp_name);
6549 0 : return -1;
6550 : }
6551 29 : break;
6552 : }
6553 : }
6554 29 : if (type == NULL) {
6555 0 : PyErr_SetString(PyExc_SystemError,
6556 : "super(): __class__ cell not found");
6557 0 : return -1;
6558 : }
6559 : }
6560 :
6561 74 : if (obj == Py_None)
6562 0 : obj = NULL;
6563 74 : if (obj != NULL) {
6564 74 : obj_type = supercheck(type, obj);
6565 74 : if (obj_type == NULL)
6566 0 : return -1;
6567 74 : Py_INCREF(obj);
6568 : }
6569 74 : Py_INCREF(type);
6570 74 : su->type = type;
6571 74 : su->obj = obj;
6572 74 : su->obj_type = obj_type;
6573 74 : return 0;
6574 : }
6575 :
6576 : PyDoc_STRVAR(super_doc,
6577 : "super() -> same as super(__class__, <first argument>)\n"
6578 : "super(type) -> unbound super object\n"
6579 : "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
6580 : "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
6581 : "Typical use to call a cooperative superclass method:\n"
6582 : "class C(B):\n"
6583 : " def meth(self, arg):\n"
6584 : " super().meth(arg)\n"
6585 : "This works for class methods too:\n"
6586 : "class C(B):\n"
6587 : " @classmethod\n"
6588 : " def cmeth(cls, arg):\n"
6589 : " super().cmeth(arg)\n");
6590 :
6591 : static int
6592 0 : super_traverse(PyObject *self, visitproc visit, void *arg)
6593 : {
6594 0 : superobject *su = (superobject *)self;
6595 :
6596 0 : Py_VISIT(su->obj);
6597 0 : Py_VISIT(su->type);
6598 0 : Py_VISIT(su->obj_type);
6599 :
6600 0 : return 0;
6601 : }
6602 :
6603 : PyTypeObject PySuper_Type = {
6604 : PyVarObject_HEAD_INIT(&PyType_Type, 0)
6605 : "super", /* tp_name */
6606 : sizeof(superobject), /* tp_basicsize */
6607 : 0, /* tp_itemsize */
6608 : /* methods */
6609 : super_dealloc, /* tp_dealloc */
6610 : 0, /* tp_print */
6611 : 0, /* tp_getattr */
6612 : 0, /* tp_setattr */
6613 : 0, /* tp_reserved */
6614 : super_repr, /* tp_repr */
6615 : 0, /* tp_as_number */
6616 : 0, /* tp_as_sequence */
6617 : 0, /* tp_as_mapping */
6618 : 0, /* tp_hash */
6619 : 0, /* tp_call */
6620 : 0, /* tp_str */
6621 : super_getattro, /* tp_getattro */
6622 : 0, /* tp_setattro */
6623 : 0, /* tp_as_buffer */
6624 : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6625 : Py_TPFLAGS_BASETYPE, /* tp_flags */
6626 : super_doc, /* tp_doc */
6627 : super_traverse, /* tp_traverse */
6628 : 0, /* tp_clear */
6629 : 0, /* tp_richcompare */
6630 : 0, /* tp_weaklistoffset */
6631 : 0, /* tp_iter */
6632 : 0, /* tp_iternext */
6633 : 0, /* tp_methods */
6634 : super_members, /* tp_members */
6635 : 0, /* tp_getset */
6636 : 0, /* tp_base */
6637 : 0, /* tp_dict */
6638 : super_descr_get, /* tp_descr_get */
6639 : 0, /* tp_descr_set */
6640 : 0, /* tp_dictoffset */
6641 : super_init, /* tp_init */
6642 : PyType_GenericAlloc, /* tp_alloc */
6643 : PyType_GenericNew, /* tp_new */
6644 : PyObject_GC_Del, /* tp_free */
6645 : };
|