blob: 6508c69cbf7e361a35cb416fcca39b50da0ecfec [file] [log] [blame]
Guido van Rossum48b069a2020-04-07 09:50:06 -07001// types.GenericAlias -- used to represent e.g. list[int].
2
3#include "Python.h"
4#include "pycore_object.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02005#include "structmember.h" // PyMemberDef
Guido van Rossum48b069a2020-04-07 09:50:06 -07006
7typedef struct {
8 PyObject_HEAD
9 PyObject *origin;
10 PyObject *args;
11 PyObject *parameters;
12} gaobject;
13
14static void
15ga_dealloc(PyObject *self)
16{
17 gaobject *alias = (gaobject *)self;
18
19 _PyObject_GC_UNTRACK(self);
20 Py_XDECREF(alias->origin);
21 Py_XDECREF(alias->args);
22 Py_XDECREF(alias->parameters);
Victor Stinner8182cc22020-07-10 12:40:38 +020023 Py_TYPE(self)->tp_free(self);
Guido van Rossum48b069a2020-04-07 09:50:06 -070024}
25
26static int
27ga_traverse(PyObject *self, visitproc visit, void *arg)
28{
29 gaobject *alias = (gaobject *)self;
30 Py_VISIT(alias->origin);
31 Py_VISIT(alias->args);
32 Py_VISIT(alias->parameters);
33 return 0;
34}
35
36static int
37ga_repr_item(_PyUnicodeWriter *writer, PyObject *p)
38{
39 _Py_IDENTIFIER(__module__);
40 _Py_IDENTIFIER(__qualname__);
41 _Py_IDENTIFIER(__origin__);
42 _Py_IDENTIFIER(__args__);
43 PyObject *qualname = NULL;
44 PyObject *module = NULL;
45 PyObject *r = NULL;
46 PyObject *tmp;
47 int err;
48
49 if (p == Py_Ellipsis) {
50 // The Ellipsis object
51 r = PyUnicode_FromString("...");
52 goto done;
53 }
54
55 if (_PyObject_LookupAttrId(p, &PyId___origin__, &tmp) < 0) {
56 goto done;
57 }
58 if (tmp != NULL) {
59 Py_DECREF(tmp);
60 if (_PyObject_LookupAttrId(p, &PyId___args__, &tmp) < 0) {
61 goto done;
62 }
63 if (tmp != NULL) {
64 Py_DECREF(tmp);
65 // It looks like a GenericAlias
66 goto use_repr;
67 }
68 }
69
70 if (_PyObject_LookupAttrId(p, &PyId___qualname__, &qualname) < 0) {
71 goto done;
72 }
73 if (qualname == NULL) {
74 goto use_repr;
75 }
76 if (_PyObject_LookupAttrId(p, &PyId___module__, &module) < 0) {
77 goto done;
78 }
79 if (module == NULL || module == Py_None) {
80 goto use_repr;
81 }
82
83 // Looks like a class
84 if (PyUnicode_Check(module) &&
85 _PyUnicode_EqualToASCIIString(module, "builtins"))
86 {
87 // builtins don't need a module name
88 r = PyObject_Str(qualname);
89 goto done;
90 }
91 else {
92 r = PyUnicode_FromFormat("%S.%S", module, qualname);
93 goto done;
94 }
95
96use_repr:
97 r = PyObject_Repr(p);
98
99done:
100 Py_XDECREF(qualname);
101 Py_XDECREF(module);
102 if (r == NULL) {
103 // error if any of the above PyObject_Repr/PyUnicode_From* fail
104 err = -1;
105 }
106 else {
107 err = _PyUnicodeWriter_WriteStr(writer, r);
108 Py_DECREF(r);
109 }
110 return err;
111}
112
113static PyObject *
114ga_repr(PyObject *self)
115{
116 gaobject *alias = (gaobject *)self;
117 Py_ssize_t len = PyTuple_GET_SIZE(alias->args);
118
119 _PyUnicodeWriter writer;
120 _PyUnicodeWriter_Init(&writer);
Victor Stinner4a21e572020-04-15 02:35:41 +0200121
Guido van Rossum48b069a2020-04-07 09:50:06 -0700122 if (ga_repr_item(&writer, alias->origin) < 0) {
123 goto error;
124 }
125 if (_PyUnicodeWriter_WriteASCIIString(&writer, "[", 1) < 0) {
126 goto error;
127 }
128 for (Py_ssize_t i = 0; i < len; i++) {
129 if (i > 0) {
130 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) {
131 goto error;
132 }
133 }
134 PyObject *p = PyTuple_GET_ITEM(alias->args, i);
135 if (ga_repr_item(&writer, p) < 0) {
136 goto error;
137 }
138 }
139 if (len == 0) {
140 // for something like tuple[()] we should print a "()"
141 if (_PyUnicodeWriter_WriteASCIIString(&writer, "()", 2) < 0) {
142 goto error;
143 }
144 }
145 if (_PyUnicodeWriter_WriteASCIIString(&writer, "]", 1) < 0) {
146 goto error;
147 }
148 return _PyUnicodeWriter_Finish(&writer);
149error:
150 _PyUnicodeWriter_Dealloc(&writer);
151 return NULL;
152}
153
154// isinstance(obj, TypeVar) without importing typing.py.
155// Returns -1 for errors.
156static int
157is_typevar(PyObject *obj)
158{
159 PyTypeObject *type = Py_TYPE(obj);
160 if (strcmp(type->tp_name, "TypeVar") != 0) {
161 return 0;
162 }
163 PyObject *module = PyObject_GetAttrString((PyObject *)type, "__module__");
164 if (module == NULL) {
165 return -1;
166 }
167 int res = PyUnicode_Check(module)
168 && _PyUnicode_EqualToASCIIString(module, "typing");
169 Py_DECREF(module);
170 return res;
171}
172
173// Index of item in self[:len], or -1 if not found (self is a tuple)
174static Py_ssize_t
175tuple_index(PyObject *self, Py_ssize_t len, PyObject *item)
176{
177 for (Py_ssize_t i = 0; i < len; i++) {
178 if (PyTuple_GET_ITEM(self, i) == item) {
179 return i;
180 }
181 }
182 return -1;
183}
184
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300185static int
186tuple_add(PyObject *self, Py_ssize_t len, PyObject *item)
187{
188 if (tuple_index(self, len, item) < 0) {
189 Py_INCREF(item);
190 PyTuple_SET_ITEM(self, len, item);
191 return 1;
192 }
193 return 0;
194}
195
Guido van Rossum48b069a2020-04-07 09:50:06 -0700196static PyObject *
197make_parameters(PyObject *args)
198{
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300199 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
200 Py_ssize_t len = nargs;
Guido van Rossum48b069a2020-04-07 09:50:06 -0700201 PyObject *parameters = PyTuple_New(len);
202 if (parameters == NULL)
203 return NULL;
204 Py_ssize_t iparam = 0;
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300205 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
Guido van Rossum48b069a2020-04-07 09:50:06 -0700206 PyObject *t = PyTuple_GET_ITEM(args, iarg);
207 int typevar = is_typevar(t);
208 if (typevar < 0) {
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300209 Py_DECREF(parameters);
Guido van Rossum48b069a2020-04-07 09:50:06 -0700210 return NULL;
211 }
212 if (typevar) {
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300213 iparam += tuple_add(parameters, iparam, t);
214 }
215 else {
216 _Py_IDENTIFIER(__parameters__);
217 PyObject *subparams;
218 if (_PyObject_LookupAttrId(t, &PyId___parameters__, &subparams) < 0) {
219 Py_DECREF(parameters);
220 return NULL;
Guido van Rossum48b069a2020-04-07 09:50:06 -0700221 }
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300222 if (subparams && PyTuple_Check(subparams)) {
223 Py_ssize_t len2 = PyTuple_GET_SIZE(subparams);
224 Py_ssize_t needed = len2 - 1 - (iarg - iparam);
225 if (needed > 0) {
226 len += needed;
227 if (_PyTuple_Resize(&parameters, len) < 0) {
228 Py_DECREF(subparams);
229 Py_DECREF(parameters);
230 return NULL;
231 }
232 }
233 for (Py_ssize_t j = 0; j < len2; j++) {
234 PyObject *t2 = PyTuple_GET_ITEM(subparams, j);
235 iparam += tuple_add(parameters, iparam, t2);
236 }
237 }
238 Py_XDECREF(subparams);
Guido van Rossum48b069a2020-04-07 09:50:06 -0700239 }
240 }
241 if (iparam < len) {
242 if (_PyTuple_Resize(&parameters, iparam) < 0) {
243 Py_XDECREF(parameters);
244 return NULL;
245 }
246 }
247 return parameters;
248}
249
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300250/* If obj is a generic alias, substitute type variables params
251 with substitutions argitems. For example, if obj is list[T],
252 params is (T, S), and argitems is (str, int), return list[str].
253 If obj doesn't have a __parameters__ attribute or that's not
254 a non-empty tuple, return a new reference to obj. */
255static PyObject *
256subs_tvars(PyObject *obj, PyObject *params, PyObject **argitems)
257{
258 _Py_IDENTIFIER(__parameters__);
259 PyObject *subparams;
260 if (_PyObject_LookupAttrId(obj, &PyId___parameters__, &subparams) < 0) {
261 return NULL;
262 }
263 if (subparams && PyTuple_Check(subparams) && PyTuple_GET_SIZE(subparams)) {
264 Py_ssize_t nparams = PyTuple_GET_SIZE(params);
265 Py_ssize_t nsubargs = PyTuple_GET_SIZE(subparams);
266 PyObject *subargs = PyTuple_New(nsubargs);
267 if (subargs == NULL) {
268 Py_DECREF(subparams);
269 return NULL;
270 }
271 for (Py_ssize_t i = 0; i < nsubargs; ++i) {
272 PyObject *arg = PyTuple_GET_ITEM(subparams, i);
273 Py_ssize_t iparam = tuple_index(params, nparams, arg);
274 if (iparam >= 0) {
275 arg = argitems[iparam];
276 }
277 Py_INCREF(arg);
278 PyTuple_SET_ITEM(subargs, i, arg);
279 }
280
281 obj = PyObject_GetItem(obj, subargs);
282
283 Py_DECREF(subargs);
284 }
285 else {
286 Py_INCREF(obj);
287 }
288 Py_XDECREF(subparams);
289 return obj;
290}
291
Guido van Rossum48b069a2020-04-07 09:50:06 -0700292static PyObject *
293ga_getitem(PyObject *self, PyObject *item)
294{
295 gaobject *alias = (gaobject *)self;
296 // do a lookup for __parameters__ so it gets populated (if not already)
297 if (alias->parameters == NULL) {
298 alias->parameters = make_parameters(alias->args);
299 if (alias->parameters == NULL) {
300 return NULL;
301 }
302 }
303 Py_ssize_t nparams = PyTuple_GET_SIZE(alias->parameters);
304 if (nparams == 0) {
305 return PyErr_Format(PyExc_TypeError,
306 "There are no type variables left in %R",
307 self);
308 }
309 int is_tuple = PyTuple_Check(item);
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300310 Py_ssize_t nitems = is_tuple ? PyTuple_GET_SIZE(item) : 1;
311 PyObject **argitems = is_tuple ? &PyTuple_GET_ITEM(item, 0) : &item;
312 if (nitems != nparams) {
Guido van Rossum48b069a2020-04-07 09:50:06 -0700313 return PyErr_Format(PyExc_TypeError,
314 "Too %s arguments for %R",
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300315 nitems > nparams ? "many" : "few",
Guido van Rossum48b069a2020-04-07 09:50:06 -0700316 self);
317 }
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300318 /* Replace all type variables (specified by alias->parameters)
319 with corresponding values specified by argitems.
320 t = list[T]; t[int] -> newargs = [int]
321 t = dict[str, T]; t[int] -> newargs = [str, int]
322 t = dict[T, list[S]]; t[str, int] -> newargs = [str, list[int]]
323 */
Guido van Rossum48b069a2020-04-07 09:50:06 -0700324 Py_ssize_t nargs = PyTuple_GET_SIZE(alias->args);
325 PyObject *newargs = PyTuple_New(nargs);
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300326 if (newargs == NULL) {
Guido van Rossum48b069a2020-04-07 09:50:06 -0700327 return NULL;
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300328 }
Guido van Rossum48b069a2020-04-07 09:50:06 -0700329 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
330 PyObject *arg = PyTuple_GET_ITEM(alias->args, iarg);
331 int typevar = is_typevar(arg);
332 if (typevar < 0) {
333 Py_DECREF(newargs);
334 return NULL;
335 }
336 if (typevar) {
337 Py_ssize_t iparam = tuple_index(alias->parameters, nparams, arg);
338 assert(iparam >= 0);
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300339 arg = argitems[iparam];
340 Py_INCREF(arg);
341 }
342 else {
343 arg = subs_tvars(arg, alias->parameters, argitems);
344 if (arg == NULL) {
345 Py_DECREF(newargs);
346 return NULL;
Guido van Rossum48b069a2020-04-07 09:50:06 -0700347 }
348 }
Guido van Rossum48b069a2020-04-07 09:50:06 -0700349 PyTuple_SET_ITEM(newargs, iarg, arg);
350 }
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300351
Guido van Rossum48b069a2020-04-07 09:50:06 -0700352 PyObject *res = Py_GenericAlias(alias->origin, newargs);
Serhiy Storchaka41a64582020-05-04 10:56:05 +0300353
Guido van Rossum48b069a2020-04-07 09:50:06 -0700354 Py_DECREF(newargs);
355 return res;
356}
357
358static PyMappingMethods ga_as_mapping = {
359 .mp_subscript = ga_getitem,
360};
361
362static Py_hash_t
363ga_hash(PyObject *self)
364{
365 gaobject *alias = (gaobject *)self;
366 // TODO: Hash in the hash for the origin
367 Py_hash_t h0 = PyObject_Hash(alias->origin);
368 if (h0 == -1) {
369 return -1;
370 }
371 Py_hash_t h1 = PyObject_Hash(alias->args);
372 if (h1 == -1) {
373 return -1;
374 }
375 return h0 ^ h1;
376}
377
378static PyObject *
379ga_call(PyObject *self, PyObject *args, PyObject *kwds)
380{
381 gaobject *alias = (gaobject *)self;
382 PyObject *obj = PyObject_Call(alias->origin, args, kwds);
383 if (obj != NULL) {
384 if (PyObject_SetAttrString(obj, "__orig_class__", self) < 0) {
385 if (!PyErr_ExceptionMatches(PyExc_AttributeError) &&
386 !PyErr_ExceptionMatches(PyExc_TypeError))
387 {
388 Py_DECREF(obj);
389 return NULL;
390 }
391 PyErr_Clear();
392 }
393 }
394 return obj;
395}
396
397static const char* const attr_exceptions[] = {
398 "__origin__",
399 "__args__",
400 "__parameters__",
401 "__mro_entries__",
402 "__reduce_ex__", // needed so we don't look up object.__reduce_ex__
403 "__reduce__",
404 NULL,
405};
406
407static PyObject *
408ga_getattro(PyObject *self, PyObject *name)
409{
410 gaobject *alias = (gaobject *)self;
411 if (PyUnicode_Check(name)) {
412 for (const char * const *p = attr_exceptions; ; p++) {
413 if (*p == NULL) {
414 return PyObject_GetAttr(alias->origin, name);
415 }
416 if (_PyUnicode_EqualToASCIIString(name, *p)) {
417 break;
418 }
419 }
420 }
421 return PyObject_GenericGetAttr(self, name);
422}
423
424static PyObject *
425ga_richcompare(PyObject *a, PyObject *b, int op)
426{
Hai Shi5e8ffe12020-05-04 21:31:38 +0800427 if (!Py_IS_TYPE(a, &Py_GenericAliasType) ||
428 !Py_IS_TYPE(b, &Py_GenericAliasType) ||
Guido van Rossum48b069a2020-04-07 09:50:06 -0700429 (op != Py_EQ && op != Py_NE))
430 {
431 Py_RETURN_NOTIMPLEMENTED;
432 }
433
434 if (op == Py_NE) {
435 PyObject *eq = ga_richcompare(a, b, Py_EQ);
436 if (eq == NULL)
437 return NULL;
438 Py_DECREF(eq);
439 if (eq == Py_True) {
440 Py_RETURN_FALSE;
441 }
442 else {
443 Py_RETURN_TRUE;
444 }
445 }
446
447 gaobject *aa = (gaobject *)a;
448 gaobject *bb = (gaobject *)b;
449 int eq = PyObject_RichCompareBool(aa->origin, bb->origin, Py_EQ);
450 if (eq < 0) {
451 return NULL;
452 }
453 if (!eq) {
454 Py_RETURN_FALSE;
455 }
456 return PyObject_RichCompare(aa->args, bb->args, Py_EQ);
457}
458
459static PyObject *
460ga_mro_entries(PyObject *self, PyObject *args)
461{
462 gaobject *alias = (gaobject *)self;
463 return PyTuple_Pack(1, alias->origin);
464}
465
466static PyObject *
467ga_instancecheck(PyObject *self, PyObject *Py_UNUSED(ignored))
468{
469 PyErr_SetString(PyExc_TypeError,
470 "isinstance() argument 2 cannot be a parameterized generic");
471 return NULL;
472}
473
474static PyObject *
475ga_subclasscheck(PyObject *self, PyObject *Py_UNUSED(ignored))
476{
477 PyErr_SetString(PyExc_TypeError,
478 "issubclass() argument 2 cannot be a parameterized generic");
479 return NULL;
480}
481
482static PyObject *
483ga_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
484{
485 gaobject *alias = (gaobject *)self;
486 return Py_BuildValue("O(OO)", Py_TYPE(alias),
487 alias->origin, alias->args);
488}
489
Batuhan Taskaya2e877742020-09-16 00:58:32 +0300490static PyObject *
491ga_dir(PyObject *self, PyObject *Py_UNUSED(ignored))
492{
493 gaobject *alias = (gaobject *)self;
494 PyObject *dir = PyObject_Dir(alias->origin);
495 if (dir == NULL) {
496 return NULL;
497 }
498
499 PyObject *dir_entry = NULL;
500 for (const char * const *p = attr_exceptions; ; p++) {
501 if (*p == NULL) {
502 break;
503 }
504 else {
505 dir_entry = PyUnicode_FromString(*p);
506 if (dir_entry == NULL) {
507 goto error;
508 }
509 int contains = PySequence_Contains(dir, dir_entry);
510 if (contains < 0) {
511 goto error;
512 }
513 if (contains == 0 && PyList_Append(dir, dir_entry) < 0) {
514 goto error;
515 }
516
517 Py_CLEAR(dir_entry);
518 }
519 }
520 return dir;
521
522error:
523 Py_DECREF(dir);
524 Py_XDECREF(dir_entry);
525 return NULL;
526}
527
Guido van Rossum48b069a2020-04-07 09:50:06 -0700528static PyMethodDef ga_methods[] = {
529 {"__mro_entries__", ga_mro_entries, METH_O},
530 {"__instancecheck__", ga_instancecheck, METH_O},
531 {"__subclasscheck__", ga_subclasscheck, METH_O},
532 {"__reduce__", ga_reduce, METH_NOARGS},
Batuhan Taskaya2e877742020-09-16 00:58:32 +0300533 {"__dir__", ga_dir, METH_NOARGS},
Guido van Rossum48b069a2020-04-07 09:50:06 -0700534 {0}
535};
536
537static PyMemberDef ga_members[] = {
538 {"__origin__", T_OBJECT, offsetof(gaobject, origin), READONLY},
539 {"__args__", T_OBJECT, offsetof(gaobject, args), READONLY},
540 {0}
541};
542
543static PyObject *
544ga_parameters(PyObject *self, void *unused)
545{
546 gaobject *alias = (gaobject *)self;
547 if (alias->parameters == NULL) {
548 alias->parameters = make_parameters(alias->args);
549 if (alias->parameters == NULL) {
550 return NULL;
551 }
552 }
553 Py_INCREF(alias->parameters);
554 return alias->parameters;
555}
556
557static PyGetSetDef ga_properties[] = {
558 {"__parameters__", ga_parameters, (setter)NULL, "Type variables in the GenericAlias.", NULL},
559 {0}
560};
561
562static PyObject *
563ga_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
564{
Dong-hee Na02e44842020-04-24 01:25:53 +0900565 if (!_PyArg_NoKwnames("GenericAlias", kwds)) {
Guido van Rossum48b069a2020-04-07 09:50:06 -0700566 return NULL;
567 }
Dong-hee Na02e44842020-04-24 01:25:53 +0900568 if (!_PyArg_CheckPositional("GenericAlias", PyTuple_GET_SIZE(args), 2, 2)) {
Guido van Rossum48b069a2020-04-07 09:50:06 -0700569 return NULL;
570 }
571 PyObject *origin = PyTuple_GET_ITEM(args, 0);
572 PyObject *arguments = PyTuple_GET_ITEM(args, 1);
573 return Py_GenericAlias(origin, arguments);
574}
575
576// TODO:
577// - argument clinic?
578// - __doc__?
579// - cache?
580PyTypeObject Py_GenericAliasType = {
581 PyVarObject_HEAD_INIT(&PyType_Type, 0)
582 .tp_name = "types.GenericAlias",
583 .tp_doc = "Represent a PEP 585 generic type\n"
584 "\n"
Mikhail Golubev77f0a232020-10-09 00:38:36 +0300585 "E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).",
Guido van Rossum48b069a2020-04-07 09:50:06 -0700586 .tp_basicsize = sizeof(gaobject),
587 .tp_dealloc = ga_dealloc,
588 .tp_repr = ga_repr,
589 .tp_as_mapping = &ga_as_mapping,
590 .tp_hash = ga_hash,
591 .tp_call = ga_call,
592 .tp_getattro = ga_getattro,
593 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
594 .tp_traverse = ga_traverse,
595 .tp_richcompare = ga_richcompare,
596 .tp_methods = ga_methods,
597 .tp_members = ga_members,
598 .tp_alloc = PyType_GenericAlloc,
599 .tp_new = ga_new,
600 .tp_free = PyObject_GC_Del,
601 .tp_getset = ga_properties,
602};
603
604PyObject *
605Py_GenericAlias(PyObject *origin, PyObject *args)
606{
607 if (!PyTuple_Check(args)) {
608 args = PyTuple_Pack(1, args);
609 if (args == NULL) {
610 return NULL;
611 }
612 }
613 else {
614 Py_INCREF(args);
615 }
616
617 gaobject *alias = PyObject_GC_New(gaobject, &Py_GenericAliasType);
618 if (alias == NULL) {
619 Py_DECREF(args);
620 return NULL;
621 }
622
623 Py_INCREF(origin);
624 alias->origin = origin;
625 alias->args = args;
626 alias->parameters = NULL;
627 _PyObject_GC_TRACK(alias);
628 return (PyObject *)alias;
629}