Coverage Report

Created: 2026-04-20 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/complexobject.c
Line
Count
Source
1
/* Complex object implementation */
2
3
/* Borrows heavily from floatobject.c */
4
5
/* Submitted by Jim Hugunin */
6
7
#include "Python.h"
8
#include "pycore_call.h"          // _PyObject_CallNoArgs()
9
#include "pycore_complexobject.h" // _PyComplex_FormatAdvancedWriter()
10
#include "pycore_floatobject.h"   // _Py_convert_int_to_double()
11
#include "pycore_freelist.h"      // _Py_FREELIST_FREE(), _Py_FREELIST_POP()
12
#include "pycore_long.h"          // _PyLong_GetZero()
13
#include "pycore_object.h"        // _PyObject_Init()
14
#include "pycore_pymath.h"        // _Py_ADJUST_ERANGE2()
15
16
17
110k
#define _PyComplexObject_CAST(op)   ((PyComplexObject *)(op))
18
19
20
/*[clinic input]
21
class complex "PyComplexObject *" "&PyComplex_Type"
22
[clinic start generated code]*/
23
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
24
25
#include "clinic/complexobject.c.h"
26
27
/* elementary operations on complex numbers */
28
29
static Py_complex c_1 = {1., 0.};
30
31
Py_complex
32
_Py_c_sum(Py_complex a, Py_complex b)
33
784
{
34
784
    Py_complex r;
35
784
    r.real = a.real + b.real;
36
784
    r.imag = a.imag + b.imag;
37
784
    return r;
38
784
}
39
40
Py_complex
41
_Py_cr_sum(Py_complex a, double b)
42
19.9k
{
43
19.9k
    Py_complex r = a;
44
19.9k
    r.real += b;
45
19.9k
    return r;
46
19.9k
}
47
48
static inline Py_complex
49
_Py_rc_sum(double a, Py_complex b)
50
834
{
51
834
    return _Py_cr_sum(b, a);
52
834
}
53
54
Py_complex
55
_Py_c_diff(Py_complex a, Py_complex b)
56
958
{
57
958
    Py_complex r;
58
958
    r.real = a.real - b.real;
59
958
    r.imag = a.imag - b.imag;
60
958
    return r;
61
958
}
62
63
Py_complex
64
_Py_cr_diff(Py_complex a, double b)
65
11.3k
{
66
11.3k
    Py_complex r = a;
67
11.3k
    r.real -= b;
68
11.3k
    return r;
69
11.3k
}
70
71
Py_complex
72
_Py_rc_diff(double a, Py_complex b)
73
159
{
74
159
    Py_complex r;
75
159
    r.real = a - b.real;
76
159
    r.imag = -b.imag;
77
159
    return r;
78
159
}
79
80
Py_complex
81
_Py_c_neg(Py_complex a)
82
0
{
83
0
    Py_complex r;
84
0
    r.real = -a.real;
85
0
    r.imag = -a.imag;
86
0
    return r;
87
0
}
88
89
Py_complex
90
_Py_c_prod(Py_complex z, Py_complex w)
91
29.4k
{
92
29.4k
    double a = z.real, b = z.imag, c = w.real, d = w.imag;
93
29.4k
    double ac = a*c, bd = b*d, ad = a*d, bc = b*c;
94
29.4k
    Py_complex r = {ac - bd, ad + bc};
95
96
    /* Recover infinities that computed as nan+nanj.  See e.g. the C11,
97
       Annex G.5.1, routine _Cmultd(). */
98
29.4k
    if (isnan(r.real) && isnan(r.imag)) {
99
3.36k
        int recalc = 0;
100
101
3.36k
        if (isinf(a) || isinf(b)) {  /* z is infinite */
102
            /* "Box" the infinity and change nans in the other factor to 0 */
103
2.16k
            a = copysign(isinf(a) ? 1.0 : 0.0, a);
104
2.16k
            b = copysign(isinf(b) ? 1.0 : 0.0, b);
105
2.16k
            if (isnan(c)) {
106
144
                c = copysign(0.0, c);
107
144
            }
108
2.16k
            if (isnan(d)) {
109
403
                d = copysign(0.0, d);
110
403
            }
111
2.16k
            recalc = 1;
112
2.16k
        }
113
3.36k
        if (isinf(c) || isinf(d)) {  /* w is infinite */
114
            /* "Box" the infinity and change nans in the other factor to 0 */
115
772
            c = copysign(isinf(c) ? 1.0 : 0.0, c);
116
772
            d = copysign(isinf(d) ? 1.0 : 0.0, d);
117
772
            if (isnan(a)) {
118
120
                a = copysign(0.0, a);
119
120
            }
120
772
            if (isnan(b)) {
121
120
                b = copysign(0.0, b);
122
120
            }
123
772
            recalc = 1;
124
772
        }
125
3.36k
        if (!recalc && (isinf(ac) || isinf(bd) || isinf(ad) || isinf(bc))) {
126
            /* Recover infinities from overflow by changing nans to 0 */
127
0
            if (isnan(a)) {
128
0
                a = copysign(0.0, a);
129
0
            }
130
0
            if (isnan(b)) {
131
0
                b = copysign(0.0, b);
132
0
            }
133
0
            if (isnan(c)) {
134
0
                c = copysign(0.0, c);
135
0
            }
136
0
            if (isnan(d)) {
137
0
                d = copysign(0.0, d);
138
0
            }
139
0
            recalc = 1;
140
0
        }
141
3.36k
        if (recalc) {
142
2.32k
            r.real = INFINITY*(a*c - b*d);
143
2.32k
            r.imag = INFINITY*(a*d + b*c);
144
2.32k
        }
145
3.36k
    }
146
147
29.4k
    return r;
148
29.4k
}
149
150
Py_complex
151
_Py_cr_prod(Py_complex a, double b)
152
3.90k
{
153
3.90k
    Py_complex r = a;
154
3.90k
    r.real *= b;
155
3.90k
    r.imag *= b;
156
3.90k
    return r;
157
3.90k
}
158
159
static inline Py_complex
160
_Py_rc_prod(double a, Py_complex b)
161
605
{
162
605
    return _Py_cr_prod(b, a);
163
605
}
164
165
/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
166
#ifdef _M_ARM64
167
#pragma optimize("", off)
168
#endif
169
Py_complex
170
_Py_c_quot(Py_complex a, Py_complex b)
171
4.47k
{
172
    /******************************************************************
173
    This was the original algorithm.  It's grossly prone to spurious
174
    overflow and underflow errors.  It also merrily divides by 0 despite
175
    checking for that(!).  The code still serves a doc purpose here, as
176
    the algorithm following is a simple by-cases transformation of this
177
    one:
178
179
    Py_complex r;
180
    double d = b.real*b.real + b.imag*b.imag;
181
    if (d == 0.)
182
        errno = EDOM;
183
    r.real = (a.real*b.real + a.imag*b.imag)/d;
184
    r.imag = (a.imag*b.real - a.real*b.imag)/d;
185
    return r;
186
    ******************************************************************/
187
188
    /* This algorithm is better, and is pretty obvious:  first divide the
189
     * numerators and denominator by whichever of {b.real, b.imag} has
190
     * larger magnitude.  The earliest reference I found was to CACM
191
     * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
192
     * University).
193
     */
194
4.47k
     Py_complex r;      /* the result */
195
4.47k
     const double abs_breal = b.real < 0 ? -b.real : b.real;
196
4.47k
     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
197
198
4.47k
    if (abs_breal >= abs_bimag) {
199
        /* divide tops and bottom by b.real */
200
2.51k
        if (abs_breal == 0.0) {
201
962
            errno = EDOM;
202
962
            r.real = r.imag = 0.0;
203
962
        }
204
1.55k
        else {
205
1.55k
            const double ratio = b.imag / b.real;
206
1.55k
            const double denom = b.real + b.imag * ratio;
207
1.55k
            r.real = (a.real + a.imag * ratio) / denom;
208
1.55k
            r.imag = (a.imag - a.real * ratio) / denom;
209
1.55k
        }
210
2.51k
    }
211
1.96k
    else if (abs_bimag >= abs_breal) {
212
        /* divide tops and bottom by b.imag */
213
1.85k
        const double ratio = b.real / b.imag;
214
1.85k
        const double denom = b.real * ratio + b.imag;
215
1.85k
        assert(b.imag != 0.0);
216
1.85k
        r.real = (a.real * ratio + a.imag) / denom;
217
1.85k
        r.imag = (a.imag * ratio - a.real) / denom;
218
1.85k
    }
219
107
    else {
220
        /* At least one of b.real or b.imag is a NaN */
221
107
        r.real = r.imag = Py_NAN;
222
107
    }
223
224
    /* Recover infinities and zeros that computed as nan+nanj.  See e.g.
225
       the C11, Annex G.5.2, routine _Cdivd(). */
226
4.47k
    if (isnan(r.real) && isnan(r.imag)) {
227
1.08k
        if ((isinf(a.real) || isinf(a.imag))
228
1.08k
            && isfinite(b.real) && isfinite(b.imag))
229
357
        {
230
357
            const double x = copysign(isinf(a.real) ? 1.0 : 0.0, a.real);
231
357
            const double y = copysign(isinf(a.imag) ? 1.0 : 0.0, a.imag);
232
357
            r.real = INFINITY * (x*b.real + y*b.imag);
233
357
            r.imag = INFINITY * (y*b.real - x*b.imag);
234
357
        }
235
724
        else if ((isinf(abs_breal) || isinf(abs_bimag))
236
724
                 && isfinite(a.real) && isfinite(a.imag))
237
13
        {
238
13
            const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
239
13
            const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
240
13
            r.real = 0.0 * (a.real*x + a.imag*y);
241
13
            r.imag = 0.0 * (a.imag*x - a.real*y);
242
13
        }
243
1.08k
    }
244
245
4.47k
    return r;
246
4.47k
}
247
248
Py_complex
249
_Py_cr_quot(Py_complex a, double b)
250
1.36k
{
251
1.36k
    Py_complex r = a;
252
1.36k
    if (b) {
253
1.07k
        r.real /= b;
254
1.07k
        r.imag /= b;
255
1.07k
    }
256
293
    else {
257
293
        errno = EDOM;
258
293
        r.real = r.imag = 0.0;
259
293
    }
260
1.36k
    return r;
261
1.36k
}
262
263
/* an equivalent of _Py_c_quot() function, when 1st argument is real */
264
Py_complex
265
_Py_rc_quot(double a, Py_complex b)
266
1.97k
{
267
1.97k
    Py_complex r;
268
1.97k
    const double abs_breal = b.real < 0 ? -b.real : b.real;
269
1.97k
    const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
270
271
1.97k
    if (abs_breal >= abs_bimag) {
272
515
        if (abs_breal == 0.0) {
273
255
            errno = EDOM;
274
255
            r.real = r.imag = 0.0;
275
255
        }
276
260
        else {
277
260
            const double ratio = b.imag / b.real;
278
260
            const double denom = b.real + b.imag * ratio;
279
260
            r.real = a / denom;
280
260
            r.imag = (-a * ratio) / denom;
281
260
        }
282
515
    }
283
1.45k
    else if (abs_bimag >= abs_breal) {
284
1.37k
        const double ratio = b.real / b.imag;
285
1.37k
        const double denom = b.real * ratio + b.imag;
286
1.37k
        assert(b.imag != 0.0);
287
1.37k
        r.real = (a * ratio) / denom;
288
1.37k
        r.imag = (-a) / denom;
289
1.37k
    }
290
79
    else {
291
79
        r.real = r.imag = Py_NAN;
292
79
    }
293
294
1.97k
    if (isnan(r.real) && isnan(r.imag) && isfinite(a)
295
79
        && (isinf(abs_breal) || isinf(abs_bimag)))
296
0
    {
297
0
        const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
298
0
        const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
299
0
        r.real = 0.0 * (a*x);
300
0
        r.imag = 0.0 * (-a*y);
301
0
    }
302
303
1.97k
    return r;
304
1.97k
}
305
#ifdef _M_ARM64
306
#pragma optimize("", on)
307
#endif
308
309
Py_complex
310
_Py_c_pow(Py_complex a, Py_complex b)
311
11.1k
{
312
11.1k
    Py_complex r;
313
11.1k
    double vabs,len,at,phase;
314
11.1k
    if (b.real == 0. && b.imag == 0.) {
315
0
        r.real = 1.;
316
0
        r.imag = 0.;
317
0
    }
318
11.1k
    else if (a.real == 0. && a.imag == 0.) {
319
612
        if (b.imag != 0. || b.real < 0.)
320
612
            errno = EDOM;
321
612
        r.real = 0.;
322
612
        r.imag = 0.;
323
612
    }
324
10.5k
    else {
325
10.5k
        vabs = hypot(a.real,a.imag);
326
10.5k
        len = pow(vabs,b.real);
327
10.5k
        at = atan2(a.imag, a.real);
328
10.5k
        phase = at*b.real;
329
10.5k
        if (b.imag != 0.0) {
330
6.75k
            len *= exp(-at*b.imag);
331
6.75k
            phase += b.imag*log(vabs);
332
6.75k
        }
333
10.5k
        r.real = len*cos(phase);
334
10.5k
        r.imag = len*sin(phase);
335
336
10.5k
        _Py_ADJUST_ERANGE2(r.real, r.imag);
337
10.5k
    }
338
11.1k
    return r;
339
11.1k
}
340
341
static Py_complex
342
c_powu(Py_complex x, long n)
343
5.64k
{
344
5.64k
    Py_complex r, p;
345
5.64k
    long mask = 1;
346
5.64k
    r = c_1;
347
5.64k
    p = x;
348
20.7k
    while (mask > 0 && n >= mask) {
349
15.0k
        if (n & mask)
350
9.50k
            r = _Py_c_prod(r,p);
351
15.0k
        mask <<= 1;
352
15.0k
        p = _Py_c_prod(p,p);
353
15.0k
    }
354
5.64k
    return r;
355
5.64k
}
356
357
static Py_complex
358
c_powi(Py_complex x, long n)
359
5.64k
{
360
5.64k
    if (n > 0)
361
3.36k
        return c_powu(x,n);
362
2.28k
    else
363
2.28k
        return _Py_c_quot(c_1, c_powu(x,-n));
364
365
5.64k
}
366
367
double
368
_Py_c_abs(Py_complex z)
369
0
{
370
    /* sets errno = ERANGE on overflow;  otherwise errno = 0 */
371
0
    double result;
372
373
0
    if (!isfinite(z.real) || !isfinite(z.imag)) {
374
        /* C99 rules: if either the real or the imaginary part is an
375
           infinity, return infinity, even if the other part is a
376
           NaN. */
377
0
        if (isinf(z.real)) {
378
0
            result = fabs(z.real);
379
0
            errno = 0;
380
0
            return result;
381
0
        }
382
0
        if (isinf(z.imag)) {
383
0
            result = fabs(z.imag);
384
0
            errno = 0;
385
0
            return result;
386
0
        }
387
        /* either the real or imaginary part is a NaN,
388
           and neither is infinite. Result should be NaN. */
389
0
        return Py_NAN;
390
0
    }
391
0
    result = hypot(z.real, z.imag);
392
0
    if (!isfinite(result))
393
0
        errno = ERANGE;
394
0
    else
395
0
        errno = 0;
396
0
    return result;
397
0
}
398
399
static PyObject *
400
complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
401
0
{
402
0
    PyObject *op;
403
404
0
    op = type->tp_alloc(type, 0);
405
0
    if (op != NULL)
406
0
        ((PyComplexObject *)op)->cval = cval;
407
0
    return op;
408
0
}
409
410
PyObject *
411
PyComplex_FromCComplex(Py_complex cval)
412
141k
{
413
141k
    PyComplexObject *op = _Py_FREELIST_POP(PyComplexObject, complexes);
414
415
141k
    if (op == NULL) {
416
        /* Inline PyObject_New */
417
71.6k
        op = PyObject_Malloc(sizeof(PyComplexObject));
418
71.6k
        if (op == NULL) {
419
0
            return PyErr_NoMemory();
420
0
        }
421
71.6k
        _PyObject_Init((PyObject*)op, &PyComplex_Type);
422
71.6k
    }
423
141k
    op->cval = cval;
424
141k
    return (PyObject *) op;
425
141k
}
426
427
static void
428
complex_dealloc(PyObject *op)
429
141k
{
430
141k
    assert(PyComplex_Check(op));
431
141k
    if (PyComplex_CheckExact(op)) {
432
141k
        _Py_FREELIST_FREE(complexes, op, PyObject_Free);
433
141k
    }
434
0
    else {
435
0
        Py_TYPE(op)->tp_free(op);
436
0
    }
437
141k
}
438
439
static PyObject *
440
complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
441
0
{
442
0
    Py_complex c;
443
0
    c.real = real;
444
0
    c.imag = imag;
445
0
    return complex_subtype_from_c_complex(type, c);
446
0
}
447
448
PyObject *
449
PyComplex_FromDoubles(double real, double imag)
450
3.04k
{
451
3.04k
    Py_complex c;
452
3.04k
    c.real = real;
453
3.04k
    c.imag = imag;
454
3.04k
    return PyComplex_FromCComplex(c);
455
3.04k
}
456
457
static PyObject * try_complex_special_method(PyObject *);
458
459
double
460
PyComplex_RealAsDouble(PyObject *op)
461
0
{
462
0
    double real = -1.0;
463
464
0
    if (PyComplex_Check(op)) {
465
0
        real = ((PyComplexObject *)op)->cval.real;
466
0
    }
467
0
    else {
468
0
        PyObject* newop = try_complex_special_method(op);
469
0
        if (newop) {
470
0
            real = ((PyComplexObject *)newop)->cval.real;
471
0
            Py_DECREF(newop);
472
0
        } else if (!PyErr_Occurred()) {
473
0
            real = PyFloat_AsDouble(op);
474
0
        }
475
0
    }
476
477
0
    return real;
478
0
}
479
480
double
481
PyComplex_ImagAsDouble(PyObject *op)
482
0
{
483
0
    double imag = -1.0;
484
485
0
    if (PyComplex_Check(op)) {
486
0
        imag = ((PyComplexObject *)op)->cval.imag;
487
0
    }
488
0
    else {
489
0
        PyObject* newop = try_complex_special_method(op);
490
0
        if (newop) {
491
0
            imag = ((PyComplexObject *)newop)->cval.imag;
492
0
            Py_DECREF(newop);
493
0
        } else if (!PyErr_Occurred()) {
494
0
            PyFloat_AsDouble(op);
495
0
            if (!PyErr_Occurred()) {
496
0
                imag = 0.0;
497
0
            }
498
0
        }
499
0
    }
500
501
0
    return imag;
502
0
}
503
504
static PyObject *
505
try_complex_special_method(PyObject *op)
506
0
{
507
0
    PyObject *f;
508
509
0
    f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__));
