Coverage Report

Created: 2025-12-14 07:07

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
292k
#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
1.03k
{
34
1.03k
    Py_complex r;
35
1.03k
    r.real = a.real + b.real;
36
1.03k
    r.imag = a.imag + b.imag;
37
1.03k
    return r;
38
1.03k
}
39
40
Py_complex
41
_Py_cr_sum(Py_complex a, double b)
42
4.91k
{
43
4.91k
    Py_complex r = a;
44
4.91k
    r.real += b;
45
4.91k
    return r;
46
4.91k
}
47
48
static inline Py_complex
49
_Py_rc_sum(double a, Py_complex b)
50
455
{
51
455
    return _Py_cr_sum(b, a);
52
455
}
53
54
Py_complex
55
_Py_c_diff(Py_complex a, Py_complex b)
56
1.50k
{
57
1.50k
    Py_complex r;
58
1.50k
    r.real = a.real - b.real;
59
1.50k
    r.imag = a.imag - b.imag;
60
1.50k
    return r;
61
1.50k
}
62
63
Py_complex
64
_Py_cr_diff(Py_complex a, double b)
65
3.38k
{
66
3.38k
    Py_complex r = a;
67
3.38k
    r.real -= b;
68
3.38k
    return r;
69
3.38k
}
70
71
Py_complex
72
_Py_rc_diff(double a, Py_complex b)
73
1.17k
{
74
1.17k
    Py_complex r;
75
1.17k
    r.real = a - b.real;
76
1.17k
    r.imag = -b.imag;
77
1.17k
    return r;
78
1.17k
}
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
45.0k
{
92
45.0k
    double a = z.real, b = z.imag, c = w.real, d = w.imag;
93
45.0k
    double ac = a*c, bd = b*d, ad = a*d, bc = b*c;
94
45.0k
    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
45.0k
    if (isnan(r.real) && isnan(r.imag)) {
99
5.68k
        int recalc = 0;
100
101
5.68k
        if (isinf(a) || isinf(b)) {  /* z is infinite */
102
            /* "Box" the infinity and change nans in the other factor to 0 */
103
3.60k
            a = copysign(isinf(a) ? 1.0 : 0.0, a);
104
3.60k
            b = copysign(isinf(b) ? 1.0 : 0.0, b);
105
3.60k
            if (isnan(c)) {
106
195
                c = copysign(0.0, c);
107
195
            }
108
3.60k
            if (isnan(d)) {
109
1.49k
                d = copysign(0.0, d);
110
1.49k
            }
111
3.60k
            recalc = 1;
112
3.60k
        }
113
5.68k
        if (isinf(c) || isinf(d)) {  /* w is infinite */
114
            /* "Box" the infinity and change nans in the other factor to 0 */
115
2.25k
            c = copysign(isinf(c) ? 1.0 : 0.0, c);
116
2.25k
            d = copysign(isinf(d) ? 1.0 : 0.0, d);
117
2.25k
            if (isnan(a)) {
118
663
                a = copysign(0.0, a);
119
663
            }
120
2.25k
            if (isnan(b)) {
121
663
                b = copysign(0.0, b);
122
663
            }
123
2.25k
            recalc = 1;
124
2.25k
        }
125
5.68k
        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
5.68k
        if (recalc) {
142
4.40k
            r.real = INFINITY*(a*c - b*d);
143
4.40k
            r.imag = INFINITY*(a*d + b*c);
144
4.40k
        }
145
5.68k
    }
146
147
45.0k
    return r;
148
45.0k
}
149
150
Py_complex
151
_Py_cr_prod(Py_complex a, double b)
152
5.43k
{
153
5.43k
    Py_complex r = a;
154
5.43k
    r.real *= b;
155
5.43k
    r.imag *= b;
156
5.43k
    return r;
157
5.43k
}
158
159
static inline Py_complex
160
_Py_rc_prod(double a, Py_complex b)
161
1.55k
{
162
1.55k
    return _Py_cr_prod(b, a);
163
1.55k
}
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
11.5k
{
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
11.5k
     Py_complex r;      /* the result */
195
11.5k
     const double abs_breal = b.real < 0 ? -b.real : b.real;
196
11.5k
     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
197
198
11.5k
    if (abs_breal >= abs_bimag) {
199
        /* divide tops and bottom by b.real */
200
4.95k
        if (abs_breal == 0.0) {
201
721
            errno = EDOM;
202
721
            r.real = r.imag = 0.0;
203
721
        }
204
4.23k
        else {
205
4.23k
            const double ratio = b.imag / b.real;
206
4.23k
            const double denom = b.real + b.imag * ratio;
207
4.23k
            r.real = (a.real + a.imag * ratio) / denom;
208
4.23k
            r.imag = (a.imag - a.real * ratio) / denom;
209
4.23k
        }
210
4.95k
    }
211
6.61k
    else if (abs_bimag >= abs_breal) {
212
        /* divide tops and bottom by b.imag */
213
6.12k
        const double ratio = b.real / b.imag;
214
6.12k
        const double denom = b.real * ratio + b.imag;
215
6.12k
        assert(b.imag != 0.0);
216
6.12k
        r.real = (a.real * ratio + a.imag) / denom;
217
6.12k
        r.imag = (a.imag * ratio - a.real) / denom;
218
6.12k
    }
219
493
    else {
220
        /* At least one of b.real or b.imag is a NaN */
221
493
        r.real = r.imag = Py_NAN;
222
493
    }
223
224
    /* Recover infinities and zeros that computed as nan+nanj.  See e.g.
225
       the C11, Annex G.5.2, routine _Cdivd(). */
226
11.5k
    if (isnan(r.real) && isnan(r.imag)) {
227
4.79k
        if ((isinf(a.real) || isinf(a.imag))
228
4.79k
            && isfinite(b.real) && isfinite(b.imag))
229
1.63k
        {
230
1.63k
            const double x = copysign(isinf(a.real) ? 1.0 : 0.0, a.real);
231
1.63k
            const double y = copysign(isinf(a.imag) ? 1.0 : 0.0, a.imag);
232
1.63k
            r.real = INFINITY * (x*b.real + y*b.imag);
233
1.63k
            r.imag = INFINITY * (y*b.real - x*b.imag);
234
1.63k
        }
235
3.16k
        else if ((isinf(abs_breal) || isinf(abs_bimag))
236
3.16k
                 && isfinite(a.real) && isfinite(a.imag))
237
408
        {
238
408
            const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
239
408
            const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
240
408
            r.real = 0.0 * (a.real*x + a.imag*y);
241
408
            r.imag = 0.0 * (a.imag*x - a.real*y);
242
408
        }
243
4.79k
    }
244
245
11.5k
    return r;
246
11.5k
}
247
248
Py_complex
249
_Py_cr_quot(Py_complex a, double b)
250
3.93k
{
251
3.93k
    Py_complex r = a;
252
3.93k
    if (b) {
253
3.03k
        r.real /= b;
254
3.03k
        r.imag /= b;
255
3.03k
    }
256
902
    else {
257
902
        errno = EDOM;
258
902
        r.real = r.imag = 0.0;
259
902
    }
260
3.93k
    return r;
261
3.93k
}
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
3.74k
{
267
3.74k
    Py_complex r;
268
3.74k
    const double abs_breal = b.real < 0 ? -b.real : b.real;
269
3.74k
    const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
270
271
3.74k
    if (abs_breal >= abs_bimag) {
272
1.65k
        if (abs_breal == 0.0) {
273
448
            errno = EDOM;
274
448
            r.real = r.imag = 0.0;
275
448
        }
276
1.20k
        else {
277
1.20k
            const double ratio = b.imag / b.real;
278
1.20k
            const double denom = b.real + b.imag * ratio;
279
1.20k
            r.real = a / denom;
280
1.20k
            r.imag = (-a * ratio) / denom;
281
1.20k
        }
282
1.65k
    }
283
2.09k
    else if (abs_bimag >= abs_breal) {
284
2.04k
        const double ratio = b.real / b.imag;
285
2.04k
        const double denom = b.real * ratio + b.imag;
286
2.04k
        assert(b.imag != 0.0);
287
2.04k
        r.real = (a * ratio) / denom;
288
2.04k
        r.imag = (-a) / denom;
289
2.04k
    }
290
53
    else {
291
53
        r.real = r.imag = Py_NAN;
292
53
    }
293
294
3.74k
    if (isnan(r.real) && isnan(r.imag) && isfinite(a)
295
53
        && (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
3.74k
    return r;
304
3.74k
}
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.7k
{
312
11.7k
    Py_complex r;
313
11.7k
    double vabs,len,at,phase;
314
11.7k
    if (b.real == 0. && b.imag == 0.) {
315
0
        r.real = 1.;
316
0
        r.imag = 0.;
317
0
    }
318
11.7k
    else if (a.real == 0. && a.imag == 0.) {
319
933
        if (b.imag != 0. || b.real < 0.)
320
933
            errno = EDOM;
321
933
        r.real = 0.;
322
933
        r.imag = 0.;
323
933
    }
324
10.7k
    else {
325
10.7k
        vabs = hypot(a.real,a.imag);
326
10.7k
        len = pow(vabs,b.real);
327
10.7k
        at = atan2(a.imag, a.real);
328
10.7k
        phase = at*b.real;
329
10.7k
        if (b.imag != 0.0) {
330
6.45k
            len *= exp(-at*b.imag);
331
6.45k
            phase += b.imag*log(vabs);
332
6.45k
        }
333
10.7k
        r.real = len*cos(phase);
334
10.7k
        r.imag = len*sin(phase);
335
336
10.7k
        _Py_ADJUST_ERANGE2(r.real, r.imag);
337
10.7k
    }
338
11.7k
    return r;
339
11.7k
}
340
341
static Py_complex
342
c_powu(Py_complex x, long n)
343
7.55k
{
344
7.55k
    Py_complex r, p;
345
7.55k
    long mask = 1;
346
7.55k
    r = c_1;
347
7.55k
    p = x;
348
32.9k
    while (mask > 0 && n >= mask) {
349
25.4k
        if (n & mask)
350
13.6k
            r = _Py_c_prod(r,p);
351
25.4k
        mask <<= 1;
352
25.4k
        p = _Py_c_prod(p,p);
353
25.4k
    }
354
7.55k
    return r;
355
7.55k
}
356
357
static Py_complex
358
c_powi(Py_complex x, long n)
359
7.55k
{
360
7.55k
    if (n > 0)
361
4.64k
        return c_powu(x,n);
362
2.90k
    else
363
2.90k
        return _Py_c_quot(c_1, c_powu(x,-n));
364
365
7.55k
}
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
162k
{
413
162k
    PyComplexObject *op = _Py_FREELIST_POP(PyComplexObject, complexes);
414
415
162k
    if (op == NULL) {
416
        /* Inline PyObject_New */
417
75.1k
        op = PyObject_Malloc(sizeof(PyComplexObject));
418
75.1k
        if (op == NULL) {
419
0
            return PyErr_NoMemory();
420
0
        }
421
75.1k
        _PyObject_Init((PyObject*)op, &PyComplex_Type);
422
75.1k
    }
423
162k
    op->cval = cval;
424
162k
    return (PyObject *) op;
425
162k
}
426
427
static void
428
complex_dealloc(PyObject *op)
429
162k
{
430
162k
    assert(PyComplex_Check(op));
431
162k
    if (PyComplex_CheckExact(op)) {
432
162k
        _Py_FREELIST_FREE(complexes, op, PyObject_Free);
433
162k
    }
434
0
    else {
435
0
        Py_TYPE(op)->tp_free(op);
436
0
    }
437
162k
}
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
2.69k
{
451
2.69k
    Py_complex c;
452
2.69k
    c.real = real;
453
2.69k
    c.imag = imag;
454
2.69k
    return PyComplex_FromCComplex(c);
455
2.69k
}
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
191k
{
540
191k
    Py_complex cv;
541
191k
    PyObject *newop = NULL;
542
543
191k
    assert(op);
544
    /* If op is already of type PyComplex_Type, return its value */
545
191k
    if (PyComplex_Check(op)) {
546
191k
        return ((PyComplexObject *)op)->cval;
547
191k
    }
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
8.96k
{
576
8.96k
    int precision = 0;
577
8.96k
    char format_code = 'r';
578
8.96k
    PyObject *result = NULL;
579
8.96k
    PyComplexObject *v = _PyComplexObject_CAST(op);
580
581
    /* If these are non-NULL, they'll need to be freed. */
582
8.96k
    char *pre = NULL;
583
8.96k
    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
8.96k
    const char *re = NULL;
589
8.96k
    const char *lead = "";
590
8.96k
    const char *tail = "";
591
592
8.96k
    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
8.96k
        re = "";
596
8.96k
        im = PyOS_double_to_string(v->cval.imag, format_code,
597
8.96k
                                   precision, 0, NULL);
598
8.96k
        if (!im) {
599
0
            PyErr_NoMemory();
600
0
            goto done;
601
0
        }
602
8.96k
    } 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
8.96k
    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
623
8.96k
  done:
624
8.96k
    PyMem_Free(im);
625
8.96k
    PyMem_Free(pre);
626
627
8.96k
    return result;
628
8.96k
}
629
630
static Py_hash_t
631
complex_hash(PyObject *op)
632
259k
{
633
259k
    Py_uhash_t hashreal, hashimag, combined;
634
259k
    PyComplexObject *v = _PyComplexObject_CAST(op);
635
259k
    hashreal = (Py_uhash_t)_Py_HashDouble(op, v->cval.real);
636
259k
    if (hashreal == (Py_uhash_t)-1)
637
0
        return -1;
638
259k
    hashimag = (Py_uhash_t)_Py_HashDouble(op, v->cval.imag);
639
259k
    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
259k
    combined = hashreal + PyHASH_IMAG * hashimag;
648
259k
    if (combined == (Py_uhash_t)-1)
649
0
        combined = (Py_uhash_t)-2;
650
259k
    return (Py_hash_t)combined;
651
259k
}
652
653
/* This macro may return! */
654
#define TO_COMPLEX(obj, c)                      \
655
192k
    if (PyComplex_Check(obj))                   \
656
192k
        c = ((PyComplexObject *)(obj))->cval;   \
657
192k
    else if (real_to_complex(&(obj), &(c)) < 0) \
658
13.5k
        return (obj)
659
660
static int
661
real_to_double(PyObject **pobj, double *dbl)
662
38.6k
{
663
38.6k
    PyObject *obj = *pobj;
664
665
38.6k
    if (PyFloat_Check(obj)) {
666
7.39k
        *dbl = PyFloat_AS_DOUBLE(obj);
667
7.39k
    }
668
31.2k
    else if (_Py_convert_int_to_double(pobj, dbl) < 0) {
669
2.99k
        return -1;
670
2.99k
    }
671
35.6k
    return 0;
672
38.6k
}
673
674
static int
675
real_to_complex(PyObject **pobj, Py_complex *pc)
676
13.5k
{
677
13.5k
    pc->imag = 0.0;
678
13.5k
    return real_to_double(pobj, &(pc->real));
679
13.5k
}
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
42.3k
    {                                                       \
700
42.3k
        Py_complex a;                                       \
701
42.3k
        errno = 0;                                          \
702
42.3k
        if (PyComplex_Check(w)) {                           \
703
25.8k
            Py_complex b = ((PyComplexObject *)w)->cval;    \
704
25.8k
            if (PyComplex_Check(v)) {                       \
705
17.1k
                a = ((PyComplexObject *)v)->cval;           \
706
17.1k
                a = _Py_c_##FUNC(a, b);                     \
707
17.1k
            }                                               \
708
25.8k
            else if (real_to_double(&v, &a.real) < 0) {     \
709
1.71k
                return v;                                   \
710
1.71k
            }                                               \
711
8.64k
            else {                                          \
712
6.93k
                a = _Py_rc_##FUNC(a.real, b);               \
713
6.93k
            }                                               \
714
25.8k
        }                                                   \
715
42.3k
        else if (!PyComplex_Check(v)) {                     \
716
0
            Py_RETURN_NOTIMPLEMENTED;                       \
717
0
        }                                                   \
718
16.5k
        else {                                              \
719
16.5k
            a = ((PyComplexObject *)v)->cval;               \
720
16.5k
            double b;                                       \
721
16.5k
            if (real_to_double(&w, &b) < 0) {               \
722
850
                return w;                                   \
723
850
            }                                               \
724
16.5k
            a = _Py_cr_##FUNC(a, b);                        \
725
15.6k
        }                                                   \
726
42.3k
        if (errno == EDOM) {                                \
727
1.95k
            PyErr_SetString(PyExc_ZeroDivisionError,        \
728
1.95k
                            "division by zero");            \
729
1.95k
            return NULL;                                    \
730
1.95k
        }                                                   \
731
39.7k
        return PyComplex_FromCComplex(a);                   \
732
39.7k
   }
733
734
6.34k
COMPLEX_BINOP(add, sum)
735
12.1k
COMPLEX_BINOP(mul, prod)
736
7.18k
COMPLEX_BINOP(sub, diff)
737
16.6k
COMPLEX_BINOP(div, quot)
738
739
static PyObject *
740
complex_pow(PyObject *v, PyObject *w, PyObject *z)
741
19.6k
{
742
19.6k
    Py_complex p;
743
19.6k
    Py_complex a, b;
744
19.6k
    TO_COMPLEX(v, a);
745
19.6k
    TO_COMPLEX(w, b);
746
747
19.2k
    if (z != Py_None) {
748
0
        PyErr_SetString(PyExc_ValueError, "complex modulo");
749
0
        return NULL;
750
0
    }
751
19.2k
    errno = 0;
752
    // Check whether the exponent has a small integer value, and if so use
753
    // a faster and more accurate algorithm.
754
19.2k
    if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
755
7.55k
        p = c_powi(a, (long)b.real);
756
7.55k
        _Py_ADJUST_ERANGE2(p.real, p.imag);
757
7.55k
    }
758
11.7k
    else {
759
11.7k
        p = _Py_c_pow(a, b);
760
11.7k
    }
761
762
19.2k
    if (errno == EDOM) {
763
970
        PyErr_SetString(PyExc_ZeroDivisionError,
764
970
                        "zero to a negative or complex power");
765
970
        return NULL;
766
970
    }
767
18.2k
    else if (errno == ERANGE) {
768
1.41k
        PyErr_SetString(PyExc_OverflowError,
769
1.41k
                        "complex exponentiation");
770
1.41k
        return NULL;
771
1.41k
    }
772
16.8k
    return PyComplex_FromCComplex(p);
773
19.2k
}
774
775
static PyObject *
776
complex_neg(PyObject *op)
777
7.22k
{
778
7.22k
    PyComplexObject *v = _PyComplexObject_CAST(op);
779
7.22k
    Py_complex neg;
780
7.22k
    neg.real = -v->cval.real;
781
7.22k
    neg.imag = -v->cval.imag;
782
7.22k
    return PyComplex_FromCComplex(neg);
783
7.22k
}
784
785
static PyObject *
786
complex_pos(PyObject *op)
787
16.0k
{
788
16.0k
    PyComplexObject *v = _PyComplexObject_CAST(op);
789
16.0k
    if (PyComplex_CheckExact(v)) {
790
16.0k
        return Py_NewRef(v);
791
16.0k
    }
792
0
    return PyComplex_FromCComplex(v->cval);
793
16.0k
}
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
555
{
811
555
    PyComplexObject *v = _PyComplexObject_CAST(op);
812
555
    return v->cval.real != 0.0 || v->cval.imag != 0.0;
813
555
}
814
815
static PyObject *
816
complex_richcompare(PyObject *v, PyObject *w, int op)
817
76.7k
{
818
76.7k
    PyObject *res;
819
76.7k
    Py_complex i;
820
76.7k
    int equal;
821
822
76.7k
    if (op != Py_EQ && op != Py_NE) {
823
0
        goto Unimplemented;
824
0
    }
825
826
76.7k
    assert(PyComplex_Check(v));
827
76.7k
    TO_COMPLEX(v, i);
828
829
76.7k
    if (PyLong_Check(w)) {
830
        /* Check for 0.0 imaginary part first to avoid the rich
831
         * comparison when possible.
832
         */
833
115
        if (i.imag == 0.0) {
834
115
            PyObject *j, *sub_res;
835
115
            j = PyFloat_FromDouble(i.real);
836
115
            if (j == NULL)
837
0
                return NULL;
838
839
115
            sub_res = PyObject_RichCompare(j, w, op);
840
115
            Py_DECREF(j);
841
115
            return sub_res;
842
115
        }
843
0
        else {
844
0
            equal = 0;
845
0
        }
846
115
    }
847
76.5k
    else if (PyFloat_Check(w)) {
848
96
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
849
96
    }
850
76.5k
    else if (PyComplex_Check(w)) {
851
76.4k
        Py_complex j;
852
853
76.4k
        TO_COMPLEX(w, j);
854
76.4k
        equal = (i.real == j.real && i.imag == j.imag);
855
76.4k
    }
856
20
    else {
857
20
        goto Unimplemented;
858
20
    }
859
860
76.5k
    if (equal == (op == Py_EQ))
861
75.5k
         res = Py_True;
862
1.00k
    else
863
1.00k
         res = Py_False;
864
865
76.5k
    return Py_NewRef(res);
866
867
20
Unimplemented:
868
20
    Py_RETURN_NOTIMPLEMENTED;
869
76.7k
}
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
};