Coverage Report

Created: 2026-05-30 06:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/genericaliasobject.c
Line
Count
Source
1
// types.GenericAlias -- used to represent e.g. list[int].
2
3
#include "Python.h"
4
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
5
#include "pycore_modsupport.h"    // _PyArg_NoKeywords()
6
#include "pycore_object.h"
7
#include "pycore_typevarobject.h" // _Py_typing_type_repr
8
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
9
#include "pycore_unionobject.h"   // _Py_union_type_or, _PyGenericAlias_Check
10
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
11
12
13
#include <stdbool.h>
14
15
typedef struct {
16
    PyObject_HEAD
17
    PyObject *origin;
18
    PyObject *args;
19
    PyObject *parameters;
20
    PyObject *weakreflist;
21
    // Whether we're a starred type, e.g. *tuple[int].
22
    bool starred;
23
    vectorcallfunc vectorcall;
24
} gaobject;
25
26
typedef struct {
27
    PyObject_HEAD
28
    PyObject *obj;  /* Set to NULL when iterator is exhausted */
29
} gaiterobject;
30
31
static void
32
ga_dealloc(PyObject *self)
33
128
{
34
128
    gaobject *alias = (gaobject *)self;
35
36
128
    _PyObject_GC_UNTRACK(self);
37
128
    FT_CLEAR_WEAKREFS(self, alias->weakreflist);
38
128
    Py_XDECREF(alias->origin);
39
128
    Py_XDECREF(alias->args);
40
128
    Py_XDECREF(alias->parameters);
41
128
    Py_TYPE(self)->tp_free(self);
42
128
}
43
44
static int
45
ga_traverse(PyObject *self, visitproc visit, void *arg)
46
43.6k
{
47
43.6k
    gaobject *alias = (gaobject *)self;
48
43.6k
    Py_VISIT(alias->origin);
49
43.6k
    Py_VISIT(alias->args);
50
43.6k
    Py_VISIT(alias->parameters);
51
43.6k
    return 0;
52
43.6k
}
53
54
static int
55
ga_repr_items_list(PyUnicodeWriter *writer, PyObject *p)
56
0
{
57
0
    assert(PyList_CheckExact(p));
58
59
0
    Py_ssize_t len = PyList_GET_SIZE(p);
60
61
0
    if (PyUnicodeWriter_WriteChar(writer, '[') < 0) {
62
0
        return -1;
63
0
    }
64
65
0
    for (Py_ssize_t i = 0; i < len; i++) {
66
0
        if (i > 0) {
67
0
            if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) {
68
0
                return -1;
69
0
            }
70
0
        }
71
0
        PyObject *item = PyList_GetItemRef(p, i);
72
0
        if (item == NULL) {
73
0
            return -1;  // list can be mutated in a callback
74
0
        }
75
0
        if (_Py_typing_type_repr(writer, item) < 0) {
76
0
            Py_DECREF(item);
77
0
            return -1;
78
0
        }
79
0
        Py_DECREF(item);
80
0
    }
81
82
0
    if (PyUnicodeWriter_WriteChar(writer, ']') < 0) {
83
0
        return -1;
84
0
    }
85
86
0
    return 0;
87
0
}
88
89
static PyObject *
90
ga_repr(PyObject *self)
91
4
{
92
4
    gaobject *alias = (gaobject *)self;
93
4
    Py_ssize_t len = PyTuple_GET_SIZE(alias->args);
94
95
    // Estimation based on the shortest format: "int[int, int, int]"
96
4
    Py_ssize_t estimate = (len <= PY_SSIZE_T_MAX / 5) ? len * 5 : len;
97
4
    estimate = 3 + 1 + estimate + 1;
98
4
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(estimate);
99
4
    if (writer == NULL) {
100
0
        return NULL;
101
0
    }
102
103
4
    if (alias->starred) {
104
0
        if (PyUnicodeWriter_WriteChar(writer, '*') < 0) {
105
0
            goto error;
106
0
        }
107
0
    }
108
4
    if (_Py_typing_type_repr(writer, alias->origin) < 0) {
109
0
        goto error;
110
0
    }
111
4
    if (PyUnicodeWriter_WriteChar(writer, '[') < 0) {
112
0
        goto error;
113
0
    }
114
12
    for (Py_ssize_t i = 0; i < len; i++) {
115
8
        if (i > 0) {
116
4
            if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) {
117
0
                goto error;
118
0
            }
119
4
        }
120
8
        PyObject *p = PyTuple_GET_ITEM(alias->args, i);
121
8
        if (PyList_CheckExact(p)) {
122
            // Looks like we are working with ParamSpec's list of type args:
123
0
            if (ga_repr_items_list(writer, p) < 0) {
124
0
                goto error;
125
0
            }
126
0
        }
127
8
        else if (_Py_typing_type_repr(writer, p) < 0) {
128
0
            goto error;
129
0
        }
130
8
    }
131
4
    if (len == 0) {
132
        // for something like tuple[()] we should print a "()"
133
0
        if (PyUnicodeWriter_WriteASCII(writer, "()", 2) < 0) {
134
0
            goto error;
135
0
        }
136
0
    }
137
4
    if (PyUnicodeWriter_WriteChar(writer, ']') < 0) {
138
0
        goto error;
139
0
    }
140
4
    return PyUnicodeWriter_Finish(writer);
141
142
0
error:
143
0
    PyUnicodeWriter_Discard(writer);