510
0
    if (f) {
511
0
        PyObject *res = _PyObject_CallNoArgs(f);
512
0
        Py_DECREF(f);
513
0
        if (!res || PyComplex_CheckExact(res)) {
514
0
            return res;
515
0
        }
516
0
        if (!PyComplex_Check(res)) {
517
0
            PyErr_Format(PyExc_TypeError,
518
0
                "%T.__complex__() must return a complex, not %T",
519
0
                op, res);
520
0
            Py_DECREF(res);
521
0
            return NULL;
522
0
        }
523
        /* Issue #29894: warn if 'res' not of exact type complex. */
524
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
525
0
                "%T.__complex__() must return a complex, not %T.  "
526
0
                "The ability to return an instance of a strict subclass of complex "
527
0
                "is deprecated, and may be removed in a future version of Python.",
528
0
                op, res)) {
529
0
            Py_DECREF(res);
530
0
            return NULL;
531
0
        }
532
0
        return res;
533
0
    }
534
0
    return NULL;
535
0
}
536
537
Py_complex
538
PyComplex_AsCComplex(PyObject *op)
539
98.1k
{
540
98.1k
    Py_complex cv;
541
98.1k
    PyObject *newop = NULL;
542
543
98.1k
    assert(op);
544
    /* If op is already of type PyComplex_Type, return its value */
545
98.1k
    if (PyComplex_Check(op)) {
546
98.1k
        return ((PyComplexObject *)op)->cval;
547
98.1k
    }
548
    /* If not, use op's __complex__  method, if it exists */
549
550
    /* return -1 on failure */
551
0
    cv.real = -1.;
552
0
    cv.imag = 0.;
553
554
0
    newop = try_complex_special_method(op);
555
556
0
    if (newop) {
557
0
        cv = ((PyComplexObject *)newop)->cval;
558
0
        Py_DECREF(newop);
559
0
        return cv;
560
0
    }
561
0
    else if (PyErr_Occurred()) {
562
0
        return cv;
563
0
    }
564
    /* If neither of the above works, interpret op as a float giving the
565
       real part of the result, and fill in the imaginary part as 0. */
566
0
    else {
567
        /* PyFloat_AsDouble will return -1 on failure */
568
0
        cv.real = PyFloat_AsDouble(op);
569
0
        return cv;
570
0
    }
571
0
}
572
573
static PyObject *
574
complex_repr(PyObject *op)
575
3.24k
{
576
3.24k
    int precision = 0;
577
3.24k
    char format_code = 'r';
578
3.24k
    PyObject *result = NULL;
579
3.24k
    PyComplexObject *v = _PyComplexObject_CAST(op);
580
581
    /* If these are non-NULL, they'll need to be freed. */
582
3.24k
    char *pre = NULL;
583
3.24k
    char *im = NULL;
584
585
    /* These do not need to be freed. re is either an alias
586
       for pre or a pointer to a constant.  lead and tail
587
       are pointers to constants. */
588
3.24k
    const char *re = NULL;
589
3.24k
    const char *lead = "";
590
3.24k
    const char *tail = "";
591
592
3.24k
    if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
593
        /* Real part is +0: just output the imaginary part and do not
594
           include parens. */
595
3.24k
        re = "";
596
3.24k
        im = PyOS_double_to_string(v->cval.imag, format_code,
597
3.24k
                                   precision, 0, NULL);
598
3.24k
        if (!im) {
599
0
            PyErr_NoMemory();
600
0
            goto done;
601
0
        }
602
3.24k
    } else {
603
        /* Format imaginary part with sign, real part without. Include
604
           parens in the result. */
605
0
        pre = PyOS_double_to_string(v->cval.real, format_code,
606
0
                                    precision, 0, NULL);
607
0
        if (!pre) {
608
0
            PyErr_NoMemory();
609
0
            goto done;
610
0
        }
611
0
        re = pre;
612
613
0
        im = PyOS_double_to_string(v->cval.imag, format_code,
614
0
                                   precision, Py_DTSF_SIGN, NULL);
615
0
        if (!im) {
616
0
            PyErr_NoMemory();
617
0
            goto done;
618
0
        }
619
0
        lead = "(";
620
0
        tail = ")";
621
0
    }
