Coverage Report

Created: 2026-06-21 06:15

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
125
{
34
125
    gaobject *alias = (gaobject *)self;
35
36
125
    _PyObject_GC_UNTRACK(self);
37
125
    FT_CLEAR_WEAKREFS(self, alias->weakreflist);
38
125
    Py_XDECREF(alias->origin);
39
125
    Py_XDECREF(alias->args);
40
125
    Py_XDECREF(alias->parameters);
41
125
    Py_TYPE(self)->tp_free(self);
42
125
}
43
44
static int
45
ga_traverse(PyObject *self, visitproc visit, void *arg)
46
25.5k
{
47
25.5k
    gaobject *alias = (gaobject *)self;
48
25.5k
    Py_VISIT(alias->origin);
49
25.5k
    Py_VISIT(alias->args);
50
25.5k
    Py_VISIT(alias->parameters);
51
25.5k
    return 0;
52
25.5k
}
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
"For example, for t = list[int], t.__origin__ is list and t.__args__\n"
576
"is (int,).");
577
578
static PyObject *
579
ga_getitem(PyObject *self, PyObject *item)
580
0
{
581
0
    gaobject *alias = (gaobject *)self;
582
    // Populate __parameters__ if needed.
583
0
    if (alias->parameters == NULL) {
584
0
        alias->parameters = _Py_make_parameters(alias->args);
585
0
        if (alias->parameters == NULL) {
586
0
            return NULL;
587
0
        }
588
0
    }
589
590
0
    PyObject *newargs = _Py_subs_parameters(self, alias->args, alias->parameters, item);
591
0
    if (newargs == NULL) {
592
0
        return NULL;
593
0
    }
594
595
0
    PyObject *res = Py_GenericAlias(alias->origin, newargs);
596
0
    if (res == NULL) {
597
0
        Py_DECREF(newargs);
598
0
        return NULL;
599
0
    }
600
0
    ((gaobject *)res)->starred = alias->starred;
601
602
0
    Py_DECREF(newargs);
603
0
    return res;
604
0
}
605
606
static PyMappingMethods ga_as_mapping = {
607
    .mp_subscript = ga_getitem,
608
};
609
610
static Py_hash_t
611
ga_hash(PyObject *self)
612
736
{
613
736
    gaobject *alias = (gaobject *)self;
614
    // TODO: Hash in the hash for the origin
615
736
    Py_hash_t h0 = PyObject_Hash(alias->origin);
616
736
    if (h0 == -1) {
617
0
        return -1;
618
0
    }
619
736
    Py_hash_t h1 = PyObject_Hash(alias->args);
620
736
    if (h1 == -1) {
621
0
        return -1;
622
0
    }
623
736
    return h0 ^ h1;
624
736
}
625
626
static inline PyObject *
627
set_orig_class(PyObject *obj, PyObject *self)
628
0
{
629
0
    if (obj != NULL) {
630
0
        if (PyObject_SetAttr(obj, &_Py_ID(__orig_class__), self) < 0) {
631
0
            if (!PyErr_ExceptionMatches(PyExc_AttributeError) &&
632
0
                !PyErr_ExceptionMatches(PyExc_TypeError))
633
0
            {
634
0
                Py_DECREF(obj);
635
0
                return NULL;
636
0
            }
637
0
            PyErr_Clear();
638
0
        }
639
0
    }
640
0
    return obj;
641
0
}
642
643
static PyObject *
644
ga_call(PyObject *self, PyObject *args, PyObject *kwds)
645
0
{
646
0
    gaobject *alias = (gaobject *)self;
647
0
    PyObject *obj = PyObject_Call(alias->origin, args, kwds);
648
0
    return set_orig_class(obj, self);
649
0
}
650
651
static PyObject *
652
ga_vectorcall(PyObject *self, PyObject *const *args,
653
              size_t nargsf, PyObject *kwnames)