144
0
    return NULL;
145
4
}
146
147
// Index of item in self[:len], or -1 if not found (self is a tuple)
148
static Py_ssize_t
149
tuple_index(PyObject *self, Py_ssize_t len, PyObject *item)
150
32
{
151
36
    for (Py_ssize_t i = 0; i < len; i++) {
152
4
        if (PyTuple_GET_ITEM(self, i) == item) {
153
0
            return i;
154
0
        }
155
4
    }
156
32
    return -1;
157
32
}
158
159
static int
160
tuple_add(PyObject *self, Py_ssize_t len, PyObject *item)
161
32
{
162
32
    if (tuple_index(self, len, item) < 0) {
163
32
        PyTuple_SET_ITEM(self, len, Py_NewRef(item));
164
32
        return 1;
165
32
    }
166
0
    return 0;
167
32
}
168
169
static Py_ssize_t
170
tuple_extend(PyObject **dst, Py_ssize_t dstindex,
171
             PyObject **src, Py_ssize_t count)
172
0
{
173
0
    assert(count >= 0);
174
0
    if (_PyTuple_Resize(dst, PyTuple_GET_SIZE(*dst) + count - 1) != 0) {
175
0
        return -1;
176
0
    }
177
0
    assert(dstindex + count <= PyTuple_GET_SIZE(*dst));
178
0
    for (Py_ssize_t i = 0; i < count; ++i) {
179
0
        PyObject *item = src[i];
180
0
        PyTuple_SET_ITEM(*dst, dstindex + i, Py_NewRef(item));
181
0
    }
182
0
    return dstindex + count;
183
0
}
184
185
PyObject *
186
_Py_make_parameters(PyObject *args)
187
104
{
188
104
    assert(PyTuple_Check(args) || PyList_Check(args));
189
104
    const bool is_args_list = PyList_Check(args);
190
104
    PyObject *tuple_args = NULL;
191
104
    if (is_args_list) {
192
0
        args = tuple_args = PySequence_Tuple(args);
193
0
        if (args == NULL) {
194
0
            return NULL;
195
0
        }
196
0
    }
197
104
    Py_ssize_t nargs = PyTuple_GET_SIZE(args);
198
104
    Py_ssize_t len = nargs;
199
104
    PyObject *parameters = PyTuple_New(len);
200
104
    if (parameters == NULL) {
201
0
        Py_XDECREF(tuple_args);
202
0
        return NULL;
203
0
    }
204
104
    Py_ssize_t iparam = 0;
205
304
    for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
206
200
        PyObject *t = PyTuple_GET_ITEM(args, iarg);
207
        // We don't want __parameters__ descriptor of a bare Python class.
208
200
        if (PyType_Check(t)) {
209
100
            continue;
210
100
        }
211
100
        int rc = PyObject_HasAttrWithError(t, &_Py_ID(__typing_subst__));
212
100
        if (rc < 0) {
213
0
            Py_DECREF(parameters);
214
0
            Py_XDECREF(tuple_args);
215
0
            return NULL;
216
0
        }
217
100
        if (rc) {
218
32
            iparam += tuple_add(parameters, iparam, t);
219
32
        }
220
68
        else {
221
68
            PyObject *subparams;
222
68
            if (PyObject_GetOptionalAttr(t, &_Py_ID(__parameters__),
223
68
                                     &subparams) < 0) {
224
0
                Py_DECREF(parameters);
225
0
                Py_XDECREF(tuple_args);
226
0
                return NULL;
227
0
            }
228
68
            if (!subparams && (PyTuple_Check(t) || PyList_Check(t))) {
229
                // Recursively call _Py_make_parameters for lists/tuples and
230
                // add the results to the current parameters.
231
0
                subparams = _Py_make_parameters(t);
232
0
                if (subparams == NULL) {
233
0
                    Py_DECREF(parameters);
234
0
                    Py_XDECREF(tuple_args);
235
0
                    return NULL;
236
0
                }
237
0
            }
238
68
            if (subparams && PyTuple_Check(subparams)) {
239
40
                Py_ssize_t len2 = PyTuple_GET_SIZE(subparams);
240
40
                Py_ssize_t needed = len2 - 1 - (iarg - iparam);
241
40
                if (needed > 0) {
242
0
                    len += needed;
243
0
                    if (_PyTuple_Resize(&parameters, len) < 0) {
244
0
                        Py_DECREF(subparams);
245
0
                        Py_XDECREF(tuple_args);
246
0
                        return NULL;
247
0
                    }
248
0
                }
249
40
                for (Py_ssize_t j = 0; j < len2; j++) {
250
0
                    PyObject *t2 = PyTuple_GET_ITEM(subparams, j);
251
0
                    iparam += tuple_add(parameters, iparam, t2);
252
0
                }
253
40
            }
254
68
            Py_XDECREF(subparams);
255
68
        }
256
100
    }
257
104
    if (iparam < len) {
258
80
        if (_PyTuple_Resize(&parameters, iparam) < 0) {
259
0
            Py_XDECREF(parameters);
260
0
            Py_XDECREF(tuple_args);
261
0
            return NULL;
262
0
        }
263
80
    }
264
104
    Py_XDECREF(tuple_args);
265
104
    return parameters;
266
104
}
267
268
/* If obj is a generic alias, substitute type variables params
269
   with substitutions argitems.  For example, if obj is list[T],
270
   params is (T, S), and argitems is (str, int), return list[str].
271
   If obj doesn't have a __parameters__ attribute or that's not
272
   a non-empty tuple, return a new reference to obj. */