622
3.24k
    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
623
3.24k
  done:
624
3.24k
    PyMem_Free(im);
625
3.24k
    PyMem_Free(pre);
626
627
3.24k
    return result;
628
3.24k
}
629
630
static Py_hash_t
631
complex_hash(PyObject *op)
632
102k
{
633
102k
    Py_uhash_t hashreal, hashimag, combined;
634
102k
    PyComplexObject *v = _PyComplexObject_CAST(op);
635
102k
    hashreal = (Py_uhash_t)_Py_HashDouble(op, v->cval.real);
636
102k
    if (hashreal == (Py_uhash_t)-1)
637
0
        return -1;
638
102k
    hashimag = (Py_uhash_t)_Py_HashDouble(op, v->cval.imag);
639
102k
    if (hashimag == (Py_uhash_t)-1)
640
0
        return -1;
641
    /* Note:  if the imaginary part is 0, hashimag is 0 now,
642
     * so the following returns hashreal unchanged.  This is
643
     * important because numbers of different types that
644
     * compare equal must have the same hash value, so that
645
     * hash(x + 0*j) must equal hash(x).
646
     */
647
102k
    combined = hashreal + PyHASH_IMAG * hashimag;
648
102k
    if (combined == (Py_uhash_t)-1)
649
0
        combined = (Py_uhash_t)-2;
650
102k
    return (Py_hash_t)combined;
651
102k
}
652
653
/* This macro may return! */
654
#define TO_COMPLEX(obj, c)                      \
655
145k
    if (PyComplex_Check(obj))                   \