654
0
{
655
0
    gaobject *alias = (gaobject *) self;
656
0
    PyObject *obj = PyObject_Vectorcall(alias->origin, args, nargsf, kwnames);
657
0
    return set_orig_class(obj, self);
658
0
}
659
660
static const char* const attr_exceptions[] = {
661
    "__class__",
662
    "__origin__",
663
    "__args__",
664
    "__unpacked__",
665
    "__parameters__",
666
    "__typing_unpacked_tuple_args__",
667
    "__mro_entries__",
668
    "__reduce_ex__",  // needed so we don't look up object.__reduce_ex__
669
    "__reduce__",
670
    NULL,
671
};
672
673
static const char* const attr_blocked[] = {
674
    "__bases__",
675
    "__copy__",
676
    "__deepcopy__",
677
    NULL,
678
};
679
680
static PyObject *
681
ga_getattro(PyObject *self, PyObject *name)
682
957
{
683
957
    gaobject *alias = (gaobject *)self;
684
957
    if (PyUnicode_Check(name)) {
685
        // When we check blocked attrs, we don't allow to proxy them to `__origin__`.
686
        // Otherwise, we can break existing code.
687
3.82k
        for (const char * const *p = attr_blocked; ; p++) {
688
3.82k
            if (*p == NULL) {
689
957
                break;
690
957
            }
691
2.87k
            if (_PyUnicode_EqualToASCIIString(name, *p)) {
692
0
                goto generic_getattr;
693
0
            }
694
2.87k
        }
695
696
        // When we see own attrs, it has a priority over `__origin__`'s attr.
697
2.69k
        for (const char * const *p = attr_exceptions; ; p++) {
698
2.69k
            if (*p == NULL) {
699
144
                return PyObject_GetAttr(alias->origin, name);
700
144
            }
701
2.55k
            if (_PyUnicode_EqualToASCIIString(name, *p)) {
702
813
                goto generic_getattr;
703
813
            }
704
2.55k
        }
705
957
    }
706
707
813
generic_getattr:
708
813
    return PyObject_GenericGetAttr(self, name);
709
957
}
710
711
static PyObject *
712
ga_richcompare(PyObject *a, PyObject *b, int op)
713
152
{
714
152
    if (!_PyGenericAlias_Check(b) ||
715
24
        (op != Py_EQ && op != Py_NE))
716
128
    {
717
128
        Py_RETURN_NOTIMPLEMENTED;
718
128
    }
719
720
24
    if (op == Py_NE) {
721
0
        PyObject *eq = ga_richcompare(a, b, Py_EQ);
722
0
        if (eq == NULL)
723
0
            return NULL;
724
0
        Py_DECREF(eq);
725
0
        if (eq == Py_True) {
726
0
            Py_RETURN_FALSE;
727
0
        }
728
0
        else {
729
0
            Py_RETURN_TRUE;
730
0
        }
731
0
    }
732
733
24
    gaobject *aa = (gaobject *)a;
734
24
    gaobject *bb = (gaobject *)b;
735
24
    if (aa->starred != bb->starred) {
736
0
        Py_RETURN_FALSE;
737
0
    }
738
24
    int eq = PyObject_RichCompareBool(aa->origin, bb->origin, Py_EQ);
739
24
    if (eq < 0) {
740
0
        return NULL;
741
0
    }
742
24
    if (!eq) {
743
0
        Py_RETURN_FALSE;
744
0
    }
745
24
    return PyObject_RichCompare(aa->args, bb->args, Py_EQ);
746
24
}
747
748
static PyObject *
749
ga_mro_entries(PyObject *self, PyObject *args)
750
5
{
751
5
    gaobject *alias = (gaobject *)self;
752
5
    return PyTuple_Pack(1, alias->origin);
753
5
}
754
755
static PyObject *
756
ga_instancecheck(PyObject *self, PyObject *Py_UNUSED(ignored))
757
0
{
758
0
    PyErr_SetString(PyExc_TypeError,
759
0
                    "isinstance() argument 2 cannot be a parameterized generic");
760
0
    return NULL;
761
0
}
762
763
static PyObject *
764
ga_subclasscheck(PyObject *self, PyObject *Py_UNUSED(ignored))
765
0
{
766
0
    PyErr_SetString(PyExc_TypeError,
767
0
                    "issubclass() argument 2 cannot be a parameterized generic");
768
0
    return NULL;
769
0
}
770
771
static PyObject *
772
ga_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
773
0
{
774
0
    gaobject *alias = (gaobject *)self;
775
0
    if (alias->starred) {
776
0
        PyObject *tmp = Py_GenericAlias(alias->origin, alias->args);
777
0
        if (tmp != NULL) {
778
0
            Py_SETREF(tmp, PyObject_GetIter(tmp));
779
0
        }
780
0
        if (tmp == NULL) {
781
0
            return NULL;
782
0
        }
783
0
        return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(next)), tmp);