273
static PyObject *
274
subs_tvars(PyObject *obj, PyObject *params,
275
           PyObject **argitems, Py_ssize_t nargs)
276
0
{
277
0
    PyObject *subparams;
278
0
    if (PyObject_GetOptionalAttr(obj, &_Py_ID(__parameters__), &subparams) < 0) {
279
0
        return NULL;
280
0
    }
281
0
    if (subparams && PyTuple_Check(subparams) && PyTuple_GET_SIZE(subparams)) {
282
0
        Py_ssize_t nparams = PyTuple_GET_SIZE(params);
283
0
        Py_ssize_t nsubargs = PyTuple_GET_SIZE(subparams);
284
0
        PyObject *subargs = PyTuple_New(nsubargs);
285
0
        if (subargs == NULL) {
286
0
            Py_DECREF(subparams);
287
0
            return NULL;
288
0
        }
289
0
        Py_ssize_t j = 0;
290
0
        for (Py_ssize_t i = 0; i < nsubargs; ++i) {
291
0
            PyObject *arg = PyTuple_GET_ITEM(subparams, i);
292
0
            Py_ssize_t iparam = tuple_index(params, nparams, arg);
293
0
            if (iparam >= 0) {
294
0
                PyObject *param = PyTuple_GET_ITEM(params, iparam);
295
0
                arg = argitems[iparam];
296
0
                if (Py_TYPE(param)->tp_iter && PyTuple_Check(arg)) {  // TypeVarTuple
297
0
                    j = tuple_extend(&subargs, j,
298
0
                                    &PyTuple_GET_ITEM(arg, 0),
299
0
                                    PyTuple_GET_SIZE(arg));
300
0
                    if (j < 0) {
301
0
                        Py_DECREF(subparams);
302
0
                        Py_DECREF(subargs);
303
0
                        return NULL;
304
0
                    }
305
0
                    continue;
306
0
                }
307
0
            }
308
0
            PyTuple_SET_ITEM(subargs, j, Py_NewRef(arg));
309
0
            j++;
310
0
        }
311
0
        assert(j == PyTuple_GET_SIZE(subargs));
312
313
0
        obj = PyObject_GetItem(obj, subargs);
314
315
0
        Py_DECREF(subargs);
316
0
    }
317
0
    else {
318
0
        Py_INCREF(obj);
319
0
    }
320
0
    Py_XDECREF(subparams);
321
0
    return obj;
322
0
}
323
324
static int
325
_is_unpacked_typevartuple(PyObject *arg)
326
0
{
327
0
    PyObject *tmp;
328
0
    if (PyType_Check(arg)) { // TODO: Add test
329
0
        return 0;
330
0
    }
331
0
    int res = PyObject_GetOptionalAttr(arg, &_Py_ID(__typing_is_unpacked_typevartuple__), &tmp);
332
0
    if (res > 0) {
333
0
        res = PyObject_IsTrue(tmp);
334
0
        Py_DECREF(tmp);
335
0
    }
336
0
    return res;
337
0
}
338
339
static PyObject *
340
_unpacked_tuple_args(PyObject *arg)
341
0
{
342
0
    PyObject *result;
343
0
    assert(!PyType_Check(arg));
344
    // Fast path
345
0
    if (_PyGenericAlias_Check(arg) &&
346
0
            ((gaobject *)arg)->starred &&
347
0
            ((gaobject *)arg)->origin == (PyObject *)&PyTuple_Type)
348
0
    {
349
0
        result = ((gaobject *)arg)->args;
350
0
        return Py_NewRef(result);
351
0
    }
352
353
0
    if (PyObject_GetOptionalAttr(arg, &_Py_ID(__typing_unpacked_tuple_args__), &result) > 0) {
354
0
        if (result == Py_None) {
355
0
            Py_DECREF(result);
356
0
            return NULL;
357
0
        }
358
0
        return result;
359
0
    }
360
0
    return NULL;
361
0
}
362
363
static PyObject *
364
_unpack_args(PyObject *item)
365
0
{
366
0
    PyObject *newargs = PyList_New(0);
367
0
    if (newargs == NULL) {
368
0
        return NULL;
369
0
    }
370
0
    int is_tuple = PyTuple_Check(item);
371
0
    Py_ssize_t nitems = is_tuple ? PyTuple_GET_SIZE(item) : 1;
372
0
    PyObject **argitems = is_tuple ? &PyTuple_GET_ITEM(item, 0) : &item;
373
0
    for (Py_ssize_t i = 0; i < nitems; i++) {
374
0
        item = argitems[i];
375
0
        if (!PyType_Check(item)) {
376
0
            PyObject *subargs = _unpacked_tuple_args(item);
377
0
            if (subargs != NULL &&
378
0
                PyTuple_Check(subargs) &&
379
0
                !(PyTuple_GET_SIZE(subargs) &&
380
0
                  PyTuple_GET_ITEM(subargs, PyTuple_GET_SIZE(subargs)-1) == Py_Ellipsis))
381
0
            {
382
0
                if (PyList_SetSlice(newargs, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, subargs) < 0) {
383
0
                    Py_DECREF(subargs);
384
0
                    Py_DECREF(newargs);
385
0
                    return NULL;
386
0
                }
387
0
                Py_DECREF(subargs);
388
0
                continue;
389
0
            }
390
0
            Py_XDECREF(subargs);
391
0
            if (PyErr_Occurred()) {
392
0
                Py_DECREF(newargs);
393
0
                return NULL;
394
0
            }
395
0
        }
396
0
        if (PyList_Append(newargs, item) < 0) {
397
0
            Py_DECREF(newargs);
398
0
            return NULL;
399
0
        }
400
0
    }
401
0
    Py_SETREF(newargs, PySequence_Tuple(newargs));
402
0
    return newargs;
403
0
}
404
405
PyObject *
406
_Py_subs_parameters(PyObject *self, PyObject *args, PyObject *parameters, PyObject *item)
407
0
{
408
0
    Py_ssize_t nparams = PyTuple_GET_SIZE(parameters);
409
0
    if (nparams == 0) {
410
0
        return PyErr_Format(PyExc_TypeError,
411
0
                            "%R is not a generic class",
412
0
                            self);
413
0
    }
414
0
    item = _unpack_args(item);
415
0
    if (item == NULL) {
416
0
        return NULL;
417
0
    }
418
0
    for (Py_ssize_t i = 0; i < nparams; i++) {
419
0
        PyObject *param = PyTuple_GET_ITEM(parameters, i);
420
0
        PyObject *prepare, *tmp;
421
0
        if (PyObject_GetOptionalAttr(param, &_Py_ID(__typing_prepare_subst__), &prepare) < 0) {
422
0
            Py_DECREF(item);
423
0
            return NULL;
424
0
        }
425
0
        if (prepare && prepare != Py_None) {
426
0
            if (PyTuple_Check(item)) {
427
0
                tmp = PyObject_CallFunction(prepare, "OO", self, item);
428
0
            }
429
0
            else {
430
0
                tmp = PyObject_CallFunction(prepare, "O(O)", self, item);
431
0
            }
432
0
            Py_DECREF(prepare);
433
0
            Py_SETREF(item, tmp);
434
0
            if (item == NULL) {
435
0
                return NULL;
436
0
            }
437
0
        }
438
0
    }
439
0
    int is_tuple = PyTuple_Check(item);
440
0
    Py_ssize_t nitems = is_tuple ? PyTuple_GET_SIZE(item) : 1;
441
0
    PyObject **argitems = is_tuple ? &PyTuple_GET_ITEM(item, 0) : &item;
442
0
    if (nitems != nparams) {
443
0
        Py_DECREF(item);
444
0
        return PyErr_Format(PyExc_TypeError,
445
0
                            "Too %s arguments for %R; actual %zd, expected %zd",
446
0
                            nitems > nparams ? "many" : "few",
447
0
                            self, nitems, nparams);
448
0
    }
449
    /* Replace all type variables (specified by parameters)
450
       with corresponding values specified by argitems.
451
        t = list[T];          t[int]      -> newargs = [int]
452
        t = dict[str, T];     t[int]      -> newargs = [str, int]
453
        t = dict[T, list[S]]; t[str, int] -> newargs = [str, list[int]]
454
        t = list[[T]];        t[str]      -> newargs = [[str]]
455
     */
456
0
    assert (PyTuple_Check(args) || PyList_Check(args));
457
0
    const bool is_args_list = PyList_Check(args);
458
0
    PyObject *tuple_args = NULL;
459
0
    if (is_args_list) {
460
0
        args = tuple_args = PySequence_Tuple(args);
461
0
        if (args == NULL) {
462
0
            Py_DECREF(item);
463
0
            return NULL;
464
0
        }
465
0
    }
466
0
    Py_ssize_t nargs = PyTuple_GET_SIZE(args);
467
0
    PyObject *newargs = PyTuple_New(nargs);
468
0
    if (newargs == NULL) {
469
0
        Py_DECREF(item);
470
0
        Py_XDECREF(tuple_args);
471
0
        return NULL;
472
0
    }
473
0
    for (Py_ssize_t iarg = 0, jarg = 0; iarg < nargs; iarg++) {
474
0
        PyObject *arg = PyTuple_GET_ITEM(args, iarg);
475
0
        if (PyType_Check(arg)) {
476
0
            PyTuple_SET_ITEM(newargs, jarg, Py_NewRef(arg));
477
0
            jarg++;
478
0
            continue;
479
0
        }
480
        // Recursively substitute params in lists/tuples.
481
0
        if (PyTuple_Check(arg) || PyList_Check(arg)) {
482
0
            PyObject *subargs = _Py_subs_parameters(self, arg, parameters, item);
483
0
            if (subargs == NULL) {
484
0
                Py_DECREF(newargs);
485
0
                Py_DECREF(item);
486
0
                Py_XDECREF(tuple_args);
487
0
                return NULL;
488
0
            }
489
0
            if (PyTuple_Check(arg)) {
490
0
                PyTuple_SET_ITEM(newargs, jarg, subargs);
491
0
            }
492
0
            else {
493
                // _Py_subs_parameters returns a tuple. If the original arg was a list,
494
                // convert subargs to a list as well.
495
0
                PyObject *subargs_list = PySequence_List(subargs);
496
0
                Py_DECREF(subargs);
497
0
                if (subargs_list == NULL) {
498
0
                    Py_DECREF(newargs);
499
0
                    Py_DECREF(item);
500
0
                    Py_XDECREF(tuple_args);
501
0
                    return NULL;
502
0
                }
503
0
                PyTuple_SET_ITEM(newargs, jarg, subargs_list);
504
0
            }
505
0
            jarg++;
506
0
            continue;
507
0
        }
508
0
        int unpack = _is_unpacked_typevartuple(arg);
509
0
        if (unpack < 0) {
510
0
            Py_DECREF(newargs);
511
0
            Py_DECREF(item);
512
0
            Py_XDECREF(tuple_args);
513
0
            return NULL;
514
0
        }
515
0
        PyObject *subst;
516
0
        if (PyObject_GetOptionalAttr(arg, &_Py_ID(__typing_subst__), &subst) < 0) {
517
0
            Py_DECREF(newargs);
518
0
            Py_DECREF(item);
519
0
            Py_XDECREF(tuple_args);
520
0
            return NULL;
521
0
        }
522
0
        if (subst) {
523
0
            Py_ssize_t iparam = tuple_index(parameters, nparams, arg);
524
0
            assert(iparam >= 0);
525
0
            arg = PyObject_CallOneArg(subst, argitems[iparam]);
526
0
            Py_DECREF(subst);
527
0
        }
528
0
        else {
529
0
            arg = subs_tvars(arg, parameters, argitems, nitems);
530
0
        }
531
0
        if (arg == NULL) {
532
0
            Py_DECREF(newargs);
533
0
            Py_DECREF(item);
534
0
            Py_XDECREF(tuple_args);
535
0
            return NULL;
536
0
        }
537
0
        if (unpack) {
538
0
            if (!PyTuple_Check(arg)) {
539
0
                Py_DECREF(newargs);
540
0
                Py_DECREF(item);
541
0
                Py_XDECREF(tuple_args);
542
0
                PyObject *original = PyTuple_GET_ITEM(args, iarg);
543
0
                PyErr_Format(PyExc_TypeError,
544
0
                             "expected __typing_subst__ of %T objects to return a tuple, not %T",
545
0
                             original, arg);
546
0
                Py_DECREF(arg);
547
0
                return NULL;
548
0
            }
549
0
            jarg = tuple_extend(&newargs, jarg,
550
0
                    &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg));
551
0
            Py_DECREF(arg);
552
0
            if (jarg < 0) {
553
0
                Py_DECREF(item);
554
0
                Py_XDECREF(tuple_args);
555
0
                assert(newargs == NULL);
556
0
                return NULL;
557
0
            }
558
0
        }
559
0
        else {
560
0
            PyTuple_SET_ITEM(newargs, jarg, arg);
561
0
            jarg++;
562
0
        }
563
0
    }