656
145k
        c = ((PyComplexObject *)(obj))->cval;   \
657
145k
    else if (real_to_complex(&(obj), &(c)) < 0) \
658
11.6k
        return (obj)
659
660
static int
661
real_to_double(PyObject **pobj, double *dbl)
662
50.6k
{
663
50.6k
    PyObject *obj = *pobj;
664
665
50.6k
    if (PyFloat_Check(obj)) {
666
7.51k
        *dbl = PyFloat_AS_DOUBLE(obj);
667
7.51k
    }
668
43.1k
    else if (_Py_convert_int_to_double(pobj, dbl) < 0) {
669
504
        return -1;
670
504
    }
671
50.1k
    return 0;
672
50.6k
}
673
674
static int
675
real_to_complex(PyObject **pobj, Py_complex *pc)
676
11.6k
{
677
11.6k
    pc->imag = 0.0;
678
11.6k
    return real_to_double(pobj, &(pc->real));
679
11.6k
}
680
681
/* Complex arithmetic rules implement special mixed-mode case where combining
682
   a pure-real (float or int) value and a complex value is performed directly
683
   without first coercing the real value to a complex value.
684
685
   Let us consider the addition as an example, assuming that ints are implicitly
686
   converted to floats.  We have the following rules (up to variants with changed
687
   order of operands):
688
689
       complex(a, b) + complex(c, d) = complex(a + c, b + d)
690
       float(a) + complex(b, c) = complex(a + b, c)
691
692
   Similar rules are implemented for subtraction, multiplication and division.
693
   See C11's Annex G, sections G.5.1 and G.5.2.
694
 */
695
696
#define COMPLEX_BINOP(NAME, FUNC)                           \
697
    static PyObject *                                       \
698
    complex_##NAME(PyObject *v, PyObject *w)                \
699
47.8k
    {                                                       \
700
47.8k
        Py_complex a;                                       \
701
47.8k
        errno = 0;                                          \
702
47.8k
        if (PyComplex_Check(w)) {                           \
703
12.3k
            Py_complex b = ((PyComplexObject *)w)->cval;    \
704
12.3k
            if (PyComplex_Check(v)) {                       \
705
8.76k
                a = ((PyComplexObject *)v)->cval;           \
706
8.76k
                a = _Py_c_##FUNC(a, b);                     \
707
8.76k
            }                                               \
708
12.3k
            else if (real_to_double(&v, &a.real) < 0) {     \
709
35
                return v;                                   \
710
35
            }                                               \
711
3.60k
            else {                                          \
712
3.57k
                a = _Py_rc_##FUNC(a.real, b);               \
713
3.57k
            }                                               \
714
12.3k
        }                                                   \
715
47.8k
        else if (!PyComplex_Check(v)) {                     \
716
0
            Py_RETURN_NOTIMPLEMENTED;                       \
717
0
        }                                                   \
718
35.4k
        else {                                              \
719
35.4k
            a = ((PyComplexObject *)v)->cval;               \
720
35.4k
            double b;                                       \
721
35.4k
            if (real_to_double(&w, &b) < 0) {               \
722
397
                return w;                                   \
723
397
            }                                               \
724
35.4k
            a = _Py_cr_##FUNC(a, b);                        \
725
35.0k
        }                                                   \
726
47.8k
        if (errno == EDOM) {                                \
727
1.00k
            PyErr_SetString(PyExc_ZeroDivisionError,        \
728
1.00k
                            "division by zero");            \
729
1.00k
            return NULL;                                    \
730
1.00k
        }                                                   \
731
47.4k
        return PyComplex_FromCComplex(a);                   \
732
47.4k
   }