784
0
    }
785
0
    return Py_BuildValue("O(OO)", Py_TYPE(alias),
786
0
                         alias->origin, alias->args);
787
0
}
788
789
static PyObject *
790
ga_dir(PyObject *self, PyObject *Py_UNUSED(ignored))
791
0
{
792
0
    gaobject *alias = (gaobject *)self;
793
0
    PyObject *dir = PyObject_Dir(alias->origin);
794
0
    if (dir == NULL) {
795
0
        return NULL;
796
0
    }
797
798
0
    PyObject *dir_entry = NULL;
799
0
    for (const char * const *p = attr_exceptions; ; p++) {
800
0
        if (*p == NULL) {
801
0
            break;
802
0
        }
803
0
        else {
804
0
            dir_entry = PyUnicode_FromString(*p);
805
0
            if (dir_entry == NULL) {
806
0
                goto error;
807
0
            }
808
0
            int contains = PySequence_Contains(dir, dir_entry);
809
0
            if (contains < 0) {
810
0
                goto error;
811
0
            }
812
0
            if (contains == 0 && PyList_Append(dir, dir_entry) < 0) {
813
0
                goto error;
814
0
            }
815
816
0
            Py_CLEAR(dir_entry);
817
0
        }
818
0
    }
819
0
    return dir;
820
821
0
error:
822
0
    Py_DECREF(dir);
823
0
    Py_XDECREF(dir_entry);
824
0
    return NULL;
825
0
}
826
827
static PyMethodDef ga_methods[] = {
828
    {"__mro_entries__", ga_mro_entries, METH_O},
829
    {"__instancecheck__", ga_instancecheck, METH_O},
830
    {"__subclasscheck__", ga_subclasscheck, METH_O},
831
    {"__reduce__", ga_reduce, METH_NOARGS},
832
    {"__dir__", ga_dir, METH_NOARGS},
833
    {0}
834
};
835
836
static PyMemberDef ga_members[] = {
837
    {"__origin__", _Py_T_OBJECT, offsetof(gaobject, origin), Py_READONLY},
838
    {"__args__", _Py_T_OBJECT, offsetof(gaobject, args), Py_READONLY},
839
    {"__unpacked__", Py_T_BOOL, offsetof(gaobject, starred), Py_READONLY},
840
    {0}
841
};
842
843
static PyObject *
844
ga_parameters(PyObject *self, void *unused)
845
84
{
846
84
    gaobject *alias = (gaobject *)self;
847
84
    if (alias->parameters == NULL) {
848
80
        alias->parameters = _Py_make_parameters(alias->args);
849
80
        if (alias->parameters == NULL) {
850
0
            return NULL;
851
0
        }
852
80
    }
853
84
    return Py_NewRef(alias->parameters);
854
84
}
855
856
static PyObject *
857
ga_unpacked_tuple_args(PyObject *self, void *unused)
858
0
{
859
0
    gaobject *alias = (gaobject *)self;
860
0
    if (alias->starred && alias->origin == (PyObject *)&PyTuple_Type) {
861
0
        return Py_NewRef(alias->args);
862
0
    }
863
0
    Py_RETURN_NONE;
864
0
}
865
866
static PyGetSetDef ga_properties[] = {
867
    {"__parameters__", ga_parameters, NULL, PyDoc_STR("Type variables in the GenericAlias."), NULL},
868
    {"__typing_unpacked_tuple_args__", ga_unpacked_tuple_args, NULL, NULL},
869
    {0}
870
};
871
872
/* A helper function to create GenericAlias' args tuple and set its attributes.
873
 * Returns 1 on success, 0 on failure.
874
 */