564
565
0
    Py_DECREF(item);
566
0
    Py_XDECREF(tuple_args);
567
0
    return newargs;
568
0
}
569
570
PyDoc_STRVAR(genericalias__doc__,
571
"GenericAlias(origin, args, /)\n"
572
"--\n\n"
573
"Represent a PEP 585 generic type\n"
574
"\n"
575
"E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).");
576
577
static PyObject *
578
ga_getitem(PyObject *self, PyObject *item)
579
0
{
580
0
    gaobject *alias = (gaobject *)self;
581
    // Populate __parameters__ if needed.
582
0
    if (alias->parameters == NULL) {
583
0
        alias->parameters = _Py_make_parameters(alias->args);
584
0
        if (alias->parameters == NULL) {
585
0
            return NULL;
586
0
        }
587
0
    }
588
589
0
    PyObject *newargs = _Py_subs_parameters(self, alias->args, alias->parameters, item);
590
0
    if (newargs == NULL) {
591
0
        return NULL;
592
0
    }
593
594
0
    PyObject *res = Py_GenericAlias(alias->origin, newargs);
595
0
    if (res == NULL) {
596
0
        Py_DECREF(newargs);
597
0
        return NULL;
598
0
    }
599
0
    ((gaobject *)res)->starred = alias->starred;
600
601
0
    Py_DECREF(newargs);
602
0
    return res;
603
0
}
604
605
static PyMappingMethods ga_as_mapping = {
606
    .mp_subscript = ga_getitem,
607
};
608
609
static Py_hash_t
610
ga_hash(PyObject *self)
611
736
{
612
736
    gaobject *alias = (gaobject *)self;
613
    // TODO: Hash in the hash for the origin
614
736
    Py_hash_t h0 = PyObject_Hash(alias->origin);
615
736
    if (h0 == -1) {
616
0
        return -1;
617
0
    }
618
736
    Py_hash_t h1 = PyObject_Hash(alias->args);
619
736
    if (h1 == -1) {
620
0
        return -1;
621
0
    }
622
736
    return h0 ^ h1;
623
736
}
624
625
static inline PyObject *
626
set_orig_class(PyObject *obj, PyObject *self)
627
0
{
628
0
    if (obj != NULL) {
629
0
        if (PyObject_SetAttr(obj, &_Py_ID(__orig_class__), self) < 0) {
630
0
            if (!PyErr_ExceptionMatches(PyExc_AttributeError) &&
631
0
                !PyErr_ExceptionMatches(PyExc_TypeError))
632
0
            {
633
0
                Py_DECREF(obj);
634
0
                return NULL;
635
0
            }
636
0
            PyErr_Clear();
637
0
        }
638
0
    }
639
0
    return obj;
640
0
}
641
642
static PyObject *
643
ga_call(PyObject *self, PyObject *args, PyObject *kwds)
644
0
{
645
0
    gaobject *alias = (gaobject *)self;
646
0
    PyObject *obj = PyObject_Call(alias->origin, args, kwds);
647
0
    return set_orig_class(obj, self);
648
0
}
649
650
static PyObject *
651
ga_vectorcall(PyObject *self, PyObject *const *args,
652
              size_t nargsf, PyObject *kwnames)
