blob: 89fdaf42560c1b5b9bc3533bf17c4c8e59528591 [file] [log] [blame]
Maggie Moss1b4552c2020-09-09 13:23:24 -07001// types.Union -- used to represent e.g. Union[int, str], int | str
2#include "Python.h"
3#include "pycore_unionobject.h"
4#include "structmember.h"
5
6
7typedef struct {
8 PyObject_HEAD
9 PyObject *args;
10} unionobject;
11
12static void
13unionobject_dealloc(PyObject *self)
14{
15 unionobject *alias = (unionobject *)self;
16
17 Py_XDECREF(alias->args);
18 self->ob_type->tp_free(self);
19}
20
21static Py_hash_t
22union_hash(PyObject *self)
23{
24 unionobject *alias = (unionobject *)self;
25 Py_hash_t h1 = PyObject_Hash(alias->args);
26 if (h1 == -1) {
27 return -1;
28 }
29 return h1;
30}
31
32static int
33is_generic_alias_in_args(PyObject *args) {
34 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
35 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
36 PyObject *arg = PyTuple_GET_ITEM(args, iarg);
37 if (Py_TYPE(arg) == &Py_GenericAliasType) {
38 return 0;
39 }
40 }
41 return 1;
42}
43
44static PyObject *
45union_instancecheck(PyObject *self, PyObject *instance)
46{
47 unionobject *alias = (unionobject *) self;
48 Py_ssize_t nargs = PyTuple_GET_SIZE(alias->args);
49 if (!is_generic_alias_in_args(alias->args)) {
50 PyErr_SetString(PyExc_TypeError,
51 "isinstance() argument 2 cannot contain a parameterized generic");
52 return NULL;
53 }
54 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
55 PyObject *arg = PyTuple_GET_ITEM(alias->args, iarg);
56 if (arg == Py_None) {
57 arg = (PyObject *)&_PyNone_Type;
58 }
59 if (PyType_Check(arg) && PyObject_IsInstance(instance, arg) != 0) {
60 Py_RETURN_TRUE;
61 }
62 }
63 Py_RETURN_FALSE;
64}
65
66static PyObject *
67union_subclasscheck(PyObject *self, PyObject *instance)
68{
69 if (!PyType_Check(instance)) {
70 PyErr_SetString(PyExc_TypeError, "issubclass() arg 1 must be a class");
71 return NULL;
72 }
73 unionobject *alias = (unionobject *)self;
74 if (!is_generic_alias_in_args(alias->args)) {
75 PyErr_SetString(PyExc_TypeError,
76 "issubclass() argument 2 cannot contain a parameterized generic");
77 return NULL;
78 }
79 Py_ssize_t nargs = PyTuple_GET_SIZE(alias->args);
80 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
81 PyObject *arg = PyTuple_GET_ITEM(alias->args, iarg);
82 if (PyType_Check(arg) && (PyType_IsSubtype((PyTypeObject *)instance, (PyTypeObject *)arg) != 0)) {
83 Py_RETURN_TRUE;
84 }
85 }
86 Py_RETURN_FALSE;
87}
88
89static int
90is_typing_module(PyObject *obj) {
91 PyObject *module = PyObject_GetAttrString(obj, "__module__");
92 if (module == NULL) {
93 return -1;
94 }
95 int is_typing = PyUnicode_Check(module) && _PyUnicode_EqualToASCIIString(module, "typing");
96 Py_DECREF(module);
97 return is_typing;
98}
99
100static int
101is_typing_name(PyObject *obj, char *name)
102{
103 PyTypeObject *type = Py_TYPE(obj);
104 if (strcmp(type->tp_name, name) != 0) {
105 return 0;
106 }
107 return is_typing_module(obj);
108}
109
110static PyObject *
111union_richcompare(PyObject *a, PyObject *b, int op)
112{
113 PyObject *result = NULL;
114 if (op != Py_EQ && op != Py_NE) {
115 result = Py_NotImplemented;
116 Py_INCREF(result);
117 return result;
118 }
119
120 PyTypeObject *type = Py_TYPE(b);
121
122 PyObject* a_set = PySet_New(((unionobject*)a)->args);
123 if (a_set == NULL) {
124 return NULL;
125 }
126 PyObject* b_set = PySet_New(NULL);
127 if (b_set == NULL) {
128 goto exit;
129 }
130
131 // Populate b_set with the data from the right object
132 int is_typing_union = is_typing_name(b, "_UnionGenericAlias");
133 if (is_typing_union < 0) {
134 goto exit;
135 }
136 if (is_typing_union) {
137 PyObject *b_args = PyObject_GetAttrString(b, "__args__");
138 if (b_args == NULL) {
139 goto exit;
140 }
141 if (!PyTuple_CheckExact(b_args)) {
142 Py_DECREF(b_args);
143 PyErr_SetString(PyExc_TypeError, "__args__ argument of typing.Union object is not a tuple");
144 goto exit;
145 }
146 Py_ssize_t b_arg_length = PyTuple_GET_SIZE(b_args);
147 for (Py_ssize_t i = 0; i < b_arg_length; i++) {
148 PyObject* arg = PyTuple_GET_ITEM(b_args, i);
149 if (arg == (PyObject *)&_PyNone_Type) {
150 arg = Py_None;
151 }
152 if (PySet_Add(b_set, arg) == -1) {
153 Py_DECREF(b_args);
154 goto exit;
155 }
156 }
157 Py_DECREF(b_args);
158 } else if (type == &_Py_UnionType) {
159 PyObject* args = ((unionobject*) b)->args;
160 Py_ssize_t arg_length = PyTuple_GET_SIZE(args);
161 for (Py_ssize_t i = 0; i < arg_length; i++) {
162 PyObject* arg = PyTuple_GET_ITEM(args, i);
163 if (PySet_Add(b_set, arg) == -1) {
164 goto exit;
165 }
166 }
167 } else {
168 if (PySet_Add(b_set, b) == -1) {
169 goto exit;
170 }
171 }
172 result = PyObject_RichCompare(a_set, b_set, op);
173exit:
174 Py_XDECREF(a_set);
175 Py_XDECREF(b_set);
176 return result;
177}
178
179static PyObject*
180flatten_args(PyObject* args)
181{
Victor Stinnerd67de0a2020-09-23 23:25:54 +0200182 Py_ssize_t arg_length = PyTuple_GET_SIZE(args);
183 Py_ssize_t total_args = 0;
Maggie Moss1b4552c2020-09-09 13:23:24 -0700184 // Get number of total args once it's flattened.
185 for (Py_ssize_t i = 0; i < arg_length; i++) {
186 PyObject *arg = PyTuple_GET_ITEM(args, i);
187 PyTypeObject* arg_type = Py_TYPE(arg);
188 if (arg_type == &_Py_UnionType) {
189 total_args += PyTuple_GET_SIZE(((unionobject*) arg)->args);
190 } else {
191 total_args++;
192 }
193 }
194 // Create new tuple of flattened args.
195 PyObject *flattened_args = PyTuple_New(total_args);
196 if (flattened_args == NULL) {
197 return NULL;
198 }
199 Py_ssize_t pos = 0;
200 for (Py_ssize_t i = 0; i < arg_length; i++) {
201 PyObject *arg = PyTuple_GET_ITEM(args, i);
202 PyTypeObject* arg_type = Py_TYPE(arg);
203 if (arg_type == &_Py_UnionType) {
204 PyObject* nested_args = ((unionobject*)arg)->args;
Victor Stinnerd73cf7c2020-09-26 12:48:41 +0200205 Py_ssize_t nested_arg_length = PyTuple_GET_SIZE(nested_args);
206 for (Py_ssize_t j = 0; j < nested_arg_length; j++) {
Maggie Moss1b4552c2020-09-09 13:23:24 -0700207 PyObject* nested_arg = PyTuple_GET_ITEM(nested_args, j);
208 Py_INCREF(nested_arg);
209 PyTuple_SET_ITEM(flattened_args, pos, nested_arg);
210 pos++;
211 }
212 } else {
213 Py_INCREF(arg);
214 PyTuple_SET_ITEM(flattened_args, pos, arg);
215 pos++;
216 }
217 }
218 return flattened_args;
219}
220
221static PyObject*
222dedup_and_flatten_args(PyObject* args)
223{
224 args = flatten_args(args);
225 if (args == NULL) {
226 return NULL;
227 }
228 Py_ssize_t arg_length = PyTuple_GET_SIZE(args);
229 PyObject *new_args = PyTuple_New(arg_length);
230 if (new_args == NULL) {
231 return NULL;
232 }
233 // Add unique elements to an array.
Victor Stinnerd73cf7c2020-09-26 12:48:41 +0200234 Py_ssize_t added_items = 0;
Maggie Moss1b4552c2020-09-09 13:23:24 -0700235 for (Py_ssize_t i = 0; i < arg_length; i++) {
236 int is_duplicate = 0;
237 PyObject* i_element = PyTuple_GET_ITEM(args, i);
238 for (Py_ssize_t j = i + 1; j < arg_length; j++) {
239 PyObject* j_element = PyTuple_GET_ITEM(args, j);
240 if (i_element == j_element) {
241 is_duplicate = 1;
242 }
243 }
244 if (!is_duplicate) {
245 Py_INCREF(i_element);
246 PyTuple_SET_ITEM(new_args, added_items, i_element);
247 added_items++;
248 }
249 }
250 Py_DECREF(args);
251 _PyTuple_Resize(&new_args, added_items);
252 return new_args;
253}
254
255static int
256is_typevar(PyObject *obj)
257{
258 return is_typing_name(obj, "TypeVar");
259}
260
261static int
262is_special_form(PyObject *obj)
263{
264 return is_typing_name(obj, "_SpecialForm");
265}
266
267static int
268is_new_type(PyObject *obj)
269{
270 PyTypeObject *type = Py_TYPE(obj);
271 if (type != &PyFunction_Type) {
272 return 0;
273 }
274 return is_typing_module(obj);
275}
276
277static int
278is_unionable(PyObject *obj)
279{
280 if (obj == Py_None) {
281 return 1;
282 }
283 PyTypeObject *type = Py_TYPE(obj);
284 return (
285 is_typevar(obj) ||
286 is_new_type(obj) ||
287 is_special_form(obj) ||
288 PyType_Check(obj) ||
289 type == &Py_GenericAliasType ||
290 type == &_Py_UnionType);
291}
292
293static PyObject *
294type_or(PyTypeObject* self, PyObject* param)
295{
296 PyObject *tuple = PyTuple_Pack(2, self, param);
297 if (tuple == NULL) {
298 return NULL;
299 }
300 PyObject *new_union = _Py_Union(tuple);
301 Py_DECREF(tuple);
302 return new_union;
303}
304
305static int
306union_repr_item(_PyUnicodeWriter *writer, PyObject *p)
307{
308 _Py_IDENTIFIER(__module__);
309 _Py_IDENTIFIER(__qualname__);
310 _Py_IDENTIFIER(__origin__);
311 _Py_IDENTIFIER(__args__);
312 PyObject *qualname = NULL;
313 PyObject *module = NULL;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300314 PyObject *tmp;
Maggie Moss1b4552c2020-09-09 13:23:24 -0700315 PyObject *r = NULL;
316 int err;
317
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300318 if (_PyObject_LookupAttrId(p, &PyId___origin__, &tmp) < 0) {
Maggie Moss1b4552c2020-09-09 13:23:24 -0700319 goto exit;
320 }
321
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300322 if (tmp) {
323 Py_DECREF(tmp);
324 if (_PyObject_LookupAttrId(p, &PyId___args__, &tmp) < 0) {
Maggie Moss1b4552c2020-09-09 13:23:24 -0700325 goto exit;
326 }
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300327 if (tmp) {
Maggie Moss1b4552c2020-09-09 13:23:24 -0700328 // It looks like a GenericAlias
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300329 Py_DECREF(tmp);
Maggie Moss1b4552c2020-09-09 13:23:24 -0700330 goto use_repr;
331 }
332 }
333
334 if (_PyObject_LookupAttrId(p, &PyId___qualname__, &qualname) < 0) {
335 goto exit;
336 }
337 if (qualname == NULL) {
338 goto use_repr;
339 }
340 if (_PyObject_LookupAttrId(p, &PyId___module__, &module) < 0) {
341 goto exit;
342 }
343 if (module == NULL || module == Py_None) {
344 goto use_repr;
345 }
346
347 // Looks like a class
348 if (PyUnicode_Check(module) &&
349 _PyUnicode_EqualToASCIIString(module, "builtins"))
350 {
351 // builtins don't need a module name
352 r = PyObject_Str(qualname);
353 goto exit;
354 }
355 else {
356 r = PyUnicode_FromFormat("%S.%S", module, qualname);
357 goto exit;
358 }
359
360use_repr:
361 r = PyObject_Repr(p);
362exit:
363 Py_XDECREF(qualname);
364 Py_XDECREF(module);
365 if (r == NULL) {
366 return -1;
367 }
368 err = _PyUnicodeWriter_WriteStr(writer, r);
369 Py_DECREF(r);
370 return err;
371}
372
373static PyObject *
374union_repr(PyObject *self)
375{
376 unionobject *alias = (unionobject *)self;
377 Py_ssize_t len = PyTuple_GET_SIZE(alias->args);
378
379 _PyUnicodeWriter writer;
380 _PyUnicodeWriter_Init(&writer);
381 for (Py_ssize_t i = 0; i < len; i++) {
382 if (i > 0 && _PyUnicodeWriter_WriteASCIIString(&writer, " | ", 3) < 0) {
383 goto error;
384 }
385 PyObject *p = PyTuple_GET_ITEM(alias->args, i);
386 if (union_repr_item(&writer, p) < 0) {
387 goto error;
388 }
389 }
390 return _PyUnicodeWriter_Finish(&writer);
391error:
392 _PyUnicodeWriter_Dealloc(&writer);
393 return NULL;
394}
395
396static PyMemberDef union_members[] = {
397 {"__args__", T_OBJECT, offsetof(unionobject, args), READONLY},
398 {0}
399};
400
401static PyMethodDef union_methods[] = {
402 {"__instancecheck__", union_instancecheck, METH_O},
403 {"__subclasscheck__", union_subclasscheck, METH_O},
404 {0}};
405
406static PyNumberMethods union_as_number = {
407 .nb_or = (binaryfunc)type_or, // Add __or__ function
408};
409
410PyTypeObject _Py_UnionType = {
411 PyVarObject_HEAD_INIT(&PyType_Type, 0)
412 .tp_name = "types.Union",
413 .tp_doc = "Represent a PEP 604 union type\n"
414 "\n"
415 "E.g. for int | str",
416 .tp_basicsize = sizeof(unionobject),
417 .tp_dealloc = unionobject_dealloc,
418 .tp_alloc = PyType_GenericAlloc,
419 .tp_free = PyObject_Del,
420 .tp_flags = Py_TPFLAGS_DEFAULT,
421 .tp_hash = union_hash,
422 .tp_getattro = PyObject_GenericGetAttr,
423 .tp_members = union_members,
424 .tp_methods = union_methods,
425 .tp_richcompare = union_richcompare,
426 .tp_as_number = &union_as_number,
427 .tp_repr = union_repr,
428};
429
430PyObject *
431_Py_Union(PyObject *args)
432{
433 assert(PyTuple_CheckExact(args));
434
435 unionobject* result = NULL;
436
437 // Check arguments are unionable.
Victor Stinnerd67de0a2020-09-23 23:25:54 +0200438 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Maggie Moss1b4552c2020-09-09 13:23:24 -0700439 for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
440 PyObject *arg = PyTuple_GET_ITEM(args, iarg);
441 if (arg == NULL) {
442 return NULL;
443 }
444 int is_arg_unionable = is_unionable(arg);
445 if (is_arg_unionable < 0) {
446 return NULL;
447 }
448 if (!is_arg_unionable) {
449 Py_INCREF(Py_NotImplemented);
450 return Py_NotImplemented;
451 }
452 }
453
454 result = PyObject_New(unionobject, &_Py_UnionType);
455 if (result == NULL) {
456 return NULL;
457 }
458
459 result->args = dedup_and_flatten_args(args);
460 if (result->args == NULL) {
461 Py_DECREF(result);
462 return NULL;
463 }
464 return (PyObject*)result;
465}