733
734
20.7k
COMPLEX_BINOP(add, sum)
735
9.11k
COMPLEX_BINOP(mul, prod)
736
12.4k
COMPLEX_BINOP(sub, diff)
737
5.55k
COMPLEX_BINOP(div, quot)
738
739
static PyObject *
740
complex_pow(PyObject *v, PyObject *w, PyObject *z)
741
16.9k
{
742
16.9k
    Py_complex p;
743
16.9k
    Py_complex a, b;
744
16.9k
    TO_COMPLEX(v, a);
745
16.9k
    TO_COMPLEX(w, b);
746
747
16.8k
    if (z != Py_None) {
748
0
        PyErr_SetString(PyExc_ValueError, "complex modulo");
749
0
        return NULL;
750
0
    }
751
16.8k
    errno = 0;
752
    // Check whether the exponent has a small integer value, and if so use
753
    // a faster and more accurate algorithm.
754
16.8k
    if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
755
5.64k
        p = c_powi(a, (long)b.real);
756
5.64k
        _Py_ADJUST_ERANGE2(p.real, p.imag);
757
5.64k
    }
758
11.1k
    else {
759
11.1k
        p = _Py_c_pow(a, b);
760
11.1k
    }
761
762
16.8k
    if (errno == EDOM) {
763
644
        PyErr_SetString(PyExc_ZeroDivisionError,
764
644
                        "zero to a negative or complex power");
765
644
        return NULL;
766
644
    }
767
16.1k
    else if (errno == ERANGE) {
768
1.46k
        PyErr_SetString(PyExc_OverflowError,
769
1.46k
                        "complex exponentiation");
770
1.46k
        return NULL;
771
1.46k
    }
772
14.7k
    return PyComplex_FromCComplex(p);