653
0
{
654
0
    gaobject *alias = (gaobject *) self;
655
0
    PyObject *obj = PyObject_Vectorcall(alias->origin, args, nargsf, kwnames);
656
0
    return set_orig_class(obj, self);
657
0
}
658
659
static const char* const attr_exceptions[] = {
660
    "__class__",
661
    "__origin__",
662
    "__args__",
663
    "__unpacked__",
664
    "__parameters__",
665
    "__typing_unpacked_tuple_args__",
666
    "__mro_entries__",
667
    "__reduce_ex__",  // needed so we don't look up object.__reduce_ex__
668
    "__reduce__",
669
    NULL,
670
};
671
672
static const char* const attr_blocked[] = {
673
    "__bases__",
674
    "__copy__",
675
    "__deepcopy__",
676
    NULL,
677
};
678
679
static PyObject *
680
ga_getattro(PyObject *self, PyObject *name)
681
997
{
682
997
    gaobject *alias = (gaobject *)self;
683
997
    if (PyUnicode_Check(name)) {
684
        // When we check blocked attrs, we don't allow to proxy them to `__origin__`.
685
        // Otherwise, we can break existing code.
686
3.98k
        for (const char * const *p = attr_blocked; ; p++) {
687
3.98k
            if (*p == NULL) {
688
997
                break;
689
997
            }
690
2.99k
            if (_PyUnicode_EqualToASCIIString(name, *p)) {
691
0
                goto generic_getattr;
692
0
            }
693
2.99k
        }
694
695
        // When we see own attrs, it has a priority over `__origin__`'s attr.
696
2.74k
        for (const char * const *p = attr_exceptions; ; p++) {
697
2.74k
            if (*p == NULL) {
698
144
                return PyObject_GetAttr(alias->origin, name);
699
144
            }
700
2.59k
            if (_PyUnicode_EqualToASCIIString(name, *p)) {
701
853
                goto generic_getattr;
702
853
            }
703
2.59k
        }
704
997
    }
705
706
853
generic_getattr:
707
853
    return PyObject_GenericGetAttr(self, name);
708
997
}
709
710
static PyObject *
711
ga_richcompare(PyObject *a, PyObject *b, int op)
712
152
{
713
152
    if (!_PyGenericAlias_Check(b) ||
714
24
        (op != Py_EQ && op != Py_NE))
715
128
    {
716
128
        Py_RETURN_NOTIMPLEMENTED;
717
128
    }
718
719
24
    if (op == Py_NE) {
720
0
        PyObject *eq = ga_richcompare(a, b, Py_EQ);
721
0
        if (eq == NULL)
722
0
            return NULL;
723
0
        Py_DECREF(eq);
724
0
        if (eq == Py_True) {
725
0
            Py_RETURN_FALSE;
726
0
        }
727
0
        else {
728
0
            Py_RETURN_TRUE;
729
0
        }
730
0
    }
731
732
24
    gaobject *aa = (gaobject *)a;
733
24
    gaobject *bb = (gaobject *)b;
734
24
    if (aa->starred != bb->starred) {
735
0
        Py_RETURN_FALSE;
736
0
    }
737
24
    int eq = PyObject_RichCompareBool(aa->origin, bb->origin, Py_EQ);
738
24
    if (eq < 0) {
739
0
        return NULL;
740
0
    }
741
24
    if (!eq) {
742
0
        Py_RETURN_FALSE;
743
0
    }
744
24
    return PyObject_RichCompare(aa->args, bb->args, Py_EQ);
745
24
}
746
747
static PyObject *
748
ga_mro_entries(PyObject *self, PyObject *args)
749
5
{
750
5
    gaobject *alias = (gaobject *)self;
751
5
    return PyTuple_Pack(1, alias->origin);
752
5
}
753
754
static PyObject *
755
ga_instancecheck(PyObject *self, PyObject *Py_UNUSED(ignored))
756
0
{
757
0
    PyErr_SetString(PyExc_TypeError,
758
0
                    "isinstance() argument 2 cannot be a parameterized generic");
759
0
    return NULL;
760
0
}
761
762
static PyObject *
763
ga_subclasscheck(PyObject *self, PyObject *Py_UNUSED(ignored))
764
0
{
765
0
    PyErr_SetString(PyExc_TypeError,
766
0
                    "issubclass() argument 2 cannot be a parameterized generic");
767
0
    return NULL;
768
0
}
769
770
static PyObject *
771
ga_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
772
0
{
773
0
    gaobject *alias = (gaobject *)self;
774
0
    if (alias->starred) {
775
0
        PyObject *tmp = Py_GenericAlias(alias->origin, alias->args);
776
0
        if (tmp != NULL) {
777
0
            Py_SETREF(tmp, PyObject_GetIter(tmp));
778
0
        }
779
0
        if (tmp == NULL) {
780
0
            return NULL;
781
0
        }
782
0
        return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(next)), tmp);
