• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // TypeVar, TypeVarTuple, and ParamSpec
2 #include "Python.h"
3 #include "pycore_object.h"        // _PyObject_GC_TRACK/UNTRACK
4 #include "pycore_typevarobject.h"
5 #include "pycore_unionobject.h"   // _Py_union_type_or
6 
7 
8 /*[clinic input]
9 class typevar "typevarobject *" "&_PyTypeVar_Type"
10 class paramspec "paramspecobject *" "&_PyParamSpec_Type"
11 class paramspecargs "paramspecattrobject *" "&_PyParamSpecArgs_Type"
12 class paramspeckwargs "paramspecattrobject *" "&_PyParamSpecKwargs_Type"
13 class typevartuple "typevartupleobject *" "&_PyTypeVarTuple_Type"
14 class typealias "typealiasobject *" "&_PyTypeAlias_Type"
15 class Generic "PyObject *" "&PyGeneric_Type"
16 [clinic start generated code]*/
17 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=aa86741931a0f55c]*/
18 
19 typedef struct {
20     PyObject_HEAD
21     PyObject *name;
22     PyObject *bound;
23     PyObject *evaluate_bound;
24     PyObject *constraints;
25     PyObject *evaluate_constraints;
26     PyObject *default_value;
27     PyObject *evaluate_default;
28     bool covariant;
29     bool contravariant;
30     bool infer_variance;
31 } typevarobject;
32 
33 typedef struct {
34     PyObject_HEAD
35     PyObject *name;
36     PyObject *default_value;
37     PyObject *evaluate_default;
38 } typevartupleobject;
39 
40 typedef struct {
41     PyObject_HEAD
42     PyObject *name;
43     PyObject *bound;
44     PyObject *default_value;
45     PyObject *evaluate_default;
46     bool covariant;
47     bool contravariant;
48     bool infer_variance;
49 } paramspecobject;
50 
51 typedef struct {
52     PyObject_HEAD
53     PyObject *name;
54     PyObject *type_params;
55     PyObject *compute_value;
56     PyObject *value;
57     PyObject *module;
58 } typealiasobject;
59 
60 #include "clinic/typevarobject.c.h"
61 
62 /* NoDefault is a marker object to indicate that a parameter has no default. */
63 
64 static PyObject *
NoDefault_repr(PyObject * op)65 NoDefault_repr(PyObject *op)
66 {
67     return PyUnicode_FromString("typing.NoDefault");
68 }
69 
70 static PyObject *
NoDefault_reduce(PyObject * op,PyObject * Py_UNUSED (ignored))71 NoDefault_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
72 {
73     return PyUnicode_FromString("NoDefault");
74 }
75 
76 static PyMethodDef nodefault_methods[] = {
77     {"__reduce__", NoDefault_reduce, METH_NOARGS, NULL},
78     {NULL, NULL}
79 };
80 
81 static PyObject *
nodefault_new(PyTypeObject * type,PyObject * args,PyObject * kwargs)82 nodefault_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
83 {
84     if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
85         PyErr_SetString(PyExc_TypeError, "NoDefaultType takes no arguments");
86         return NULL;
87     }
88     return &_Py_NoDefaultStruct;
89 }
90 
91 static void
nodefault_dealloc(PyObject * nodefault)92 nodefault_dealloc(PyObject *nodefault)
93 {
94     /* This should never get called, but we also don't want to SEGV if
95      * we accidentally decref NoDefault out of existence. Instead,
96      * since NoDefault is an immortal object, re-set the reference count.
97      */
98     _Py_SetImmortal(nodefault);
99 }
100 
101 PyDoc_STRVAR(nodefault_doc,
102 "NoDefaultType()\n"
103 "--\n\n"
104 "The type of the NoDefault singleton.");
105 
106 PyTypeObject _PyNoDefault_Type = {
107     PyVarObject_HEAD_INIT(&PyType_Type, 0)
108     "NoDefaultType",
109     .tp_dealloc = nodefault_dealloc,
110     .tp_repr = NoDefault_repr,
111     .tp_flags = Py_TPFLAGS_DEFAULT,
112     .tp_doc = nodefault_doc,
113     .tp_methods = nodefault_methods,
114     .tp_new = nodefault_new,
115 };
116 
117 PyObject _Py_NoDefaultStruct = _PyObject_HEAD_INIT(&_PyNoDefault_Type);
118 
119 
120 static PyObject *
call_typing_func_object(const char * name,PyObject ** args,size_t nargs)121 call_typing_func_object(const char *name, PyObject **args, size_t nargs)
122 {
123     PyObject *typing = PyImport_ImportModule("typing");
124     if (typing == NULL) {
125         return NULL;
126     }
127     PyObject *func = PyObject_GetAttrString(typing, name);
128     if (func == NULL) {
129         Py_DECREF(typing);
130         return NULL;
131     }
132     PyObject *result = PyObject_Vectorcall(func, args, nargs, NULL);
133     Py_DECREF(func);
134     Py_DECREF(typing);
135     return result;
136 }
137 
138 static PyObject *
type_check(PyObject * arg,const char * msg)139 type_check(PyObject *arg, const char *msg)
140 {
141     // Calling typing.py here leads to bootstrapping problems
142     if (Py_IsNone(arg)) {
143         return Py_NewRef(Py_TYPE(arg));
144     }
145     PyObject *message_str = PyUnicode_FromString(msg);
146     if (message_str == NULL) {
147         return NULL;
148     }
149     PyObject *args[2] = {arg, message_str};
150     PyObject *result = call_typing_func_object("_type_check", args, 2);
151     Py_DECREF(message_str);
152     return result;
153 }
154 
155 /*
156  * Return a typing.Union. This is used as the nb_or (|) operator for
157  * TypeVar and ParamSpec. We use this rather than _Py_union_type_or
158  * (which would produce a types.Union) because historically TypeVar
159  * supported unions with string forward references, and we want to
160  * preserve that behavior. _Py_union_type_or only allows a small set
161  * of types.
162  */
163 static PyObject *
make_union(PyObject * self,PyObject * other)164 make_union(PyObject *self, PyObject *other)
165 {
166     PyObject *args[2] = {self, other};
167     PyObject *result = call_typing_func_object("_make_union", args, 2);
168     return result;
169 }
170 
171 static PyObject *
caller(void)172 caller(void)
173 {
174     _PyInterpreterFrame *f = _PyThreadState_GET()->current_frame;
175     if (f == NULL) {
176         Py_RETURN_NONE;
177     }
178     if (f == NULL || f->f_funcobj == NULL) {
179         Py_RETURN_NONE;
180     }
181     PyObject *r = PyFunction_GetModule(f->f_funcobj);
182     if (!r) {
183         PyErr_Clear();
184         Py_RETURN_NONE;
185     }
186     return Py_NewRef(r);
187 }
188 
189 static PyObject *
typevartuple_unpack(PyObject * tvt)190 typevartuple_unpack(PyObject *tvt)
191 {
192     PyObject *typing = PyImport_ImportModule("typing");
193     if (typing == NULL) {
194         return NULL;
195     }
196     PyObject *unpack = PyObject_GetAttrString(typing, "Unpack");
197     if (unpack == NULL) {
198         Py_DECREF(typing);
199         return NULL;
200     }
201     PyObject *unpacked = PyObject_GetItem(unpack, tvt);
202     Py_DECREF(typing);
203     Py_DECREF(unpack);
204     return unpacked;
205 }
206 
207 static int
contains_typevartuple(PyTupleObject * params)208 contains_typevartuple(PyTupleObject *params)
209 {
210     Py_ssize_t n = PyTuple_GET_SIZE(params);
211     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.typevartuple_type;
212     for (Py_ssize_t i = 0; i < n; i++) {
213         PyObject *param = PyTuple_GET_ITEM(params, i);
214         if (Py_IS_TYPE(param, tp)) {
215             return 1;
216         }
217     }
218     return 0;
219 }
220 
221 static PyObject *
unpack_typevartuples(PyObject * params)222 unpack_typevartuples(PyObject *params)
223 {
224     assert(PyTuple_Check(params));
225     // TypeVarTuple must be unpacked when passed to Generic, so we do that here.
226     if (contains_typevartuple((PyTupleObject *)params)) {
227         Py_ssize_t n = PyTuple_GET_SIZE(params);
228         PyObject *new_params = PyTuple_New(n);
229         if (new_params == NULL) {
230             return NULL;
231         }
232         PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.typevartuple_type;
233         for (Py_ssize_t i = 0; i < n; i++) {
234             PyObject *param = PyTuple_GET_ITEM(params, i);
235             if (Py_IS_TYPE(param, tp)) {
236                 PyObject *unpacked = typevartuple_unpack(param);
237                 if (unpacked == NULL) {
238                     Py_DECREF(new_params);
239                     return NULL;
240                 }
241                 PyTuple_SET_ITEM(new_params, i, unpacked);
242             }
243             else {
244                 PyTuple_SET_ITEM(new_params, i, Py_NewRef(param));
245             }
246         }
247         return new_params;
248     }
249     else {
250         return Py_NewRef(params);
251     }
252 }
253 
254 static void
typevar_dealloc(PyObject * self)255 typevar_dealloc(PyObject *self)
256 {
257     PyTypeObject *tp = Py_TYPE(self);
258     typevarobject *tv = (typevarobject *)self;
259 
260     _PyObject_GC_UNTRACK(self);
261 
262     Py_DECREF(tv->name);
263     Py_XDECREF(tv->bound);
264     Py_XDECREF(tv->evaluate_bound);
265     Py_XDECREF(tv->constraints);
266     Py_XDECREF(tv->evaluate_constraints);
267     Py_XDECREF(tv->default_value);
268     Py_XDECREF(tv->evaluate_default);
269     PyObject_ClearManagedDict(self);
270     PyObject_ClearWeakRefs(self);
271 
272     Py_TYPE(self)->tp_free(self);
273     Py_DECREF(tp);
274 }
275 
276 static int
typevar_traverse(PyObject * self,visitproc visit,void * arg)277 typevar_traverse(PyObject *self, visitproc visit, void *arg)
278 {
279     Py_VISIT(Py_TYPE(self));
280     typevarobject *tv = (typevarobject *)self;
281     Py_VISIT(tv->bound);
282     Py_VISIT(tv->evaluate_bound);
283     Py_VISIT(tv->constraints);
284     Py_VISIT(tv->evaluate_constraints);
285     Py_VISIT(tv->default_value);
286     Py_VISIT(tv->evaluate_default);
287     PyObject_VisitManagedDict(self, visit, arg);
288     return 0;
289 }
290 
291 static int
typevar_clear(typevarobject * self)292 typevar_clear(typevarobject *self)
293 {
294     Py_CLEAR(self->bound);
295     Py_CLEAR(self->evaluate_bound);
296     Py_CLEAR(self->constraints);
297     Py_CLEAR(self->evaluate_constraints);
298     Py_CLEAR(self->default_value);
299     Py_CLEAR(self->evaluate_default);
300     PyObject_ClearManagedDict((PyObject *)self);
301     return 0;
302 }
303 
304 static PyObject *
typevar_repr(PyObject * self)305 typevar_repr(PyObject *self)
306 {
307     typevarobject *tv = (typevarobject *)self;
308 
309     if (tv->infer_variance) {
310         return Py_NewRef(tv->name);
311     }
312 
313     char variance = tv->covariant ? '+' : tv->contravariant ? '-' : '~';
314     return PyUnicode_FromFormat("%c%U", variance, tv->name);
315 }
316 
317 static PyMemberDef typevar_members[] = {
318     {"__name__", _Py_T_OBJECT, offsetof(typevarobject, name), Py_READONLY},
319     {"__covariant__", Py_T_BOOL, offsetof(typevarobject, covariant), Py_READONLY},
320     {"__contravariant__", Py_T_BOOL, offsetof(typevarobject, contravariant), Py_READONLY},
321     {"__infer_variance__", Py_T_BOOL, offsetof(typevarobject, infer_variance), Py_READONLY},
322     {0}
323 };
324 
325 static PyObject *
typevar_bound(typevarobject * self,void * Py_UNUSED (ignored))326 typevar_bound(typevarobject *self, void *Py_UNUSED(ignored))
327 {
328     if (self->bound != NULL) {
329         return Py_NewRef(self->bound);
330     }
331     if (self->evaluate_bound == NULL) {
332         Py_RETURN_NONE;
333     }
334     PyObject *bound = PyObject_CallNoArgs(self->evaluate_bound);
335     self->bound = Py_XNewRef(bound);
336     return bound;
337 }
338 
339 static PyObject *
typevar_default(typevarobject * self,void * unused)340 typevar_default(typevarobject *self, void *unused)
341 {
342     if (self->default_value != NULL) {
343         return Py_NewRef(self->default_value);
344     }
345     if (self->evaluate_default == NULL) {
346         return &_Py_NoDefaultStruct;
347     }
348     PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default);
349     self->default_value = Py_XNewRef(default_value);
350     return default_value;
351 }
352 
353 static PyObject *
typevar_constraints(typevarobject * self,void * Py_UNUSED (ignored))354 typevar_constraints(typevarobject *self, void *Py_UNUSED(ignored))
355 {
356     if (self->constraints != NULL) {
357         return Py_NewRef(self->constraints);
358     }
359     if (self->evaluate_constraints == NULL) {
360         return PyTuple_New(0);
361     }
362     PyObject *constraints = PyObject_CallNoArgs(self->evaluate_constraints);
363     self->constraints = Py_XNewRef(constraints);
364     return constraints;
365 }
366 
367 static PyGetSetDef typevar_getset[] = {
368     {"__bound__", (getter)typevar_bound, NULL, NULL, NULL},
369     {"__constraints__", (getter)typevar_constraints, NULL, NULL, NULL},
370     {"__default__", (getter)typevar_default, NULL, NULL, NULL},
371     {0}
372 };
373 
374 static typevarobject *
typevar_alloc(PyObject * name,PyObject * bound,PyObject * evaluate_bound,PyObject * constraints,PyObject * evaluate_constraints,PyObject * default_value,bool covariant,bool contravariant,bool infer_variance,PyObject * module)375 typevar_alloc(PyObject *name, PyObject *bound, PyObject *evaluate_bound,
376               PyObject *constraints, PyObject *evaluate_constraints,
377               PyObject *default_value,
378               bool covariant, bool contravariant, bool infer_variance,
379               PyObject *module)
380 {
381     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.typevar_type;
382     assert(tp != NULL);
383     typevarobject *tv = PyObject_GC_New(typevarobject, tp);
384     if (tv == NULL) {
385         return NULL;
386     }
387 
388     tv->name = Py_NewRef(name);
389 
390     tv->bound = Py_XNewRef(bound);
391     tv->evaluate_bound = Py_XNewRef(evaluate_bound);
392     tv->constraints = Py_XNewRef(constraints);
393     tv->evaluate_constraints = Py_XNewRef(evaluate_constraints);
394     tv->default_value = Py_XNewRef(default_value);
395     tv->evaluate_default = NULL;
396 
397     tv->covariant = covariant;
398     tv->contravariant = contravariant;
399     tv->infer_variance = infer_variance;
400     _PyObject_GC_TRACK(tv);
401 
402     if (module != NULL) {
403         if (PyObject_SetAttrString((PyObject *)tv, "__module__", module) < 0) {
404             Py_DECREF(tv);
405             return NULL;
406         }
407     }
408 
409     return tv;
410 }
411 
412 /*[clinic input]
413 @classmethod
414 typevar.__new__ as typevar_new
415 
416     name: object(subclass_of="&PyUnicode_Type")
417     *constraints: object
418     bound: object = None
419     default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault
420     covariant: bool = False
421     contravariant: bool = False
422     infer_variance: bool = False
423 
424 Create a TypeVar.
425 [clinic start generated code]*/
426 
427 static PyObject *
typevar_new_impl(PyTypeObject * type,PyObject * name,PyObject * constraints,PyObject * bound,PyObject * default_value,int covariant,int contravariant,int infer_variance)428 typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints,
429                  PyObject *bound, PyObject *default_value, int covariant,
430                  int contravariant, int infer_variance)
431 /*[clinic end generated code: output=d2b248ff074eaab6 input=836f97f631d7293a]*/
432 {
433     if (covariant && contravariant) {
434         PyErr_SetString(PyExc_ValueError,
435                         "Bivariant types are not supported.");
436         return NULL;
437     }
438 
439     if (infer_variance && (covariant || contravariant)) {
440         PyErr_SetString(PyExc_ValueError,
441                         "Variance cannot be specified with infer_variance.");
442         return NULL;
443     }
444 
445     if (Py_IsNone(bound)) {
446         bound = NULL;
447     }
448     if (bound != NULL) {
449         bound = type_check(bound, "Bound must be a type.");
450         if (bound == NULL) {
451             return NULL;
452         }
453     }
454 
455     assert(PyTuple_CheckExact(constraints));
456     Py_ssize_t n_constraints = PyTuple_GET_SIZE(constraints);
457     if (n_constraints == 1) {
458         PyErr_SetString(PyExc_TypeError,
459                         "A single constraint is not allowed");
460         Py_XDECREF(bound);
461         return NULL;
462     } else if (n_constraints == 0) {
463         constraints = NULL;
464     } else if (bound != NULL) {
465         PyErr_SetString(PyExc_TypeError,
466                         "Constraints cannot be combined with bound=...");
467         Py_XDECREF(bound);
468         return NULL;
469     }
470     PyObject *module = caller();
471     if (module == NULL) {
472         Py_XDECREF(bound);
473         return NULL;
474     }
475 
476     PyObject *tv = (PyObject *)typevar_alloc(name, bound, NULL,
477                                              constraints, NULL,
478                                              default_value,
479                                              covariant, contravariant,
480                                              infer_variance, module);
481     Py_XDECREF(bound);
482     Py_XDECREF(module);
483     return tv;
484 }
485 
486 /*[clinic input]
487 typevar.__typing_subst__ as typevar_typing_subst
488 
489     arg: object
490     /
491 
492 [clinic start generated code]*/
493 
494 static PyObject *
typevar_typing_subst(typevarobject * self,PyObject * arg)495 typevar_typing_subst(typevarobject *self, PyObject *arg)
496 /*[clinic end generated code: output=0773735e8ce18968 input=9e87b57f0fc59b92]*/
497 {
498     PyObject *args[2] = {(PyObject *)self, arg};
499     PyObject *result = call_typing_func_object("_typevar_subst", args, 2);
500     return result;
501 }
502 
503 /*[clinic input]
504 typevar.__typing_prepare_subst__ as typevar_typing_prepare_subst
505 
506     alias: object
507     args: object
508     /
509 
510 [clinic start generated code]*/
511 
512 static PyObject *
typevar_typing_prepare_subst_impl(typevarobject * self,PyObject * alias,PyObject * args)513 typevar_typing_prepare_subst_impl(typevarobject *self, PyObject *alias,
514                                   PyObject *args)
515 /*[clinic end generated code: output=82c3f4691e0ded22 input=201a750415d14ffb]*/
516 {
517     PyObject *params = PyObject_GetAttrString(alias, "__parameters__");
518     if (params == NULL) {
519         return NULL;
520     }
521     Py_ssize_t i = PySequence_Index(params, (PyObject *)self);
522     if (i == -1) {
523         Py_DECREF(params);
524         return NULL;
525     }
526     Py_ssize_t args_len = PySequence_Length(args);
527     if (args_len == -1) {
528         Py_DECREF(params);
529         return NULL;
530     }
531     if (i < args_len) {
532         // We already have a value for our TypeVar
533         Py_DECREF(params);
534         return Py_NewRef(args);
535     }
536     else if (i == args_len) {
537         // If the TypeVar has a default, use it.
538         PyObject *dflt = typevar_default(self, NULL);
539         if (dflt == NULL) {
540             Py_DECREF(params);
541             return NULL;
542         }
543         if (dflt != &_Py_NoDefaultStruct) {
544             PyObject *new_args = PyTuple_Pack(1, dflt);
545             Py_DECREF(dflt);
546             if (new_args == NULL) {
547                 Py_DECREF(params);
548                 return NULL;
549             }
550             PyObject *result = PySequence_Concat(args, new_args);
551             Py_DECREF(params);
552             Py_DECREF(new_args);
553             return result;
554         }
555     }
556     Py_DECREF(params);
557     PyErr_Format(PyExc_TypeError,
558                  "Too few arguments for %S; actual %d, expected at least %d",
559                  alias, args_len, i + 1);
560     return NULL;
561 }
562 
563 /*[clinic input]
564 typevar.__reduce__ as typevar_reduce
565 
566 [clinic start generated code]*/
567 
568 static PyObject *
typevar_reduce_impl(typevarobject * self)569 typevar_reduce_impl(typevarobject *self)
570 /*[clinic end generated code: output=02e5c55d7cf8a08f input=de76bc95f04fb9ff]*/
571 {
572     return Py_NewRef(self->name);
573 }
574 
575 
576 /*[clinic input]
577 typevar.has_default as typevar_has_default
578 
579 [clinic start generated code]*/
580 
581 static PyObject *
typevar_has_default_impl(typevarobject * self)582 typevar_has_default_impl(typevarobject *self)
583 /*[clinic end generated code: output=76bf0b8dc98b97dd input=31024aa030761cf6]*/
584 {
585     if (self->evaluate_default != NULL ||
586         (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) {
587         Py_RETURN_TRUE;
588     }
589     Py_RETURN_FALSE;
590 }
591 
592 static PyObject *
typevar_mro_entries(PyObject * self,PyObject * args)593 typevar_mro_entries(PyObject *self, PyObject *args)
594 {
595     PyErr_SetString(PyExc_TypeError,
596                     "Cannot subclass an instance of TypeVar");
597     return NULL;
598 }
599 
600 static PyMethodDef typevar_methods[] = {
601     TYPEVAR_TYPING_SUBST_METHODDEF
602     TYPEVAR_TYPING_PREPARE_SUBST_METHODDEF
603     TYPEVAR_REDUCE_METHODDEF
604     TYPEVAR_HAS_DEFAULT_METHODDEF
605     {"__mro_entries__", typevar_mro_entries, METH_O},
606     {0}
607 };
608 
609 PyDoc_STRVAR(typevar_doc,
610 "Type variable.\n\
611 \n\
612 The preferred way to construct a type variable is via the dedicated\n\
613 syntax for generic functions, classes, and type aliases::\n\
614 \n\
615     class Sequence[T]:  # T is a TypeVar\n\
616         ...\n\
617 \n\
618 This syntax can also be used to create bound and constrained type\n\
619 variables::\n\
620 \n\
621     # S is a TypeVar bound to str\n\
622     class StrSequence[S: str]:\n\
623         ...\n\
624 \n\
625     # A is a TypeVar constrained to str or bytes\n\
626     class StrOrBytesSequence[A: (str, bytes)]:\n\
627         ...\n\
628 \n\
629 Type variables can also have defaults:\n\
630 \n\
631     class IntDefault[T = int]:\n\
632         ...\n\
633 \n\
634 However, if desired, reusable type variables can also be constructed\n\
635 manually, like so::\n\
636 \n\
637    T = TypeVar('T')  # Can be anything\n\
638    S = TypeVar('S', bound=str)  # Can be any subtype of str\n\
639    A = TypeVar('A', str, bytes)  # Must be exactly str or bytes\n\
640    D = TypeVar('D', default=int)  # Defaults to int\n\
641 \n\
642 Type variables exist primarily for the benefit of static type\n\
643 checkers.  They serve as the parameters for generic types as well\n\
644 as for generic function and type alias definitions.\n\
645 \n\
646 The variance of type variables is inferred by type checkers when they\n\
647 are created through the type parameter syntax and when\n\
648 ``infer_variance=True`` is passed. Manually created type variables may\n\
649 be explicitly marked covariant or contravariant by passing\n\
650 ``covariant=True`` or ``contravariant=True``. By default, manually\n\
651 created type variables are invariant. See PEP 484 and PEP 695 for more\n\
652 details.\n\
653 ");
654 
655 static PyType_Slot typevar_slots[] = {
656     {Py_tp_doc, (void *)typevar_doc},
657     {Py_tp_methods, typevar_methods},
658     {Py_nb_or, make_union},
659     {Py_tp_new, typevar_new},
660     {Py_tp_dealloc, typevar_dealloc},
661     {Py_tp_alloc, PyType_GenericAlloc},
662     {Py_tp_free, PyObject_GC_Del},
663     {Py_tp_traverse, typevar_traverse},
664     {Py_tp_clear, typevar_clear},
665     {Py_tp_repr, typevar_repr},
666     {Py_tp_members, typevar_members},
667     {Py_tp_getset, typevar_getset},
668     {0, NULL},
669 };
670 
671 PyType_Spec typevar_spec = {
672     .name = "typing.TypeVar",
673     .basicsize = sizeof(typevarobject),
674     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
675         | Py_TPFLAGS_MANAGED_DICT | Py_TPFLAGS_MANAGED_WEAKREF,
676     .slots = typevar_slots,
677 };
678 
679 typedef struct {
680     PyObject_HEAD
681     PyObject *__origin__;
682 } paramspecattrobject;
683 
684 static void
paramspecattr_dealloc(PyObject * self)685 paramspecattr_dealloc(PyObject *self)
686 {
687     PyTypeObject *tp = Py_TYPE(self);
688     paramspecattrobject *psa = (paramspecattrobject *)self;
689 
690     _PyObject_GC_UNTRACK(self);
691 
692     Py_XDECREF(psa->__origin__);
693 
694     Py_TYPE(self)->tp_free(self);
695     Py_DECREF(tp);
696 }
697 
698 static int
paramspecattr_traverse(PyObject * self,visitproc visit,void * arg)699 paramspecattr_traverse(PyObject *self, visitproc visit, void *arg)
700 {
701     paramspecattrobject *psa = (paramspecattrobject *)self;
702     Py_VISIT(psa->__origin__);
703     return 0;
704 }
705 
706 static int
paramspecattr_clear(paramspecattrobject * self)707 paramspecattr_clear(paramspecattrobject *self)
708 {
709     Py_CLEAR(self->__origin__);
710     return 0;
711 }
712 
713 static PyObject *
paramspecattr_richcompare(PyObject * a,PyObject * b,int op)714 paramspecattr_richcompare(PyObject *a, PyObject *b, int op)
715 {
716     if (!Py_IS_TYPE(a, Py_TYPE(b))) {
717         Py_RETURN_NOTIMPLEMENTED;
718     }
719     if (op != Py_EQ && op != Py_NE) {
720         Py_RETURN_NOTIMPLEMENTED;
721     }
722     return PyObject_RichCompare(
723         ((paramspecattrobject *)a)->__origin__,
724         ((paramspecattrobject *)b)->__origin__,
725         op
726     );
727 }
728 
729 static PyMemberDef paramspecattr_members[] = {
730     {"__origin__", _Py_T_OBJECT, offsetof(paramspecattrobject, __origin__), Py_READONLY},
731     {0}
732 };
733 
734 static paramspecattrobject *
paramspecattr_new(PyTypeObject * tp,PyObject * origin)735 paramspecattr_new(PyTypeObject *tp, PyObject *origin)
736 {
737     paramspecattrobject *psa = PyObject_GC_New(paramspecattrobject, tp);
738     if (psa == NULL) {
739         return NULL;
740     }
741     psa->__origin__ = Py_NewRef(origin);
742     _PyObject_GC_TRACK(psa);
743     return psa;
744 }
745 
746 static PyObject *
paramspecargs_repr(PyObject * self)747 paramspecargs_repr(PyObject *self)
748 {
749     paramspecattrobject *psa = (paramspecattrobject *)self;
750 
751     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspec_type;
752     if (Py_IS_TYPE(psa->__origin__, tp)) {
753         return PyUnicode_FromFormat("%U.args",
754             ((paramspecobject *)psa->__origin__)->name);
755     }
756     return PyUnicode_FromFormat("%R.args", psa->__origin__);
757 }
758 
759 
760 /*[clinic input]
761 @classmethod
762 paramspecargs.__new__ as paramspecargs_new
763 
764     origin: object
765 
766 Create a ParamSpecArgs object.
767 [clinic start generated code]*/
768 
769 static PyObject *
paramspecargs_new_impl(PyTypeObject * type,PyObject * origin)770 paramspecargs_new_impl(PyTypeObject *type, PyObject *origin)
771 /*[clinic end generated code: output=9a1463dc8942fe4e input=3596a0bb6183c208]*/
772 {
773     return (PyObject *)paramspecattr_new(type, origin);
774 }
775 
776 static PyObject *
paramspecargs_mro_entries(PyObject * self,PyObject * args)777 paramspecargs_mro_entries(PyObject *self, PyObject *args)
778 {
779     PyErr_SetString(PyExc_TypeError,
780                     "Cannot subclass an instance of ParamSpecArgs");
781     return NULL;
782 }
783 
784 static PyMethodDef paramspecargs_methods[] = {
785     {"__mro_entries__", paramspecargs_mro_entries, METH_O},
786     {0}
787 };
788 
789 PyDoc_STRVAR(paramspecargs_doc,
790 "The args for a ParamSpec object.\n\
791 \n\
792 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.\n\
793 \n\
794 ParamSpecArgs objects have a reference back to their ParamSpec::\n\
795 \n\
796     >>> P = ParamSpec(\"P\")\n\
797     >>> P.args.__origin__ is P\n\
798     True\n\
799 \n\
800 This type is meant for runtime introspection and has no special meaning\n\
801 to static type checkers.\n\
802 ");
803 
804 static PyType_Slot paramspecargs_slots[] = {
805     {Py_tp_doc, (void *)paramspecargs_doc},
806     {Py_tp_methods, paramspecargs_methods},
807     {Py_tp_new, paramspecargs_new},
808     {Py_tp_dealloc, paramspecattr_dealloc},
809     {Py_tp_alloc, PyType_GenericAlloc},
810     {Py_tp_free, PyObject_GC_Del},
811     {Py_tp_traverse, paramspecattr_traverse},
812     {Py_tp_clear, (inquiry)paramspecattr_clear},
813     {Py_tp_repr, paramspecargs_repr},
814     {Py_tp_members, paramspecattr_members},
815     {Py_tp_richcompare, paramspecattr_richcompare},
816     {0, NULL},
817 };
818 
819 PyType_Spec paramspecargs_spec = {
820     .name = "typing.ParamSpecArgs",
821     .basicsize = sizeof(paramspecattrobject),
822     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
823         | Py_TPFLAGS_MANAGED_WEAKREF,
824     .slots = paramspecargs_slots,
825 };
826 
827 static PyObject *
paramspeckwargs_repr(PyObject * self)828 paramspeckwargs_repr(PyObject *self)
829 {
830     paramspecattrobject *psk = (paramspecattrobject *)self;
831 
832     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspec_type;
833     if (Py_IS_TYPE(psk->__origin__, tp)) {
834         return PyUnicode_FromFormat("%U.kwargs",
835             ((paramspecobject *)psk->__origin__)->name);
836     }
837     return PyUnicode_FromFormat("%R.kwargs", psk->__origin__);
838 }
839 
840 /*[clinic input]
841 @classmethod
842 paramspeckwargs.__new__ as paramspeckwargs_new
843 
844     origin: object
845 
846 Create a ParamSpecKwargs object.
847 [clinic start generated code]*/
848 
849 static PyObject *
paramspeckwargs_new_impl(PyTypeObject * type,PyObject * origin)850 paramspeckwargs_new_impl(PyTypeObject *type, PyObject *origin)
851 /*[clinic end generated code: output=277b11967ebaf4ab input=981bca9b0cf9e40a]*/
852 {
853     return (PyObject *)paramspecattr_new(type, origin);
854 }
855 
856 static PyObject *
paramspeckwargs_mro_entries(PyObject * self,PyObject * args)857 paramspeckwargs_mro_entries(PyObject *self, PyObject *args)
858 {
859     PyErr_SetString(PyExc_TypeError,
860                     "Cannot subclass an instance of ParamSpecKwargs");
861     return NULL;
862 }
863 
864 static PyMethodDef paramspeckwargs_methods[] = {
865     {"__mro_entries__", paramspeckwargs_mro_entries, METH_O},
866     {0}
867 };
868 
869 PyDoc_STRVAR(paramspeckwargs_doc,
870 "The kwargs for a ParamSpec object.\n\
871 \n\
872 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.\n\
873 \n\
874 ParamSpecKwargs objects have a reference back to their ParamSpec::\n\
875 \n\
876     >>> P = ParamSpec(\"P\")\n\
877     >>> P.kwargs.__origin__ is P\n\
878     True\n\
879 \n\
880 This type is meant for runtime introspection and has no special meaning\n\
881 to static type checkers.\n\
882 ");
883 
884 static PyType_Slot paramspeckwargs_slots[] = {
885     {Py_tp_doc, (void *)paramspeckwargs_doc},
886     {Py_tp_methods, paramspeckwargs_methods},
887     {Py_tp_new, paramspeckwargs_new},
888     {Py_tp_dealloc, paramspecattr_dealloc},
889     {Py_tp_alloc, PyType_GenericAlloc},
890     {Py_tp_free, PyObject_GC_Del},
891     {Py_tp_traverse, paramspecattr_traverse},
892     {Py_tp_clear, (inquiry)paramspecattr_clear},
893     {Py_tp_repr, paramspeckwargs_repr},
894     {Py_tp_members, paramspecattr_members},
895     {Py_tp_richcompare, paramspecattr_richcompare},
896     {0, NULL},
897 };
898 
899 PyType_Spec paramspeckwargs_spec = {
900     .name = "typing.ParamSpecKwargs",
901     .basicsize = sizeof(paramspecattrobject),
902     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
903         | Py_TPFLAGS_MANAGED_WEAKREF,
904     .slots = paramspeckwargs_slots,
905 };
906 
907 static void
paramspec_dealloc(PyObject * self)908 paramspec_dealloc(PyObject *self)
909 {
910     PyTypeObject *tp = Py_TYPE(self);
911     paramspecobject *ps = (paramspecobject *)self;
912 
913     _PyObject_GC_UNTRACK(self);
914 
915     Py_DECREF(ps->name);
916     Py_XDECREF(ps->bound);
917     Py_XDECREF(ps->default_value);
918     Py_XDECREF(ps->evaluate_default);
919     PyObject_ClearManagedDict(self);
920     PyObject_ClearWeakRefs(self);
921 
922     Py_TYPE(self)->tp_free(self);
923     Py_DECREF(tp);
924 }
925 
926 static int
paramspec_traverse(PyObject * self,visitproc visit,void * arg)927 paramspec_traverse(PyObject *self, visitproc visit, void *arg)
928 {
929     Py_VISIT(Py_TYPE(self));
930     paramspecobject *ps = (paramspecobject *)self;
931     Py_VISIT(ps->bound);
932     Py_VISIT(ps->default_value);
933     Py_VISIT(ps->evaluate_default);
934     PyObject_VisitManagedDict(self, visit, arg);
935     return 0;
936 }
937 
938 static int
paramspec_clear(paramspecobject * self)939 paramspec_clear(paramspecobject *self)
940 {
941     Py_CLEAR(self->bound);
942     Py_CLEAR(self->default_value);
943     Py_CLEAR(self->evaluate_default);
944     PyObject_ClearManagedDict((PyObject *)self);
945     return 0;
946 }
947 
948 static PyObject *
paramspec_repr(PyObject * self)949 paramspec_repr(PyObject *self)
950 {
951     paramspecobject *ps = (paramspecobject *)self;
952 
953     if (ps->infer_variance) {
954         return Py_NewRef(ps->name);
955     }
956 
957     char variance = ps->covariant ? '+' : ps->contravariant ? '-' : '~';
958     return PyUnicode_FromFormat("%c%U", variance, ps->name);
959 }
960 
961 static PyMemberDef paramspec_members[] = {
962     {"__name__", _Py_T_OBJECT, offsetof(paramspecobject, name), Py_READONLY},
963     {"__bound__", _Py_T_OBJECT, offsetof(paramspecobject, bound), Py_READONLY},
964     {"__covariant__", Py_T_BOOL, offsetof(paramspecobject, covariant), Py_READONLY},
965     {"__contravariant__", Py_T_BOOL, offsetof(paramspecobject, contravariant), Py_READONLY},
966     {"__infer_variance__", Py_T_BOOL, offsetof(paramspecobject, infer_variance), Py_READONLY},
967     {0}
968 };
969 
970 static PyObject *
paramspec_args(PyObject * self,void * unused)971 paramspec_args(PyObject *self, void *unused)
972 {
973     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspecargs_type;
974     return (PyObject *)paramspecattr_new(tp, self);
975 }
976 
977 static PyObject *
paramspec_kwargs(PyObject * self,void * unused)978 paramspec_kwargs(PyObject *self, void *unused)
979 {
980     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspeckwargs_type;
981     return (PyObject *)paramspecattr_new(tp, self);
982 }
983 
984 static PyObject *
paramspec_default(paramspecobject * self,void * unused)985 paramspec_default(paramspecobject *self, void *unused)
986 {
987     if (self->default_value != NULL) {
988         return Py_NewRef(self->default_value);
989     }
990     if (self->evaluate_default == NULL) {
991         return &_Py_NoDefaultStruct;
992     }
993     PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default);
994     self->default_value = Py_XNewRef(default_value);
995     return default_value;
996 }
997 
998 static PyGetSetDef paramspec_getset[] = {
999     {"args", (getter)paramspec_args, NULL, PyDoc_STR("Represents positional arguments."), NULL},
1000     {"kwargs", (getter)paramspec_kwargs, NULL, PyDoc_STR("Represents keyword arguments."), NULL},
1001     {"__default__", (getter)paramspec_default, NULL, "The default value for this ParamSpec.", NULL},
1002     {0},
1003 };
1004 
1005 static paramspecobject *
paramspec_alloc(PyObject * name,PyObject * bound,PyObject * default_value,bool covariant,bool contravariant,bool infer_variance,PyObject * module)1006 paramspec_alloc(PyObject *name, PyObject *bound, PyObject *default_value, bool covariant,
1007                 bool contravariant, bool infer_variance, PyObject *module)
1008 {
1009     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspec_type;
1010     paramspecobject *ps = PyObject_GC_New(paramspecobject, tp);
1011     if (ps == NULL) {
1012         return NULL;
1013     }
1014     ps->name = Py_NewRef(name);
1015     ps->bound = Py_XNewRef(bound);
1016     ps->covariant = covariant;
1017     ps->contravariant = contravariant;
1018     ps->infer_variance = infer_variance;
1019     ps->default_value = Py_XNewRef(default_value);
1020     ps->evaluate_default = NULL;
1021     _PyObject_GC_TRACK(ps);
1022     if (module != NULL) {
1023         if (PyObject_SetAttrString((PyObject *)ps, "__module__", module) < 0) {
1024             Py_DECREF(ps);
1025             return NULL;
1026         }
1027     }
1028     return ps;
1029 }
1030 
1031 /*[clinic input]
1032 @classmethod
1033 paramspec.__new__ as paramspec_new
1034 
1035     name: object(subclass_of="&PyUnicode_Type")
1036     *
1037     bound: object = None
1038     default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault
1039     covariant: bool = False
1040     contravariant: bool = False
1041     infer_variance: bool = False
1042 
1043 Create a ParamSpec object.
1044 [clinic start generated code]*/
1045 
1046 static PyObject *
paramspec_new_impl(PyTypeObject * type,PyObject * name,PyObject * bound,PyObject * default_value,int covariant,int contravariant,int infer_variance)1047 paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound,
1048                    PyObject *default_value, int covariant, int contravariant,
1049                    int infer_variance)
1050 /*[clinic end generated code: output=47ca9d63fa5a094d input=495e1565bc067ab9]*/
1051 {
1052     if (covariant && contravariant) {
1053         PyErr_SetString(PyExc_ValueError, "Bivariant types are not supported.");
1054         return NULL;
1055     }
1056     if (infer_variance && (covariant || contravariant)) {
1057         PyErr_SetString(PyExc_ValueError, "Variance cannot be specified with infer_variance.");
1058         return NULL;
1059     }
1060     if (bound != NULL) {
1061         bound = type_check(bound, "Bound must be a type.");
1062         if (bound == NULL) {
1063             return NULL;
1064         }
1065     }
1066     PyObject *module = caller();
1067     if (module == NULL) {
1068         Py_XDECREF(bound);
1069         return NULL;
1070     }
1071     PyObject *ps = (PyObject *)paramspec_alloc(
1072         name, bound, default_value, covariant, contravariant, infer_variance, module);
1073     Py_XDECREF(bound);
1074     Py_DECREF(module);
1075     return ps;
1076 }
1077 
1078 
1079 /*[clinic input]
1080 paramspec.__typing_subst__ as paramspec_typing_subst
1081 
1082     arg: object
1083     /
1084 
1085 [clinic start generated code]*/
1086 
1087 static PyObject *
paramspec_typing_subst(paramspecobject * self,PyObject * arg)1088 paramspec_typing_subst(paramspecobject *self, PyObject *arg)
1089 /*[clinic end generated code: output=4c5b4aaada1c5814 input=2d5b5e3d4a717189]*/
1090 {
1091     PyObject *args[2] = {(PyObject *)self, arg};
1092     PyObject *result = call_typing_func_object("_paramspec_subst", args, 2);
1093     return result;
1094 }
1095 
1096 /*[clinic input]
1097 paramspec.__typing_prepare_subst__ as paramspec_typing_prepare_subst
1098 
1099     alias: object
1100     args: object
1101     /
1102 
1103 [clinic start generated code]*/
1104 
1105 static PyObject *
paramspec_typing_prepare_subst_impl(paramspecobject * self,PyObject * alias,PyObject * args)1106 paramspec_typing_prepare_subst_impl(paramspecobject *self, PyObject *alias,
1107                                     PyObject *args)
1108 /*[clinic end generated code: output=95449d630a2adb9a input=6df6f9fef3e150da]*/
1109 {
1110     PyObject *args_array[3] = {(PyObject *)self, alias, args};
1111     PyObject *result = call_typing_func_object(
1112         "_paramspec_prepare_subst", args_array, 3);
1113     return result;
1114 }
1115 
1116 /*[clinic input]
1117 paramspec.__reduce__ as paramspec_reduce
1118 
1119 [clinic start generated code]*/
1120 
1121 static PyObject *
paramspec_reduce_impl(paramspecobject * self)1122 paramspec_reduce_impl(paramspecobject *self)
1123 /*[clinic end generated code: output=b83398674416db27 input=5bf349f0d5dd426c]*/
1124 {
1125     return Py_NewRef(self->name);
1126 }
1127 
1128 /*[clinic input]
1129 paramspec.has_default as paramspec_has_default
1130 
1131 [clinic start generated code]*/
1132 
1133 static PyObject *
paramspec_has_default_impl(paramspecobject * self)1134 paramspec_has_default_impl(paramspecobject *self)
1135 /*[clinic end generated code: output=daaae7467a6a4368 input=2112e97eeb76cd59]*/
1136 {
1137     if (self->evaluate_default != NULL ||
1138         (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) {
1139         Py_RETURN_TRUE;
1140     }
1141     Py_RETURN_FALSE;
1142 }
1143 
1144 static PyObject *
paramspec_mro_entries(PyObject * self,PyObject * args)1145 paramspec_mro_entries(PyObject *self, PyObject *args)
1146 {
1147     PyErr_SetString(PyExc_TypeError,
1148                     "Cannot subclass an instance of ParamSpec");
1149     return NULL;
1150 }
1151 
1152 static PyMethodDef paramspec_methods[] = {
1153     PARAMSPEC_TYPING_SUBST_METHODDEF
1154     PARAMSPEC_TYPING_PREPARE_SUBST_METHODDEF
1155     PARAMSPEC_HAS_DEFAULT_METHODDEF
1156     PARAMSPEC_REDUCE_METHODDEF
1157     {"__mro_entries__", paramspec_mro_entries, METH_O},
1158     {0}
1159 };
1160 
1161 PyDoc_STRVAR(paramspec_doc,
1162 "Parameter specification variable.\n\
1163 \n\
1164 The preferred way to construct a parameter specification is via the\n\
1165 dedicated syntax for generic functions, classes, and type aliases,\n\
1166 where the use of '**' creates a parameter specification::\n\
1167 \n\
1168     type IntFunc[**P] = Callable[P, int]\n\
1169 \n\
1170 The following syntax creates a parameter specification that defaults\n\
1171 to a callable accepting two positional-only arguments of types int\n\
1172 and str:\n\
1173 \n\
1174     type IntFuncDefault[**P = (int, str)] = Callable[P, int]\n\
1175 \n\
1176 For compatibility with Python 3.11 and earlier, ParamSpec objects\n\
1177 can also be created as follows::\n\
1178 \n\
1179     P = ParamSpec('P')\n\
1180     DefaultP = ParamSpec('DefaultP', default=(int, str))\n\
1181 \n\
1182 Parameter specification variables exist primarily for the benefit of\n\
1183 static type checkers.  They are used to forward the parameter types of\n\
1184 one callable to another callable, a pattern commonly found in\n\
1185 higher-order functions and decorators.  They are only valid when used\n\
1186 in ``Concatenate``, or as the first argument to ``Callable``, or as\n\
1187 parameters for user-defined Generics. See class Generic for more\n\
1188 information on generic types.\n\
1189 \n\
1190 An example for annotating a decorator::\n\
1191 \n\
1192     def add_logging[**P, T](f: Callable[P, T]) -> Callable[P, T]:\n\
1193         '''A type-safe decorator to add logging to a function.'''\n\
1194         def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n\
1195             logging.info(f'{f.__name__} was called')\n\
1196             return f(*args, **kwargs)\n\
1197         return inner\n\
1198 \n\
1199     @add_logging\n\
1200     def add_two(x: float, y: float) -> float:\n\
1201         '''Add two numbers together.'''\n\
1202         return x + y\n\
1203 \n\
1204 Parameter specification variables can be introspected. e.g.::\n\
1205 \n\
1206     >>> P = ParamSpec(\"P\")\n\
1207     >>> P.__name__\n\
1208     'P'\n\
1209 \n\
1210 Note that only parameter specification variables defined in the global\n\
1211 scope can be pickled.\n\
1212 ");
1213 
1214 static PyType_Slot paramspec_slots[] = {
1215     {Py_tp_doc, (void *)paramspec_doc},
1216     {Py_tp_members, paramspec_members},
1217     {Py_tp_methods, paramspec_methods},
1218     {Py_tp_getset, paramspec_getset},
1219     // Unions of ParamSpecs have no defined meaning, but they were allowed
1220     // by the Python implementation, so we allow them here too.
1221     {Py_nb_or, make_union},
1222     {Py_tp_new, paramspec_new},
1223     {Py_tp_dealloc, paramspec_dealloc},
1224     {Py_tp_alloc, PyType_GenericAlloc},
1225     {Py_tp_free, PyObject_GC_Del},
1226     {Py_tp_traverse, paramspec_traverse},
1227     {Py_tp_clear, paramspec_clear},
1228     {Py_tp_repr, paramspec_repr},
1229     {0, 0},
1230 };
1231 
1232 PyType_Spec paramspec_spec = {
1233     .name = "typing.ParamSpec",
1234     .basicsize = sizeof(paramspecobject),
1235     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
1236         | Py_TPFLAGS_MANAGED_DICT | Py_TPFLAGS_MANAGED_WEAKREF,
1237     .slots = paramspec_slots,
1238 };
1239 
1240 static void
typevartuple_dealloc(PyObject * self)1241 typevartuple_dealloc(PyObject *self)
1242 {
1243     PyTypeObject *tp = Py_TYPE(self);
1244     _PyObject_GC_UNTRACK(self);
1245     typevartupleobject *tvt = (typevartupleobject *)self;
1246 
1247     Py_DECREF(tvt->name);
1248     Py_XDECREF(tvt->default_value);
1249     Py_XDECREF(tvt->evaluate_default);
1250     PyObject_ClearManagedDict(self);
1251     PyObject_ClearWeakRefs(self);
1252 
1253     Py_TYPE(self)->tp_free(self);
1254     Py_DECREF(tp);
1255 }
1256 
1257 static PyObject *
typevartuple_iter(PyObject * self)1258 typevartuple_iter(PyObject *self)
1259 {
1260     PyObject *unpacked = typevartuple_unpack(self);
1261     if (unpacked == NULL) {
1262         return NULL;
1263     }
1264     PyObject *tuple = PyTuple_Pack(1, unpacked);
1265     if (tuple == NULL) {
1266         Py_DECREF(unpacked);
1267         return NULL;
1268     }
1269     PyObject *result = PyObject_GetIter(tuple);
1270     Py_DECREF(unpacked);
1271     Py_DECREF(tuple);
1272     return result;
1273 }
1274 
1275 static PyObject *
typevartuple_repr(PyObject * self)1276 typevartuple_repr(PyObject *self)
1277 {
1278     typevartupleobject *tvt = (typevartupleobject *)self;
1279 
1280     return Py_NewRef(tvt->name);
1281 }
1282 
1283 static PyMemberDef typevartuple_members[] = {
1284     {"__name__", _Py_T_OBJECT, offsetof(typevartupleobject, name), Py_READONLY},
1285     {0}
1286 };
1287 
1288 static typevartupleobject *
typevartuple_alloc(PyObject * name,PyObject * module,PyObject * default_value)1289 typevartuple_alloc(PyObject *name, PyObject *module, PyObject *default_value)
1290 {
1291     PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.typevartuple_type;
1292     typevartupleobject *tvt = PyObject_GC_New(typevartupleobject, tp);
1293     if (tvt == NULL) {
1294         return NULL;
1295     }
1296     tvt->name = Py_NewRef(name);
1297     tvt->default_value = Py_XNewRef(default_value);
1298     tvt->evaluate_default = NULL;
1299     _PyObject_GC_TRACK(tvt);
1300     if (module != NULL) {
1301         if (PyObject_SetAttrString((PyObject *)tvt, "__module__", module) < 0) {
1302             Py_DECREF(tvt);
1303             return NULL;
1304         }
1305     }
1306     return tvt;
1307 }
1308 
1309 /*[clinic input]
1310 @classmethod
1311 typevartuple.__new__
1312 
1313     name: object(subclass_of="&PyUnicode_Type")
1314     *
1315     default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault
1316 
1317 Create a new TypeVarTuple with the given name.
1318 [clinic start generated code]*/
1319 
1320 static PyObject *
typevartuple_impl(PyTypeObject * type,PyObject * name,PyObject * default_value)1321 typevartuple_impl(PyTypeObject *type, PyObject *name,
1322                   PyObject *default_value)
1323 /*[clinic end generated code: output=9d6b76dfe95aae51 input=e149739929a866d0]*/
1324 {
1325     PyObject *module = caller();
1326     if (module == NULL) {
1327         return NULL;
1328     }
1329     PyObject *result = (PyObject *)typevartuple_alloc(name, module, default_value);
1330     Py_DECREF(module);
1331     return result;
1332 }
1333 
1334 /*[clinic input]
1335 typevartuple.__typing_subst__ as typevartuple_typing_subst
1336 
1337     arg: object
1338     /
1339 
1340 [clinic start generated code]*/
1341 
1342 static PyObject *
typevartuple_typing_subst(typevartupleobject * self,PyObject * arg)1343 typevartuple_typing_subst(typevartupleobject *self, PyObject *arg)
1344 /*[clinic end generated code: output=237054c6d7484eea input=3fcf2dfd9eee7945]*/
1345 {
1346     PyErr_SetString(PyExc_TypeError, "Substitution of bare TypeVarTuple is not supported");
1347     return NULL;
1348 }
1349 
1350 /*[clinic input]
1351 typevartuple.__typing_prepare_subst__ as typevartuple_typing_prepare_subst
1352 
1353     alias: object
1354     args: object
1355     /
1356 
1357 [clinic start generated code]*/
1358 
1359 static PyObject *
typevartuple_typing_prepare_subst_impl(typevartupleobject * self,PyObject * alias,PyObject * args)1360 typevartuple_typing_prepare_subst_impl(typevartupleobject *self,
1361                                        PyObject *alias, PyObject *args)
1362 /*[clinic end generated code: output=ff999bc5b02036c1 input=685b149b0fc47556]*/
1363 {
1364     PyObject *args_array[3] = {(PyObject *)self, alias, args};
1365     PyObject *result = call_typing_func_object(
1366         "_typevartuple_prepare_subst", args_array, 3);
1367     return result;
1368 }
1369 
1370 /*[clinic input]
1371 typevartuple.__reduce__ as typevartuple_reduce
1372 
1373 [clinic start generated code]*/
1374 
1375 static PyObject *
typevartuple_reduce_impl(typevartupleobject * self)1376 typevartuple_reduce_impl(typevartupleobject *self)
1377 /*[clinic end generated code: output=3215bc0477913d20 input=3018a4d66147e807]*/
1378 {
1379     return Py_NewRef(self->name);
1380 }
1381 
1382 
1383 /*[clinic input]
1384 typevartuple.has_default as typevartuple_has_default
1385 
1386 [clinic start generated code]*/
1387 
1388 static PyObject *
typevartuple_has_default_impl(typevartupleobject * self)1389 typevartuple_has_default_impl(typevartupleobject *self)
1390 /*[clinic end generated code: output=4895f602f56a5e29 input=9ef3250ddb2c1851]*/
1391 {
1392     if (self->evaluate_default != NULL ||
1393         (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) {
1394         Py_RETURN_TRUE;
1395     }
1396     Py_RETURN_FALSE;
1397 }
1398 
1399 static PyObject *
typevartuple_mro_entries(PyObject * self,PyObject * args)1400 typevartuple_mro_entries(PyObject *self, PyObject *args)
1401 {
1402     PyErr_SetString(PyExc_TypeError,
1403                     "Cannot subclass an instance of TypeVarTuple");
1404     return NULL;
1405 }
1406 
1407 static int
typevartuple_traverse(PyObject * self,visitproc visit,void * arg)1408 typevartuple_traverse(PyObject *self, visitproc visit, void *arg)
1409 {
1410     Py_VISIT(Py_TYPE(self));
1411     Py_VISIT(((typevartupleobject *)self)->default_value);
1412     Py_VISIT(((typevartupleobject *)self)->evaluate_default);
1413     PyObject_VisitManagedDict(self, visit, arg);
1414     return 0;
1415 }
1416 
1417 static int
typevartuple_clear(PyObject * self)1418 typevartuple_clear(PyObject *self)
1419 {
1420     Py_CLEAR(((typevartupleobject *)self)->default_value);
1421     Py_CLEAR(((typevartupleobject *)self)->evaluate_default);
1422     PyObject_ClearManagedDict(self);
1423     return 0;
1424 }
1425 
1426 static PyObject *
typevartuple_default(typevartupleobject * self,void * unused)1427 typevartuple_default(typevartupleobject *self, void *unused)
1428 {
1429     if (self->default_value != NULL) {
1430         return Py_NewRef(self->default_value);
1431     }
1432     if (self->evaluate_default == NULL) {
1433         return &_Py_NoDefaultStruct;
1434     }
1435     PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default);
1436     self->default_value = Py_XNewRef(default_value);
1437     return default_value;
1438 }
1439 
1440 static PyGetSetDef typevartuple_getset[] = {
1441     {"__default__", (getter)typevartuple_default, NULL, "The default value for this TypeVarTuple.", NULL},
1442     {0},
1443 };
1444 
1445 static PyMethodDef typevartuple_methods[] = {
1446     TYPEVARTUPLE_TYPING_SUBST_METHODDEF
1447     TYPEVARTUPLE_TYPING_PREPARE_SUBST_METHODDEF
1448     TYPEVARTUPLE_REDUCE_METHODDEF
1449     TYPEVARTUPLE_HAS_DEFAULT_METHODDEF
1450     {"__mro_entries__", typevartuple_mro_entries, METH_O},
1451     {0}
1452 };
1453 
1454 PyDoc_STRVAR(typevartuple_doc,
1455 "Type variable tuple. A specialized form of type variable that enables\n\
1456 variadic generics.\n\
1457 \n\
1458 The preferred way to construct a type variable tuple is via the\n\
1459 dedicated syntax for generic functions, classes, and type aliases,\n\
1460 where a single '*' indicates a type variable tuple::\n\
1461 \n\
1462     def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n\
1463         return (*tup[1:], tup[0])\n\
1464 \n\
1465 Type variables tuples can have default values:\n\
1466 \n\
1467     type AliasWithDefault[*Ts = (str, int)] = tuple[*Ts]\n\
1468 \n\
1469 For compatibility with Python 3.11 and earlier, TypeVarTuple objects\n\
1470 can also be created as follows::\n\
1471 \n\
1472     Ts = TypeVarTuple('Ts')  # Can be given any name\n\
1473     DefaultTs = TypeVarTuple('Ts', default=(str, int))\n\
1474 \n\
1475 Just as a TypeVar (type variable) is a placeholder for a single type,\n\
1476 a TypeVarTuple is a placeholder for an *arbitrary* number of types. For\n\
1477 example, if we define a generic class using a TypeVarTuple::\n\
1478 \n\
1479     class C[*Ts]: ...\n\
1480 \n\
1481 Then we can parameterize that class with an arbitrary number of type\n\
1482 arguments::\n\
1483 \n\
1484     C[int]       # Fine\n\
1485     C[int, str]  # Also fine\n\
1486     C[()]        # Even this is fine\n\
1487 \n\
1488 For more details, see PEP 646.\n\
1489 \n\
1490 Note that only TypeVarTuples defined in the global scope can be\n\
1491 pickled.\n\
1492 ");
1493 
1494 PyType_Slot typevartuple_slots[] = {
1495     {Py_tp_doc, (void *)typevartuple_doc},
1496     {Py_tp_members, typevartuple_members},
1497     {Py_tp_methods, typevartuple_methods},
1498     {Py_tp_getset, typevartuple_getset},
1499     {Py_tp_new, typevartuple},
1500     {Py_tp_iter, typevartuple_iter},
1501     {Py_tp_repr, typevartuple_repr},
1502     {Py_tp_dealloc, typevartuple_dealloc},
1503     {Py_tp_alloc, PyType_GenericAlloc},
1504     {Py_tp_free, PyObject_GC_Del},
1505     {Py_tp_traverse, typevartuple_traverse},
1506     {Py_tp_clear, typevartuple_clear},
1507     {0, 0},
1508 };
1509 
1510 PyType_Spec typevartuple_spec = {
1511     .name = "typing.TypeVarTuple",
1512     .basicsize = sizeof(typevartupleobject),
1513     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_MANAGED_DICT
1514         | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_WEAKREF,
1515     .slots = typevartuple_slots,
1516 };
1517 
1518 PyObject *
_Py_make_typevar(PyObject * name,PyObject * evaluate_bound,PyObject * evaluate_constraints)1519 _Py_make_typevar(PyObject *name, PyObject *evaluate_bound, PyObject *evaluate_constraints)
1520 {
1521     return (PyObject *)typevar_alloc(name, NULL, evaluate_bound, NULL, evaluate_constraints,
1522                                      NULL, false, false, true, NULL);
1523 }
1524 
1525 PyObject *
_Py_make_paramspec(PyThreadState * Py_UNUSED (ignored),PyObject * v)1526 _Py_make_paramspec(PyThreadState *Py_UNUSED(ignored), PyObject *v)
1527 {
1528     assert(PyUnicode_Check(v));
1529     return (PyObject *)paramspec_alloc(v, NULL, NULL, false, false, true, NULL);
1530 }
1531 
1532 PyObject *
_Py_make_typevartuple(PyThreadState * Py_UNUSED (ignored),PyObject * v)1533 _Py_make_typevartuple(PyThreadState *Py_UNUSED(ignored), PyObject *v)
1534 {
1535     assert(PyUnicode_Check(v));
1536     return (PyObject *)typevartuple_alloc(v, NULL, NULL);
1537 }
1538 
1539 static void
typealias_dealloc(PyObject * self)1540 typealias_dealloc(PyObject *self)
1541 {
1542     PyTypeObject *tp = Py_TYPE(self);
1543     _PyObject_GC_UNTRACK(self);
1544     typealiasobject *ta = (typealiasobject *)self;
1545     Py_DECREF(ta->name);
1546     Py_XDECREF(ta->type_params);
1547     Py_XDECREF(ta->compute_value);
1548     Py_XDECREF(ta->value);
1549     Py_XDECREF(ta->module);
1550     Py_TYPE(self)->tp_free(self);
1551     Py_DECREF(tp);
1552 }
1553 
1554 static PyObject *
typealias_get_value(typealiasobject * ta)1555 typealias_get_value(typealiasobject *ta)
1556 {
1557     if (ta->value != NULL) {
1558         return Py_NewRef(ta->value);
1559     }
1560     PyObject *result = PyObject_CallNoArgs(ta->compute_value);
1561     if (result == NULL) {
1562         return NULL;
1563     }
1564     ta->value = Py_NewRef(result);
1565     return result;
1566 }
1567 
1568 static PyObject *
typealias_repr(PyObject * self)1569 typealias_repr(PyObject *self)
1570 {
1571     typealiasobject *ta = (typealiasobject *)self;
1572     return Py_NewRef(ta->name);
1573 }
1574 
1575 static PyMemberDef typealias_members[] = {
1576     {"__name__", _Py_T_OBJECT, offsetof(typealiasobject, name), Py_READONLY},
1577     {0}
1578 };
1579 
1580 static PyObject *
typealias_value(PyObject * self,void * unused)1581 typealias_value(PyObject *self, void *unused)
1582 {
1583     typealiasobject *ta = (typealiasobject *)self;
1584     return typealias_get_value(ta);
1585 }
1586 
1587 static PyObject *
typealias_parameters(PyObject * self,void * unused)1588 typealias_parameters(PyObject *self, void *unused)
1589 {
1590     typealiasobject *ta = (typealiasobject *)self;
1591     if (ta->type_params == NULL) {
1592         return PyTuple_New(0);
1593     }
1594     return unpack_typevartuples(ta->type_params);
1595 }
1596 
1597 static PyObject *
typealias_type_params(PyObject * self,void * unused)1598 typealias_type_params(PyObject *self, void *unused)
1599 {
1600     typealiasobject *ta = (typealiasobject *)self;
1601     if (ta->type_params == NULL) {
1602         return PyTuple_New(0);
1603     }
1604     return Py_NewRef(ta->type_params);
1605 }
1606 
1607 static PyObject *
typealias_module(PyObject * self,void * unused)1608 typealias_module(PyObject *self, void *unused)
1609 {
1610     typealiasobject *ta = (typealiasobject *)self;
1611     if (ta->module != NULL) {
1612         return Py_NewRef(ta->module);
1613     }
1614     if (ta->compute_value != NULL) {
1615         PyObject* mod = PyFunction_GetModule(ta->compute_value);
1616         if (mod != NULL) {
1617             // PyFunction_GetModule() returns a borrowed reference,
1618             // and it may return NULL (e.g., for functions defined
1619             // in an exec()'ed block).
1620             return Py_NewRef(mod);
1621         }
1622     }
1623     Py_RETURN_NONE;
1624 }
1625 
1626 static PyGetSetDef typealias_getset[] = {
1627     {"__parameters__", typealias_parameters, (setter)NULL, NULL, NULL},
1628     {"__type_params__", typealias_type_params, (setter)NULL, NULL, NULL},
1629     {"__value__", typealias_value, (setter)NULL, NULL, NULL},
1630     {"__module__", typealias_module, (setter)NULL, NULL, NULL},
1631     {0}
1632 };
1633 
1634 static typealiasobject *
typealias_alloc(PyObject * name,PyObject * type_params,PyObject * compute_value,PyObject * value,PyObject * module)1635 typealias_alloc(PyObject *name, PyObject *type_params, PyObject *compute_value,
1636                 PyObject *value, PyObject *module)
1637 {
1638     typealiasobject *ta = PyObject_GC_New(typealiasobject, &_PyTypeAlias_Type);
1639     if (ta == NULL) {
1640         return NULL;
1641     }
1642     ta->name = Py_NewRef(name);
1643     if (
1644         type_params == NULL
1645         || Py_IsNone(type_params)
1646         || (PyTuple_Check(type_params) && PyTuple_GET_SIZE(type_params) == 0)
1647     ) {
1648         ta->type_params = NULL;
1649     }
1650     else {
1651         ta->type_params = Py_NewRef(type_params);
1652     }
1653     ta->compute_value = Py_XNewRef(compute_value);
1654     ta->value = Py_XNewRef(value);
1655     ta->module = Py_XNewRef(module);
1656     _PyObject_GC_TRACK(ta);
1657     return ta;
1658 }
1659 
1660 static int
typealias_traverse(typealiasobject * self,visitproc visit,void * arg)1661 typealias_traverse(typealiasobject *self, visitproc visit, void *arg)
1662 {
1663     Py_VISIT(self->type_params);
1664     Py_VISIT(self->compute_value);
1665     Py_VISIT(self->value);
1666     Py_VISIT(self->module);
1667     return 0;
1668 }
1669 
1670 static int
typealias_clear(typealiasobject * self)1671 typealias_clear(typealiasobject *self)
1672 {
1673     Py_CLEAR(self->type_params);
1674     Py_CLEAR(self->compute_value);
1675     Py_CLEAR(self->value);
1676     Py_CLEAR(self->module);
1677     return 0;
1678 }
1679 
1680 /*[clinic input]
1681 typealias.__reduce__ as typealias_reduce
1682 
1683 [clinic start generated code]*/
1684 
1685 static PyObject *
typealias_reduce_impl(typealiasobject * self)1686 typealias_reduce_impl(typealiasobject *self)
1687 /*[clinic end generated code: output=913724f92ad3b39b input=4f06fbd9472ec0f1]*/
1688 {
1689     return Py_NewRef(self->name);
1690 }
1691 
1692 static PyObject *
typealias_subscript(PyObject * self,PyObject * args)1693 typealias_subscript(PyObject *self, PyObject *args)
1694 {
1695     if (((typealiasobject *)self)->type_params == NULL) {
1696         PyErr_SetString(PyExc_TypeError,
1697                         "Only generic type aliases are subscriptable");
1698         return NULL;
1699     }
1700     return Py_GenericAlias(self, args);
1701 }
1702 
1703 static PyMethodDef typealias_methods[] = {
1704     TYPEALIAS_REDUCE_METHODDEF
1705     {0}
1706 };
1707 
1708 
1709 /*[clinic input]
1710 @classmethod
1711 typealias.__new__ as typealias_new
1712 
1713     name: object(subclass_of="&PyUnicode_Type")
1714     value: object
1715     *
1716     type_params: object = NULL
1717 
1718 Create a TypeAliasType.
1719 [clinic start generated code]*/
1720 
1721 static PyObject *
typealias_new_impl(PyTypeObject * type,PyObject * name,PyObject * value,PyObject * type_params)1722 typealias_new_impl(PyTypeObject *type, PyObject *name, PyObject *value,
1723                    PyObject *type_params)
1724 /*[clinic end generated code: output=8920ce6bdff86f00 input=df163c34e17e1a35]*/
1725 {
1726     if (type_params != NULL && !PyTuple_Check(type_params)) {
1727         PyErr_SetString(PyExc_TypeError, "type_params must be a tuple");
1728         return NULL;
1729     }
1730     PyObject *module = caller();
1731     if (module == NULL) {
1732         return NULL;
1733     }
1734     PyObject *ta = (PyObject *)typealias_alloc(name, type_params, NULL, value,
1735                                                module);
1736     Py_DECREF(module);
1737     return ta;
1738 }
1739 
1740 PyDoc_STRVAR(typealias_doc,
1741 "Type alias.\n\
1742 \n\
1743 Type aliases are created through the type statement::\n\
1744 \n\
1745     type Alias = int\n\
1746 \n\
1747 In this example, Alias and int will be treated equivalently by static\n\
1748 type checkers.\n\
1749 \n\
1750 At runtime, Alias is an instance of TypeAliasType. The __name__\n\
1751 attribute holds the name of the type alias. The value of the type alias\n\
1752 is stored in the __value__ attribute. It is evaluated lazily, so the\n\
1753 value is computed only if the attribute is accessed.\n\
1754 \n\
1755 Type aliases can also be generic::\n\
1756 \n\
1757     type ListOrSet[T] = list[T] | set[T]\n\
1758 \n\
1759 In this case, the type parameters of the alias are stored in the\n\
1760 __type_params__ attribute.\n\
1761 \n\
1762 See PEP 695 for more information.\n\
1763 ");
1764 
1765 static PyNumberMethods typealias_as_number = {
1766     .nb_or = _Py_union_type_or,
1767 };
1768 
1769 static PyMappingMethods typealias_as_mapping = {
1770     .mp_subscript = typealias_subscript,
1771 };
1772 
1773 PyTypeObject _PyTypeAlias_Type = {
1774     PyVarObject_HEAD_INIT(&PyType_Type, 0)
1775     .tp_name = "typing.TypeAliasType",
1776     .tp_basicsize = sizeof(typealiasobject),
1777     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC,
1778     .tp_doc = typealias_doc,
1779     .tp_members = typealias_members,
1780     .tp_methods = typealias_methods,
1781     .tp_getset = typealias_getset,
1782     .tp_alloc = PyType_GenericAlloc,
1783     .tp_dealloc = typealias_dealloc,
1784     .tp_new = typealias_new,
1785     .tp_free = PyObject_GC_Del,
1786     .tp_traverse = (traverseproc)typealias_traverse,
1787     .tp_clear = (inquiry)typealias_clear,
1788     .tp_repr = typealias_repr,
1789     .tp_as_number = &typealias_as_number,
1790     .tp_as_mapping = &typealias_as_mapping,
1791 };
1792 
1793 PyObject *
_Py_make_typealias(PyThreadState * unused,PyObject * args)1794 _Py_make_typealias(PyThreadState* unused, PyObject *args)
1795 {
1796     assert(PyTuple_Check(args));
1797     assert(PyTuple_GET_SIZE(args) == 3);
1798     PyObject *name = PyTuple_GET_ITEM(args, 0);
1799     assert(PyUnicode_Check(name));
1800     PyObject *type_params = PyTuple_GET_ITEM(args, 1);
1801     PyObject *compute_value = PyTuple_GET_ITEM(args, 2);
1802     assert(PyFunction_Check(compute_value));
1803     return (PyObject *)typealias_alloc(name, type_params, compute_value, NULL, NULL);
1804 }
1805 
1806 PyDoc_STRVAR(generic_doc,
1807 "Abstract base class for generic types.\n\
1808 \n\
1809 On Python 3.12 and newer, generic classes implicitly inherit from\n\
1810 Generic when they declare a parameter list after the class's name::\n\
1811 \n\
1812     class Mapping[KT, VT]:\n\
1813         def __getitem__(self, key: KT) -> VT:\n\
1814             ...\n\
1815         # Etc.\n\
1816 \n\
1817 On older versions of Python, however, generic classes have to\n\
1818 explicitly inherit from Generic.\n\
1819 \n\
1820 After a class has been declared to be generic, it can then be used as\n\
1821 follows::\n\
1822 \n\
1823     def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:\n\
1824         try:\n\
1825             return mapping[key]\n\
1826         except KeyError:\n\
1827             return default\n\
1828 ");
1829 
1830 PyDoc_STRVAR(generic_class_getitem_doc,
1831 "Parameterizes a generic class.\n\
1832 \n\
1833 At least, parameterizing a generic class is the *main* thing this\n\
1834 method does. For example, for some generic class `Foo`, this is called\n\
1835 when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.\n\
1836 \n\
1837 However, note that this method is also called when defining generic\n\
1838 classes in the first place with `class Foo[T]: ...`.\n\
1839 ");
1840 
1841 static PyObject *
call_typing_args_kwargs(const char * name,PyTypeObject * cls,PyObject * args,PyObject * kwargs)1842 call_typing_args_kwargs(const char *name, PyTypeObject *cls, PyObject *args, PyObject *kwargs)
1843 {
1844     PyObject *typing = NULL, *func = NULL, *new_args = NULL;
1845     typing = PyImport_ImportModule("typing");
1846     if (typing == NULL) {
1847         goto error;
1848     }
1849     func = PyObject_GetAttrString(typing, name);
1850     if (func == NULL) {
1851         goto error;
1852     }
1853     assert(PyTuple_Check(args));
1854     Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1855     new_args = PyTuple_New(nargs + 1);
1856     if (new_args == NULL) {
1857         goto error;
1858     }
1859     PyTuple_SET_ITEM(new_args, 0, Py_NewRef((PyObject *)cls));
1860     for (Py_ssize_t i = 0; i < nargs; i++) {
1861         PyObject *arg = PyTuple_GET_ITEM(args, i);
1862         PyTuple_SET_ITEM(new_args, i + 1, Py_NewRef(arg));
1863     }
1864     PyObject *result = PyObject_Call(func, new_args, kwargs);
1865     Py_DECREF(typing);
1866     Py_DECREF(func);
1867     Py_DECREF(new_args);
1868     return result;
1869 error:
1870     Py_XDECREF(typing);
1871     Py_XDECREF(func);
1872     Py_XDECREF(new_args);
1873     return NULL;
1874 }
1875 
1876 static PyObject *
generic_init_subclass(PyTypeObject * cls,PyObject * args,PyObject * kwargs)1877 generic_init_subclass(PyTypeObject *cls, PyObject *args, PyObject *kwargs)
1878 {
1879     return call_typing_args_kwargs("_generic_init_subclass", cls, args, kwargs);
1880 }
1881 
1882 static PyObject *
generic_class_getitem(PyTypeObject * cls,PyObject * args,PyObject * kwargs)1883 generic_class_getitem(PyTypeObject *cls, PyObject *args, PyObject *kwargs)
1884 {
1885     return call_typing_args_kwargs("_generic_class_getitem", cls, args, kwargs);
1886 }
1887 
1888 PyObject *
_Py_subscript_generic(PyThreadState * unused,PyObject * params)1889 _Py_subscript_generic(PyThreadState* unused, PyObject *params)
1890 {
1891     params = unpack_typevartuples(params);
1892 
1893     PyInterpreterState *interp = _PyInterpreterState_GET();
1894     if (interp->cached_objects.generic_type == NULL) {
1895         PyErr_SetString(PyExc_SystemError, "Cannot find Generic type");
1896         return NULL;
1897     }
1898     PyObject *args[2] = {(PyObject *)interp->cached_objects.generic_type, params};
1899     PyObject *result = call_typing_func_object("_GenericAlias", args, 2);
1900     Py_DECREF(params);
1901     return result;
1902 }
1903 
1904 static PyMethodDef generic_methods[] = {
1905     {"__class_getitem__", (PyCFunction)(void (*)(void))generic_class_getitem,
1906      METH_VARARGS | METH_KEYWORDS | METH_CLASS,
1907      generic_class_getitem_doc},
1908     {"__init_subclass__", (PyCFunction)(void (*)(void))generic_init_subclass,
1909      METH_VARARGS | METH_KEYWORDS | METH_CLASS,
1910      PyDoc_STR("Function to initialize subclasses.")},
1911     {NULL} /* Sentinel */
1912 };
1913 
1914 static void
generic_dealloc(PyObject * self)1915 generic_dealloc(PyObject *self)
1916 {
1917     PyTypeObject *tp = Py_TYPE(self);
1918     _PyObject_GC_UNTRACK(self);
1919     Py_TYPE(self)->tp_free(self);
1920     Py_DECREF(tp);
1921 }
1922 
1923 static int
generic_traverse(PyObject * self,visitproc visit,void * arg)1924 generic_traverse(PyObject *self, visitproc visit, void *arg)
1925 {
1926     Py_VISIT(Py_TYPE(self));
1927     return 0;
1928 }
1929 
1930 static PyType_Slot generic_slots[] = {
1931     {Py_tp_doc, (void *)generic_doc},
1932     {Py_tp_methods, generic_methods},
1933     {Py_tp_dealloc, generic_dealloc},
1934     {Py_tp_alloc, PyType_GenericAlloc},
1935     {Py_tp_free, PyObject_GC_Del},
1936     {Py_tp_traverse, generic_traverse},
1937     {0, NULL},
1938 };
1939 
1940 PyType_Spec generic_spec = {
1941     .name = "typing.Generic",
1942     .basicsize = sizeof(PyObject),
1943     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1944     .slots = generic_slots,
1945 };
1946 
_Py_initialize_generic(PyInterpreterState * interp)1947 int _Py_initialize_generic(PyInterpreterState *interp)
1948 {
1949 #define MAKE_TYPE(name) \
1950     do { \
1951         PyTypeObject *name ## _type = (PyTypeObject *)PyType_FromSpec(&name ## _spec); \
1952         if (name ## _type == NULL) { \
1953             return -1; \
1954         } \
1955         interp->cached_objects.name ## _type = name ## _type; \
1956     } while(0)
1957 
1958     MAKE_TYPE(generic);
1959     MAKE_TYPE(typevar);
1960     MAKE_TYPE(typevartuple);
1961     MAKE_TYPE(paramspec);
1962     MAKE_TYPE(paramspecargs);
1963     MAKE_TYPE(paramspeckwargs);
1964 #undef MAKE_TYPE
1965     return 0;
1966 }
1967 
_Py_clear_generic_types(PyInterpreterState * interp)1968 void _Py_clear_generic_types(PyInterpreterState *interp)
1969 {
1970     Py_CLEAR(interp->cached_objects.generic_type);
1971     Py_CLEAR(interp->cached_objects.typevar_type);
1972     Py_CLEAR(interp->cached_objects.typevartuple_type);
1973     Py_CLEAR(interp->cached_objects.paramspec_type);
1974     Py_CLEAR(interp->cached_objects.paramspecargs_type);
1975     Py_CLEAR(interp->cached_objects.paramspeckwargs_type);
1976 }
1977 
1978 PyObject *
_Py_set_typeparam_default(PyThreadState * ts,PyObject * typeparam,PyObject * evaluate_default)1979 _Py_set_typeparam_default(PyThreadState *ts, PyObject *typeparam, PyObject *evaluate_default)
1980 {
1981     if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.typevar_type)) {
1982         Py_XSETREF(((typevarobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default));
1983         return Py_NewRef(typeparam);
1984     }
1985     else if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.paramspec_type)) {
1986         Py_XSETREF(((paramspecobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default));
1987         return Py_NewRef(typeparam);
1988     }
1989     else if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.typevartuple_type)) {
1990         Py_XSETREF(((typevartupleobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default));
1991         return Py_NewRef(typeparam);
1992     }
1993     else {
1994         PyErr_Format(PyExc_TypeError, "Expected a type param, got %R", typeparam);
1995         return NULL;
1996     }
1997 }
1998