773
16.8k
}
774
775
static PyObject *
776
complex_neg(PyObject *op)
777
2.64k
{
778
2.64k
    PyComplexObject *v = _PyComplexObject_CAST(op);
779
2.64k
    Py_complex neg;
780
2.64k
    neg.real = -v->cval.real;
781
2.64k
    neg.imag = -v->cval.imag;
782
2.64k
    return PyComplex_FromCComplex(neg);
783
2.64k
}
784
785
static PyObject *
786
complex_pos(PyObject *op)
787
1.15k
{
788
1.15k
    PyComplexObject *v = _PyComplexObject_CAST(op);
789
1.15k
    if (PyComplex_CheckExact(v)) {
790
1.15k
        return Py_NewRef(v);
791
1.15k
    }
792
0
    return PyComplex_FromCComplex(v->cval);
793
1.15k
}
794
795
static PyObject *
796
complex_abs(PyObject *op)
797
0
{
798
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
799
0
    double result = _Py_c_abs(v->cval);
800
0
    if (errno == ERANGE) {
801
0
        PyErr_SetString(PyExc_OverflowError,
802
0
                        "absolute value too large");
803
0
        return NULL;
804
0
    }
805
0
    return PyFloat_FromDouble(result);
806
0
}
807
808
static int
809
complex_bool(PyObject *op)
810
291
{
811
291
    PyComplexObject *v = _PyComplexObject_CAST(op);
812
291
    return v->cval.real != 0.0 || v->cval.imag != 0.0;
813
291
}
814
815
static PyObject *
816
complex_richcompare(PyObject *v, PyObject *w, int op)
817
55.8k
{
818
55.8k
    PyObject *res;
819
55.8k
    Py_complex i;
820
55.8k
    int equal;
821
822
55.8k
    if (op != Py_EQ && op != Py_NE) {
823
0
        goto Unimplemented;
824
0
    }
825
826
55.8k
    assert(PyComplex_Check(v));
827
55.8k
    TO_COMPLEX(v, i);
828
829
55.8k
    if (PyLong_Check(w)) {
830
        /* Check for 0.0 imaginary part first to avoid the rich
831
         * comparison when possible.
832
         */
833
1
        if (i.imag == 0.0) {
834
1
            PyObject *j, *sub_res;
835
1
            j = PyFloat_FromDouble(i.real);
836
1
            if (j == NULL)
837
0
                return NULL;
838
839
1
            sub_res = PyObject_RichCompare(j, w, op);
840
1
            Py_DECREF(j);
841
1
            return sub_res;
842
1
        }
843
0
        else {
844
0
            equal = 0;
845
0
        }
846
1
    }
847
55.8k
    else if (PyFloat_Check(w)) {
848
0
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
849
0
    }
850
55.8k
    else if (PyComplex_Check(w)) {
851
55.8k
        Py_complex j;
852
853
55.8k
        TO_COMPLEX(w, j);
854
55.8k
        equal = (i.real == j.real && i.imag == j.imag);
855
55.8k
    }
856
0
    else {
857
0
        goto Unimplemented;
858
0
    }
859
860
55.8k
    if (equal == (op == Py_EQ))
861
55.6k
         res = Py_True;
862
169
    else
863
169
         res = Py_False;
864
865
55.8k
    return Py_NewRef(res);
866
867
0
Unimplemented:
868
0
    Py_RETURN_NOTIMPLEMENTED;
869
55.8k
}
870
871
/*[clinic input]
872
@permit_long_summary
873
complex.conjugate
874
875
Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
876
[clinic start generated code]*/
877
878
static PyObject *
879
complex_conjugate_impl(PyComplexObject *self)
880
/*[clinic end generated code: output=5059ef162edfc68e input=71b8ab003e1cec95]*/
881
0
{
882
0
    Py_complex c = self->cval;
883
0
    c.imag = -c.imag;
884
0
    return PyComplex_FromCComplex(c);
885
0
}
886
887
/*[clinic input]
888
complex.__getnewargs__
889
890
[clinic start generated code]*/
891
892
static PyObject *
893
complex___getnewargs___impl(PyComplexObject *self)
894
/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
895
0
{
896
0
    Py_complex c = self->cval;
897
0
    return Py_BuildValue("(dd)", c.real, c.imag);
898
0
}
899
900
901
/*[clinic input]
902
complex.__format__
903
904
    format_spec: unicode
905
    /
906
907
Convert to a string according to format_spec.
908
[clinic start generated code]*/
909
910
static PyObject *
911
complex___format___impl(PyComplexObject *self, PyObject *format_spec)
912
/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
913
0
{
914
0
    _PyUnicodeWriter writer;
915
0
    int ret;
916
0
    _PyUnicodeWriter_Init(&writer);
917
0
    ret = _PyComplex_FormatAdvancedWriter(
918
0
        &writer,
919
0
        (PyObject *)self,
920
0
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
921
0
    if (ret == -1) {
922
0
        _PyUnicodeWriter_Dealloc(&writer);
923
0
        return NULL;
924
0
    }
925
0
    return _PyUnicodeWriter_Finish(&writer);
926
0
}
927
928
/*[clinic input]
929
complex.__complex__
930
931
Convert this value to exact type complex.
932
[clinic start generated code]*/
933
934
static PyObject *
935
complex___complex___impl(PyComplexObject *self)
936
/*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
937
0
{
938
0
    if (PyComplex_CheckExact(self)) {
939
0
        return Py_NewRef(self);
940
0
    }
941
0
    else {
942
0
        return PyComplex_FromCComplex(self->cval);
943
0
    }
944
0
}
945
946
947
static PyObject *
948
complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
949
0
{
950
0
    double x=0.0, y=0.0, z;
951
0
    int got_bracket=0;
952
0
    const char *start;
953
0
    char *end;
954
955
    /* position on first nonblank */
956
0
    start = s;
957
0
    while (Py_ISSPACE(*s))
958
0
        s++;
959
0
    if (*s == '(') {
960
        /* Skip over possible bracket from repr(). */
961
0
        got_bracket = 1;
962
0
        s++;
963
0
        while (Py_ISSPACE(*s))
964
0
            s++;
965
0
    }
966
967
    /* a valid complex string usually takes one of the three forms:
968
969
         <float>                  - real part only
970
         <float>j                 - imaginary part only
971
         <float><signed-float>j   - real and imaginary parts
972
973
       where <float> represents any numeric string that's accepted by the
974
       float constructor (including 'nan', 'inf', 'infinity', etc.), and
975
       <signed-float> is any string of the form <float> whose first
976
       character is '+' or '-'.
977
978
       For backwards compatibility, the extra forms
979
980
         <float><sign>j
981
         <sign>j
982
         j
983
984
       are also accepted, though support for these forms may be removed from
985
       a future version of Python.
986
    */
987
988
    /* first look for forms starting with <float> */
989
0
    z = PyOS_string_to_double(s, &end, NULL);
990
0
    if (z == -1.0 && PyErr_Occurred()) {
991
0
        if (PyErr_ExceptionMatches(PyExc_ValueError))
992
0
            PyErr_Clear();
993
0
        else
994
0
            return NULL;
995
0
    }
996
0
    if (end != s) {
997
        /* all 4 forms starting with <float> land here */
998
0
        s = end;
999
0
        if (*s == '+' || *s == '-') {
1000
            /* <float><signed-float>j | <float><sign>j */
1001
0
            x = z;
1002
0
            y = PyOS_string_to_double(s, &end, NULL);
1003
0
            if (y == -1.0 && PyErr_Occurred()) {
1004
0
                if (PyErr_ExceptionMatches(PyExc_ValueError))
1005
0
                    PyErr_Clear();
1006
0
                else
1007
0
                    return NULL;
1008
0
            }
1009
0
            if (end != s)
1010
                /* <float><signed-float>j */
1011
0
                s = end;
1012
0
            else {
1013
                /* <float><sign>j */
1014
0
                y = *s == '+' ? 1.0 : -1.0;
1015
0
                s++;
1016
0
            }
1017
0
            if (!(*s == 'j' || *s == 'J'))
1018
0
                goto parse_error;
1019
0
            s++;
1020
0
        }
1021
0
        else if (*s == 'j' || *s == 'J') {
1022
            /* <float>j */
1023
0
            s++;
1024
0
            y = z;
1025
0
        }
1026
0
        else
1027
            /* <float> */
1028
0
            x = z;
1029
0
    }
1030
0
    else {
1031
        /* not starting with <float>; must be <sign>j or j */
1032
0
        if (*s == '+' || *s == '-') {
1033
            /* <sign>j */
1034
0
            y = *s == '+' ? 1.0 : -1.0;
1035
0
            s++;
1036
0
        }
1037
0
        else
1038
            /* j */
1039
0
            y = 1.0;
1040
0
        if (!(*s == 'j' || *s == 'J'))
1041
0
            goto parse_error;
1042
0
        s++;
1043
0
    }
1044
1045
    /* trailing whitespace and closing bracket */
1046
0
    while (Py_ISSPACE(*s))
1047
0
        s++;
1048
0
    if (got_bracket) {
1049
        /* if there was an opening parenthesis, then the corresponding
1050
           closing parenthesis should be right here */
1051
0
        if (*s != ')')
1052
0
            goto parse_error;
1053
0
        s++;
1054
0
        while (Py_ISSPACE(*s))
1055
0
            s++;
1056
0
    }
1057
1058
    /* we should now be at the end of the string */
1059
0
    if (s-start != len)
1060
0
        goto parse_error;
1061
1062
0
    return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
1063
1064
0
  parse_error:
1065
0
    PyErr_SetString(PyExc_ValueError,
1066
0
                    "complex() arg is a malformed string");
1067
0
    return NULL;
1068
0
}
1069
1070
static PyObject *
1071
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
1072
0
{
1073
0
    const char *s;
1074
0
    PyObject *s_buffer = NULL, *result = NULL;
1075
0
    Py_ssize_t len;
1076
1077
0
    if (PyUnicode_Check(v)) {
1078
0
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
1079
0
        if (s_buffer == NULL) {
1080
0
            return NULL;
1081
0
        }
1082
0
        assert(PyUnicode_IS_ASCII(s_buffer));
1083
        /* Simply get a pointer to existing ASCII characters. */
1084
0
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
1085
0
        assert(s != NULL);
1086
0
    }
1087
0
    else {
1088
0
        PyErr_Format(PyExc_TypeError,
1089
0
            "complex() argument must be a string or a number, not %T",
1090
0
            v);
1091
0
        return NULL;
1092
0
    }
1093
1094
0
    result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
1095
0
                                                   complex_from_string_inner);
1096
0
    Py_DECREF(s_buffer);
1097
0
    return result;
1098
0
}
1099
1100
/* The constructor should only accept a string as a positional argument,
1101
 * not as by the 'real' keyword.  But Argument Clinic does not allow
1102
 * to distinguish between argument passed positionally and by keyword.
1103
 * So the constructor must be split into two parts: actual_complex_new()
1104
 * handles the case of no arguments and one positional argument, and calls
1105
 * complex_new(), implemented with Argument Clinic, to handle the remaining
1106
 * cases: 'real' and 'imag' arguments.  This separation is well suited
1107
 * for different constructor roles: converting a string or number to a complex
1108
 * number and constructing a complex number from real and imaginary parts.
1109
 */