783
0
    }
784
0
    return Py_BuildValue("O(OO)", Py_TYPE(alias),
785
0
                         alias->origin, alias->args);
786
0
}
787
788
static PyObject *
789
ga_dir(PyObject *self, PyObject *Py_UNUSED(ignored))
790
0
{
791
0
    gaobject *alias = (gaobject *)self;
792
0
    PyObject *dir = PyObject_Dir(alias->origin);
793
0
    if (dir == NULL) {
794
0
        return NULL;
795
0
    }
796
797
0
    PyObject *dir_entry = NULL;
798
0
    for (const char * const *p = attr_exceptions; ; p++) {
799
0
        if (*p == NULL) {
800
0
            break;
801
0
        }
802
0
        else {
803
0
            dir_entry = PyUnicode_FromString(*p);
804
0
            if (dir_entry == NULL) {
805
0
                goto error;
806
0
            }
807
0
            int contains = PySequence_Contains(dir, dir_entry);
808
0
            if (contains < 0) {
809
0
                goto error;
810
0
            }
811
0
            if (contains == 0 && PyList_Append(dir, dir_entry) < 0) {
812
0
                goto error;
813
0
            }
814
815
0
            Py_CLEAR(dir_entry);
816
0
        }
817
0
    }
818
0
    return dir;
819
820
0
error:
821
0
    Py_DECREF(dir);
822
0
    Py_XDECREF(dir_entry);
823
0
    return NULL;
824
0
}
825
826
static PyMethodDef ga_methods[] = {
827
    {"__mro_entries__", ga_mro_entries, METH_O},
828
    {"__instancecheck__", ga_instancecheck, METH_O},
829
    {"__subclasscheck__", ga_subclasscheck, METH_O},
830
    {"__reduce__", ga_reduce, METH_NOARGS},
831
    {"__dir__", ga_dir, METH_NOARGS},
832
    {0}
833
};
834
835
static PyMemberDef ga_members[] = {
836
    {"__origin__", _Py_T_OBJECT, offsetof(gaobject, origin), Py_READONLY},
837
    {"__args__", _Py_T_OBJECT, offsetof(gaobject, args), Py_READONLY},
838
    {"__unpacked__", Py_T_BOOL, offsetof(gaobject, starred), Py_READONLY},
839
    {0}
840
};
841
842
static PyObject *
843
ga_parameters(PyObject *self, void *unused)
844
84
{
845
84
    gaobject *alias = (gaobject *)self;
846
84
    if (alias->parameters == NULL) {
847
80
        alias->parameters = _Py_make_parameters(alias->args);
848
80
        if (alias->parameters == NULL) {
849
0
            return NULL;
850
0
        }
851
80
    }
852
84
    return Py_NewRef(alias->parameters);
853
84
}
854
855
static PyObject *
856
ga_unpacked_tuple_args(PyObject *self, void *unused)
857
0
{
858
0
    gaobject *alias = (gaobject *)self;
859
0
    if (alias->starred && alias->origin == (PyObject *)&PyTuple_Type) {
860
0
        return Py_NewRef(alias->args);
861
0
    }
862
0
    Py_RETURN_NONE;
863
0
}
864
865
static PyGetSetDef ga_properties[] = {
866
    {"__parameters__", ga_parameters, NULL, PyDoc_STR("Type variables in the GenericAlias."), NULL},
867
    {"__typing_unpacked_tuple_args__", ga_unpacked_tuple_args, NULL, NULL},
868
    {0}
869
};
870
871
/* A helper function to create GenericAlias' args tuple and set its attributes.
872
 * Returns 1 on success, 0 on failure.
873
 */