875
static inline int
876
1.79k
setup_ga(gaobject *alias, PyObject *origin, PyObject *args) {
877
1.79k
    if (!PyTuple_Check(args)) {
878
1.50k
        args = PyTuple_Pack(1, args);
879
1.50k
        if (args == NULL) {
880
0
            return 0;
881
0
        }
882
1.50k
    }
883
289
    else {
884
289
        Py_INCREF(args);
885
289
    }
886
887
1.79k
    alias->origin = Py_NewRef(origin);
888
1.79k
    alias->args = args;
889
1.79k
    alias->parameters = NULL;
890
1.79k
    alias->weakreflist = NULL;
891
892
1.79k
    if (PyVectorcall_Function(origin) != NULL) {
893
1.59k
        alias->vectorcall = ga_vectorcall;
894
1.59k
    }
895
205
    else {
896
205
        alias->vectorcall = NULL;
897
205
    }
898
899
1.79k
    return 1;
900
1.79k
}
901
902
static PyObject *
903
ga_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
904
193
{
905
193
    if (!_PyArg_NoKeywords("GenericAlias", kwds)) {
906
0
        return NULL;
907
0
    }
908
193
    if (!_PyArg_CheckPositional("GenericAlias", PyTuple_GET_SIZE(args), 2, 2)) {
909
0
        return NULL;
910
0
    }
911
193
    PyObject *origin = PyTuple_GET_ITEM(args, 0);
912
193
    PyObject *arguments = PyTuple_GET_ITEM(args, 1);
913
193
    gaobject *self = (gaobject *)type->tp_alloc(type, 0);
914
193
    if (self == NULL) {
915
0
        return NULL;
916
0
    }
917
193
    if (!setup_ga(self, origin, arguments)) {
918
0
        Py_DECREF(self);
919
0
        return NULL;
920
0
    }
921
193
    return (PyObject *)self;
922
193
}
923
924
static PyNumberMethods ga_as_number = {
925
        .nb_or = _Py_union_type_or, // Add __or__ function
926
};
927
928
static PyObject *
929
ga_iternext(PyObject *op)
930
0
{
931
0
    gaiterobject *gi = (gaiterobject*)op;
932
0
    if (gi->obj == NULL) {
933
0
        PyErr_SetNone(PyExc_StopIteration);
934
0
        return NULL;
935
0
    }
936
0
    gaobject *alias = (gaobject *)gi->obj;
937
0
    PyObject *starred_alias = Py_GenericAlias(alias->origin, alias->args);
938
0
    if (starred_alias == NULL) {
939
0
        return NULL;
940
0
    }
941
0
    ((gaobject *)starred_alias)->starred = true;
942
0
    Py_SETREF(gi->obj, NULL);
943
0
    return starred_alias;
944
0
}
945
946
static void
947
ga_iter_dealloc(PyObject *op)
948
0
{
949
0
    gaiterobject *gi = (gaiterobject*)op;
950
0
    PyObject_GC_UnTrack(gi);
951
0
    Py_XDECREF(gi->obj);
952
0
    PyObject_GC_Del(gi);
953
0
}
954
955
static int
956
ga_iter_traverse(PyObject *op, visitproc visit, void *arg)
957
0
{
958
0
    gaiterobject *gi = (gaiterobject*)op;
959
0
    Py_VISIT(gi->obj);
960
0
    return 0;
961
0
}
962
963
static int
964
ga_iter_clear(PyObject *self)
965
0
{
966
0
    gaiterobject *gi = (gaiterobject *)self;
967
0
    Py_CLEAR(gi->obj);
968
0
    return 0;
969
0
}
970
971
static PyObject *
972
ga_iter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
973
0
{
974
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
975
0
    gaiterobject *gi = (gaiterobject *)self;
976
977
    /* _PyEval_GetBuiltin can invoke arbitrary code,
978
     * call must be before access of iterator pointers.
979
     * see issue #101765 */
980
981
0
    if (gi->obj)
982
0
        return Py_BuildValue("N(O)", iter, gi->obj);
983
0
    else
984
0
        return Py_BuildValue("N(())", iter);
985
0
}
986
987
static PyMethodDef ga_iter_methods[] = {
988
    {"__reduce__", ga_iter_reduce, METH_NOARGS},
989
    {0}
990
};
991
992
// gh-91632: _Py_GenericAliasIterType is exported  to be cleared
993
// in _PyTypes_FiniTypes.
994
PyTypeObject _Py_GenericAliasIterType = {
995
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
996
    .tp_name = "generic_alias_iterator",
997
    .tp_basicsize = sizeof(gaiterobject),
998
    .tp_iter = PyObject_SelfIter,
999
    .tp_iternext = ga_iternext,
1000
    .tp_traverse = ga_iter_traverse,
1001
    .tp_methods = ga_iter_methods,
1002
    .tp_dealloc = ga_iter_dealloc,
1003
    .tp_clear = ga_iter_clear,
1004
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1005
};
1006
1007
static PyObject *
1008
0
ga_iter(PyObject *self) {
1009
0
    gaiterobject *gi = PyObject_GC_New(gaiterobject, &_Py_GenericAliasIterType);
1010
0
    if (gi == NULL) {
1011
0
        return NULL;
1012
0
    }
1013
0
    gi->obj = Py_NewRef(self);
1014
0
    PyObject_GC_Track(gi);
1015
0
    return (PyObject *)gi;
1016
0
}
1017
1018
// TODO:
1019
// - argument clinic?
1020
// - cache?
1021
PyTypeObject Py_GenericAliasType = {
1022
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1023
    .tp_name = "types.GenericAlias",
1024
    .tp_doc = genericalias__doc__,
1025
    .tp_basicsize = sizeof(gaobject),
1026
    .tp_dealloc = ga_dealloc,
1027
    .tp_repr = ga_repr,
1028
    .tp_as_number = &ga_as_number,  // allow X | Y of GenericAlias objs
1029
    .tp_as_mapping = &ga_as_mapping,
1030
    .tp_hash = ga_hash,
1031
    .tp_call = ga_call,
1032
    .tp_getattro = ga_getattro,
1033
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL,
1034
    .tp_traverse = ga_traverse,
1035
    .tp_richcompare = ga_richcompare,
1036
    .tp_weaklistoffset = offsetof(gaobject, weakreflist),
1037
    .tp_methods = ga_methods,
1038
    .tp_members = ga_members,
1039
    .tp_alloc = PyType_GenericAlloc,
1040
    .tp_new = ga_new,
1041
    .tp_free = PyObject_GC_Del,
1042
    .tp_getset = ga_properties,
1043
    .tp_iter = ga_iter,
1044
    .tp_vectorcall_offset = offsetof(gaobject, vectorcall),
1045
};
1046
1047
PyObject *
1048
Py_GenericAlias(PyObject *origin, PyObject *args)
1049
1.60k
{
1050
1.60k
    gaobject *alias = (gaobject*) PyType_GenericAlloc(
1051
1.60k
            (PyTypeObject *)&Py_GenericAliasType, 0);
1052
1.60k
    if (alias == NULL) {
1053
0
        return NULL;
1054
0
    }
1055
1.60k
    if (!setup_ga(alias, origin, args)) {
1056
0
        Py_DECREF(alias);
1057
0
        return NULL;
1058
0
    }
1059
1.60k
    return (PyObject *)alias;
1060
1.60k
}