1110
static PyObject *
1111
actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1112
0
{
1113
0
    PyObject *res = NULL;
1114
0
    PyNumberMethods *nbr;
1115
1116
0
    if (PyTuple_GET_SIZE(args) > 1 || (kwargs != NULL && PyDict_GET_SIZE(kwargs))) {
1117
0
        return complex_new(type, args, kwargs);
1118
0
    }
1119
0
    if (!PyTuple_GET_SIZE(args)) {
1120
0
        return complex_subtype_from_doubles(type, 0, 0);
1121
0
    }
1122
1123
0
    PyObject *arg = PyTuple_GET_ITEM(args, 0);
1124
    /* Special-case for a single argument when type(arg) is complex. */
1125
0
    if (PyComplex_CheckExact(arg) && type == &PyComplex_Type) {
1126
        /* Note that we can't know whether it's safe to return
1127
           a complex *subclass* instance as-is, hence the restriction
1128
           to exact complexes here.  If either the input or the
1129
           output is a complex subclass, it will be handled below
1130
           as a non-orthogonal vector.  */
1131
0
        return Py_NewRef(arg);
1132
0
    }
1133
0
    if (PyUnicode_Check(arg)) {
1134
0
        return complex_subtype_from_string(type, arg);
1135
0
    }
1136
0
    PyObject *tmp = try_complex_special_method(arg);
1137
0
    if (tmp) {
1138
0
        Py_complex c = ((PyComplexObject*)tmp)->cval;
1139
0
        res = complex_subtype_from_doubles(type, c.real, c.imag);
1140
0
        Py_DECREF(tmp);
1141
0
    }
1142
0
    else if (PyErr_Occurred()) {
1143
0
        return NULL;
1144
0
    }
1145
0
    else if (PyComplex_Check(arg)) {
1146
        /* Note that if arg is of a complex subtype, we're only
1147
           retaining its real & imag parts here, and the return
1148
           value is (properly) of the builtin complex type. */
1149
0
        Py_complex c = ((PyComplexObject*)arg)->cval;
1150
0
        res = complex_subtype_from_doubles(type, c.real, c.imag);
1151
0
    }
1152
0
    else if ((nbr = Py_TYPE(arg)->tp_as_number) != NULL &&
1153
0
             (nbr->nb_float != NULL || nbr->nb_index != NULL))
1154
0
    {
1155
        /* The argument really is entirely real, and contributes
1156
           nothing in the imaginary direction.
1157
           Just treat it as a double. */
1158
0
        double r = PyFloat_AsDouble(arg);
1159
0
        if (r != -1.0 || !PyErr_Occurred()) {
1160
0
            res = complex_subtype_from_doubles(type, r, 0);
1161
0
        }
1162
0
    }
1163
0
    else {
1164
0
        PyErr_Format(PyExc_TypeError,
1165
0
                     "complex() argument must be a string or a number, not %T",
1166
0
                     arg);
1167
0
    }
1168
0
    return res;
1169
0
}
1170
1171
/*[clinic input]
1172
@classmethod
1173
complex.__new__ as complex_new
1174
    real as r: object(c_default="NULL") = 0
1175
    imag as i: object(c_default="NULL") = 0
1176
1177
Create a complex number from a string or numbers.
1178
1179
If a string is given, parse it as a complex number.
1180
If a single number is given, convert it to a complex number.
1181
If the 'real' or 'imag' arguments are given, create a complex number
1182
with the specified real and imaginary components.
1183
[clinic start generated code]*/
1184
1185
static PyObject *
1186
complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
1187
/*[clinic end generated code: output=b6c7dd577b537dc1 input=ff4268dc540958a4]*/
1188
0
{
1189
0
    PyObject *tmp;
1190
0
    PyNumberMethods *nbr, *nbi = NULL;
1191
0
    Py_complex cr, ci;
1192
0
    int own_r = 0;
1193
0
    int cr_is_complex = 0;
1194
0
    int ci_is_complex = 0;
1195
1196
0
    if (r == NULL) {
1197
0
        r = _PyLong_GetZero();
1198
0
    }
1199
0
    PyObject *orig_r = r;
1200
1201
    /* DEPRECATED: The call of try_complex_special_method() for the "real"
1202
     * part will be dropped after the end of the deprecation period. */
1203
0
    tmp = try_complex_special_method(r);
1204
0
    if (tmp) {
1205
0
        r = tmp;
1206
0
        own_r = 1;
1207
0
    }
1208
0
    else if (PyErr_Occurred()) {
1209
0
        return NULL;
1210
0
    }
1211
1212
0
    nbr = Py_TYPE(r)->tp_as_number;
1213
0
    if (nbr == NULL ||
1214
0
        (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
1215
0
    {
1216
0
        PyErr_Format(PyExc_TypeError,
1217
0
                     "complex() argument 'real' must be a real number, not %T",
1218
0
                     r);
1219
0
        if (own_r) {
1220
0
            Py_DECREF(r);
1221
0
        }
1222
0
        return NULL;
1223
0
    }
1224
0
    if (i != NULL) {
1225
0
        nbi = Py_TYPE(i)->tp_as_number;
1226
0
        if (nbi == NULL ||
1227
0
            (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
1228
0
        {
1229
0
            PyErr_Format(PyExc_TypeError,
1230
0
                         "complex() argument 'imag' must be a real number, not %T",
1231
0
                         i);
1232
0
            if (own_r) {
1233
0
                Py_DECREF(r);
1234
0
            }
1235
0
            return NULL;
1236
0
        }
1237
0
    }
1238
1239
    /* If we get this far, then the "real" and "imag" parts should
1240
       both be treated as numbers, and the constructor should return a
1241
       complex number equal to (real + imag*1j).
1242
1243
       The following is DEPRECATED:
1244
       Note that we do NOT assume the input to already be in canonical
1245
       form; the "real" and "imag" parts might themselves be complex
1246
       numbers, which slightly complicates the code below. */
1247
0
    if (PyComplex_Check(r)) {
1248
        /* Note that if r is of a complex subtype, we're only
1249
           retaining its real & imag parts here, and the return
1250
           value is (properly) of the builtin complex type. */
1251
0
        cr = ((PyComplexObject*)r)->cval;
1252
0
        cr_is_complex = 1;
1253
0
        if (own_r) {
1254
            /* r was a newly created complex number, rather
1255
               than the original "real" argument. */
1256
0
            Py_DECREF(r);
1257
0
        }
1258
0
        nbr = Py_TYPE(orig_r)->tp_as_number;
1259
0
        if (nbr == NULL ||
1260
0
            (nbr->nb_float == NULL && nbr->nb_index == NULL))
1261
0
        {
1262
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1263
0
                    "complex() argument 'real' must be a real number, not %T",
1264
0
                    orig_r)) {
1265
0
                return NULL;
1266
0
            }
1267
0
        }
1268
0
    }
1269
0
    else {
1270
        /* The "real" part really is entirely real, and contributes
1271
           nothing in the imaginary direction.
1272
           Just treat it as a double. */
1273
0
        tmp = PyNumber_Float(r);
1274
0
        assert(!own_r);
1275
0
        if (tmp == NULL)
1276
0
            return NULL;
1277
0
        assert(PyFloat_Check(tmp));
1278
0
        cr.real = PyFloat_AsDouble(tmp);
1279
0
        cr.imag = 0.0;
1280
0
        Py_DECREF(tmp);
1281
0
    }
1282
0
    if (i == NULL) {
1283
0
        ci.real = cr.imag;
1284
0
    }
1285
0
    else if (PyComplex_Check(i)) {
1286
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1287
0
                "complex() argument 'imag' must be a real number, not %T",
1288
0
                i)) {
1289
0
            return NULL;
1290
0
        }
1291
0
        ci = ((PyComplexObject*)i)->cval;
1292
0
        ci_is_complex = 1;
1293
0
    } else {
1294
        /* The "imag" part really is entirely imaginary, and
1295
           contributes nothing in the real direction.
1296
           Just treat it as a double. */
1297
0
        tmp = PyNumber_Float(i);
1298
0
        if (tmp == NULL)
1299
0
            return NULL;
1300
0
        ci.real = PyFloat_AsDouble(tmp);
1301
0
        Py_DECREF(tmp);
1302
0
    }
1303
    /*  If the input was in canonical form, then the "real" and "imag"
1304
        parts are real numbers, so that ci.imag and cr.imag are zero.
1305
        We need this correction in case they were not real numbers. */
1306
1307
0
    if (ci_is_complex) {
1308
0
        cr.real -= ci.imag;
1309
0
    }
1310
0
    if (cr_is_complex && i != NULL) {
1311
0
        ci.real += cr.imag;
1312
0
    }
1313
0
    return complex_subtype_from_doubles(type, cr.real, ci.real);
1314
0
}
1315
1316
/*[clinic input]
1317
@classmethod
1318
complex.from_number
1319
1320
    number: object
1321
    /
1322
1323
Convert number to a complex floating-point number.
1324
[clinic start generated code]*/
1325
1326
static PyObject *
1327
complex_from_number_impl(PyTypeObject *type, PyObject *number)
1328
/*[clinic end generated code: output=7248bb593e1871e1 input=3f8bdd3a2bc3facd]*/
1329
0
{
1330
0
    if (PyComplex_CheckExact(number) && type == &PyComplex_Type) {
1331
0
        Py_INCREF(number);
1332
0
        return number;
1333
0
    }
1334
0
    Py_complex cv = PyComplex_AsCComplex(number);
1335
0
    if (cv.real == -1.0 && PyErr_Occurred()) {
1336
0
        return NULL;
1337
0
    }
1338
0
    PyObject *result = PyComplex_FromCComplex(cv);
1339
0
    if (type != &PyComplex_Type && result != NULL) {
1340
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1341
0
    }
1342
0
    return result;
1343
0
}
1344
1345
static PyMethodDef complex_methods[] = {
1346
    COMPLEX_FROM_NUMBER_METHODDEF
1347
    COMPLEX_CONJUGATE_METHODDEF
1348
    COMPLEX___COMPLEX___METHODDEF
1349
    COMPLEX___GETNEWARGS___METHODDEF
1350
    COMPLEX___FORMAT___METHODDEF
1351
    {NULL,              NULL}           /* sentinel */
1352
};
1353
1354
static PyMemberDef complex_members[] = {
1355
    {"real", Py_T_DOUBLE, offsetof(PyComplexObject, cval.real), Py_READONLY,
1356
     "the real part of a complex number"},
1357
    {"imag", Py_T_DOUBLE, offsetof(PyComplexObject, cval.imag), Py_READONLY,
1358
     "the imaginary part of a complex number"},
1359
    {0},
1360
};
1361
1362
static PyNumberMethods complex_as_number = {
1363
    complex_add,                                /* nb_add */
1364
    complex_sub,                                /* nb_subtract */
1365
    complex_mul,                                /* nb_multiply */
1366
    0,                                          /* nb_remainder */
1367
    0,                                          /* nb_divmod */
1368
    complex_pow,                                /* nb_power */
1369
    complex_neg,                                /* nb_negative */
1370
    complex_pos,                                /* nb_positive */
1371
    complex_abs,                                /* nb_absolute */
1372
    complex_bool,                               /* nb_bool */
1373
    0,                                          /* nb_invert */
1374
    0,                                          /* nb_lshift */
1375
    0,                                          /* nb_rshift */
1376
    0,                                          /* nb_and */
1377
    0,                                          /* nb_xor */
1378
    0,                                          /* nb_or */
1379
    0,                                          /* nb_int */
1380
    0,                                          /* nb_reserved */
1381
    0,                                          /* nb_float */
1382
    0,                                          /* nb_inplace_add */
1383
    0,                                          /* nb_inplace_subtract */
1384
    0,                                          /* nb_inplace_multiply*/
1385
    0,                                          /* nb_inplace_remainder */
1386
    0,                                          /* nb_inplace_power */
1387
    0,                                          /* nb_inplace_lshift */
1388
    0,                                          /* nb_inplace_rshift */
1389
    0,                                          /* nb_inplace_and */
1390
    0,                                          /* nb_inplace_xor */
1391
    0,                                          /* nb_inplace_or */
1392
    0,                                          /* nb_floor_divide */
1393
    complex_div,                                /* nb_true_divide */
1394
    0,                                          /* nb_inplace_floor_divide */
1395
    0,                                          /* nb_inplace_true_divide */
1396
};
1397
1398
PyTypeObject PyComplex_Type = {
1399
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1400
    "complex",
1401
    sizeof(PyComplexObject),
1402
    0,
1403
    complex_dealloc,                            /* tp_dealloc */
1404
    0,                                          /* tp_vectorcall_offset */
1405
    0,                                          /* tp_getattr */
1406
    0,                                          /* tp_setattr */
1407
    0,                                          /* tp_as_async */
1408
    complex_repr,                               /* tp_repr */
1409
    &complex_as_number,                         /* tp_as_number */
1410
    0,                                          /* tp_as_sequence */
1411
    0,                                          /* tp_as_mapping */
1412
    complex_hash,                               /* tp_hash */
1413
    0,                                          /* tp_call */
1414
    0,                                          /* tp_str */
1415
    PyObject_GenericGetAttr,                    /* tp_getattro */
1416
    0,                                          /* tp_setattro */
1417
    0,                                          /* tp_as_buffer */
1418
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
1419
    complex_new__doc__,                         /* tp_doc */
1420
    0,                                          /* tp_traverse */
1421
    0,                                          /* tp_clear */
1422
    complex_richcompare,                        /* tp_richcompare */
1423
    0,                                          /* tp_weaklistoffset */
1424
    0,                                          /* tp_iter */
1425
    0,                                          /* tp_iternext */
1426
    complex_methods,                            /* tp_methods */
1427
    complex_members,                            /* tp_members */
1428
    0,                                          /* tp_getset */
1429
    0,                                          /* tp_base */
1430
    0,                                          /* tp_dict */
1431
    0,                                          /* tp_descr_get */
1432
    0,                                          /* tp_descr_set */
1433
    0,                                          /* tp_dictoffset */
1434
    0,                                          /* tp_init */
1435
    PyType_GenericAlloc,                        /* tp_alloc */
1436
    actual_complex_new,                         /* tp_new */
1437
    PyObject_Free,                              /* tp_free */
1438
    .tp_version_tag = _Py_TYPE_VERSION_COMPLEX,
1439
};