874
static inline int
875
1.88k
setup_ga(gaobject *alias, PyObject *origin, PyObject *args) {
876
1.88k
    if (!PyTuple_Check(args)) {
877
1.58k
        args = PyTuple_Pack(1, args);
878
1.58k
        if (args == NULL) {
879
0
            return 0;
880
0
        }
881
1.58k
    }
882
297
    else {
883
297
        Py_INCREF(args);
884
297
    }
885
886
1.88k
    alias->origin = Py_NewRef(origin);
887
1.88k
    alias->args = args;
888
1.88k
    alias->parameters = NULL;
889
1.88k
    alias->weakreflist = NULL;
890
891
1.88k
    if (PyVectorcall_Function(origin) != NULL) {
892
1.67k
        alias->vectorcall = ga_vectorcall;
893
1.67k
    }
894
205
    else {
895
205
        alias->vectorcall = NULL;
896
205
    }
897
898
1.88k
    return 1;
899
1.88k
}
900
901
static PyObject *
902
ga_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
903
193
{
904
193
    if (!_PyArg_NoKeywords("GenericAlias", kwds)) {
905
0
        return NULL;
906
0
    }
907
193
    if (!_PyArg_CheckPositional("GenericAlias", PyTuple_GET_SIZE(args), 2, 2)) {
908
0
        return NULL;
909
0
    }
910
193
    PyObject *origin = PyTuple_GET_ITEM(args, 0);
911
193
    PyObject *arguments = PyTuple_GET_ITEM(args, 1);
912
193
    gaobject *self = (gaobject *)type->tp_alloc(type, 0);
913
193
    if (self == NULL) {
914
0
        return NULL;
915
0
    }
916
193
    if (!setup_ga(self, origin, arguments)) {
917
0
        Py_DECREF(self);
918
0
        return NULL;
919
0
    }
920
193
    return (PyObject *)self;
921
193
}
922
923
static PyNumberMethods ga_as_number = {
924
        .nb_or = _Py_union_type_or, // Add __or__ function
925
};
926
927
static PyObject *
928
ga_iternext(PyObject *op)
929
0
{
930
0
    gaiterobject *gi = (gaiterobject*)op;
931
0
    if (gi->obj == NULL) {
932
0
        PyErr_SetNone(PyExc_StopIteration);
933
0
        return NULL;
934
0
    }
935
0
    gaobject *alias = (gaobject *)gi->obj;
936
0
    PyObject *starred_alias = Py_GenericAlias(alias->origin, alias->args);
937
0
    if (starred_alias == NULL) {
938
0
        return NULL;
939
0
    }
940
0
    ((gaobject *)starred_alias)->starred = true;
941
0
    Py_SETREF(gi->obj, NULL);
942
0
    return starred_alias;
943
0
}
944
945
static void
946
ga_iter_dealloc(PyObject *op)
947
0
{
948
0
    gaiterobject *gi = (gaiterobject*)op;
949
0
    PyObject_GC_UnTrack(gi);
950
0
    Py_XDECREF(gi->obj);
951
0
    PyObject_GC_Del(gi);
952
0
}
953
954
static int
955
ga_iter_traverse(PyObject *op, visitproc visit, void *arg)
956
0
{
957
0
    gaiterobject *gi = (gaiterobject*)op;
958
0
    Py_VISIT(gi->obj);
959
0
    return 0;
960
0
}
961
962
static int
963
ga_iter_clear(PyObject *self)
964
0
{
965
0
    gaiterobject *gi = (gaiterobject *)self;
966
0
    Py_CLEAR(gi->obj);
967
0
    return 0;
968
0
}
969
970
static PyObject *
971
ga_iter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
972
0
{
973
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
974
0
    gaiterobject *gi = (gaiterobject *)self;
975
976
    /* _PyEval_GetBuiltin can invoke arbitrary code,
977
     * call must be before access of iterator pointers.
978
     * see issue #101765 */
979
980
0
    if (gi->obj)
981
0
        return Py_BuildValue("N(O)", iter, gi->obj);
982
0
    else
983
0
        return Py_BuildValue("N(())", iter);
984
0
}
985
986
static PyMethodDef ga_iter_methods[] = {
987
    {"__reduce__", ga_iter_reduce, METH_NOARGS},
988
    {0}
989
};
990
991
// gh-91632: _Py_GenericAliasIterType is exported  to be cleared
992
// in _PyTypes_FiniTypes.
993
PyTypeObject _Py_GenericAliasIterType = {
994
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
995
    .tp_name = "generic_alias_iterator",
996
    .tp_basicsize = sizeof(gaiterobject),
997
    .tp_iter = PyObject_SelfIter,
998
    .tp_iternext = ga_iternext,
999
    .tp_traverse = ga_iter_traverse,
1000
    .tp_methods = ga_iter_methods,
1001
    .tp_dealloc = ga_iter_dealloc,
1002
    .tp_clear = ga_iter_clear,
1003
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1004
};
1005
1006
static PyObject *
1007
0
ga_iter(PyObject *self) {
1008
0
    gaiterobject *gi = PyObject_GC_New(gaiterobject, &_Py_GenericAliasIterType);
1009
0
    if (gi == NULL) {
1010
0
        return NULL;
1011
0
    }
1012
0
    gi->obj = Py_NewRef(self);
1013
0
    PyObject_GC_Track(gi);
1014
0
    return (PyObject *)gi;
1015
0
}
1016
1017
// TODO:
1018
// - argument clinic?
1019
// - cache?
1020
PyTypeObject Py_GenericAliasType = {
1021
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1022
    .tp_name = "types.GenericAlias",
1023
    .tp_doc = genericalias__doc__,
1024
    .tp_basicsize = sizeof(gaobject),
1025
    .tp_dealloc = ga_dealloc,
1026
    .tp_repr = ga_repr,
1027
    .tp_as_number = &ga_as_number,  // allow X | Y of GenericAlias objs
1028
    .tp_as_mapping = &ga_as_mapping,
1029
    .tp_hash = ga_hash,
1030
    .tp_call = ga_call,
1031
    .tp_getattro = ga_getattro,
1032
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL,
1033
    .tp_traverse = ga_traverse,
1034
    .tp_richcompare = ga_richcompare,
1035
    .tp_weaklistoffset = offsetof(gaobject, weakreflist),
1036
    .tp_methods = ga_methods,
1037
    .tp_members = ga_members,
1038
    .tp_alloc = PyType_GenericAlloc,
1039
    .tp_new = ga_new,
1040
    .tp_free = PyObject_GC_Del,
1041
    .tp_getset = ga_properties,
1042
    .tp_iter = ga_iter,
1043
    .tp_vectorcall_offset = offsetof(gaobject, vectorcall),
1044
};
1045
1046
PyObject *
1047
Py_GenericAlias(PyObject *origin, PyObject *args)
1048
1.69k
{
1049
1.69k
    gaobject *alias = (gaobject*) PyType_GenericAlloc(
1050
1.69k
            (PyTypeObject *)&Py_GenericAliasType, 0);
1051
1.69k
    if (alias == NULL) {
1052
0
        return NULL;
1053
0
    }
1054
1.69k
    if (!setup_ga(alias, origin, args)) {
1055
0
        Py_DECREF(alias);
1056
0
        return NULL;
1057
0
    }
1058
1.69k
    return (PyObject *)alias;
1059
1.69k
}