Coverage Report

Created: 2026-01-17 06:45

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
443k
#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
657
{
34
657
    Py_complex r;
35
657
    r.real = a.real + b.real;
36
657
    r.imag = a.imag + b.imag;
37
657
    return r;
38
657
}
39
40
Py_complex
41
_Py_cr_sum(Py_complex a, double b)
42
8.27k
{
43
8.27k
    Py_complex r = a;
44
8.27k
    r.real += b;
45
8.27k
    return r;
46
8.27k
}
47
48
static inline Py_complex
49
_Py_rc_sum(double a, Py_complex b)
50
538
{
51
538
    return _Py_cr_sum(b, a);
52
538
}
53
54
Py_complex
55
_Py_c_diff(Py_complex a, Py_complex b)
56
951
{
57
951
    Py_complex r;
58
951
    r.real = a.real - b.real;
59
951
    r.imag = a.imag - b.imag;
60
951
    return r;
61
951
}
62
63
Py_complex
64
_Py_cr_diff(Py_complex a, double b)
65
5.30k
{
66
5.30k
    Py_complex r = a;
67
5.30k
    r.real -= b;
68
5.30k
    return r;
69
5.30k
}
70
71
Py_complex
72
_Py_rc_diff(double a, Py_complex b)
73
988
{
74
988
    Py_complex r;
75
988
    r.real = a - b.real;
76
988
    r.imag = -b.imag;
77
988
    return r;
78
988
}
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
35.7k
{
92
35.7k
    double a = z.real, b = z.imag, c = w.real, d = w.imag;
93
35.7k
    double ac = a*c, bd = b*d, ad = a*d, bc = b*c;
94
35.7k
    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
35.7k
    if (isnan(r.real) && isnan(r.imag)) {
99
7.36k
        int recalc = 0;
100
101
7.36k
        if (isinf(a) || isinf(b)) {  /* z is infinite */
102
            /* "Box" the infinity and change nans in the other factor to 0 */
103
6.04k
            a = copysign(isinf(a) ? 1.0 : 0.0, a);
104
6.04k
            b = copysign(isinf(b) ? 1.0 : 0.0, b);
105
6.04k
            if (isnan(c)) {
106
46
                c = copysign(0.0, c);
107
46
            }
108
6.04k
            if (isnan(d)) {
109
4.78k
                d = copysign(0.0, d);
110
4.78k
            }
111
6.04k
            recalc = 1;
112
6.04k
        }
113
7.36k
        if (isinf(c) || isinf(d)) {  /* w is infinite */
114
            /* "Box" the infinity and change nans in the other factor to 0 */
115
5.80k
            c = copysign(isinf(c) ? 1.0 : 0.0, c);
116
5.80k
            d = copysign(isinf(d) ? 1.0 : 0.0, d);
117
5.80k
            if (isnan(a)) {
118
495
                a = copysign(0.0, a);
119
495
            }
120
5.80k
            if (isnan(b)) {
121
495
                b = copysign(0.0, b);
122
495
            }
123
5.80k
            recalc = 1;
124
5.80k
        }
125
7.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
7.36k
        if (recalc) {
142
6.75k
            r.real = INFINITY*(a*c - b*d);
143
6.75k
            r.imag = INFINITY*(a*d + b*c);
144
6.75k
        }
145
7.36k
    }
146
147
35.7k
    return r;
148
35.7k
}
149
150
Py_complex
151
_Py_cr_prod(Py_complex a, double b)
152
6.49k
{
153
6.49k
    Py_complex r = a;
154
6.49k
    r.real *= b;
155
6.49k
    r.imag *= b;
156
6.49k
    return r;
157
6.49k
}
158
159
static inline Py_complex
160
_Py_rc_prod(double a, Py_complex b)
161
1.72k
{
162
1.72k
    return _Py_cr_prod(b, a);
163
1.72k
}
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
9.03k
{
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
9.03k
     Py_complex r;      /* the result */
195
9.03k
     const double abs_breal = b.real < 0 ? -b.real : b.real;
196
9.03k
     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
197
198
9.03k
    if (abs_breal >= abs_bimag) {
199
        /* divide tops and bottom by b.real */
200
3.32k
        if (abs_breal == 0.0) {
201
797
            errno = EDOM;
202
797
            r.real = r.imag = 0.0;
203
797
        }
204
2.52k
        else {
205
2.52k
            const double ratio = b.imag / b.real;
206
2.52k
            const double denom = b.real + b.imag * ratio;
207
2.52k
            r.real = (a.real + a.imag * ratio) / denom;
208
2.52k
            r.imag = (a.imag - a.real * ratio) / denom;
209
2.52k
        }
210
3.32k
    }
211
5.71k
    else if (abs_bimag >= abs_breal) {
212
        /* divide tops and bottom by b.imag */
213
5.15k
        const double ratio = b.real / b.imag;
214
5.15k
        const double denom = b.real * ratio + b.imag;
215
5.15k
        assert(b.imag != 0.0);
216
5.15k
        r.real = (a.real * ratio + a.imag) / denom;
217
5.15k
        r.imag = (a.imag * ratio - a.real) / denom;
218
5.15k
    }
219
566
    else {
220
        /* At least one of b.real or b.imag is a NaN */
221
566
        r.real = r.imag = Py_NAN;
222
566
    }
223
224
    /* Recover infinities and zeros that computed as nan+nanj.  See e.g.
225
       the C11, Annex G.5.2, routine _Cdivd(). */
226
9.03k
    if (isnan(r.real) && isnan(r.imag)) {
227
4.62k
        if ((isinf(a.real) || isinf(a.imag))
228
4.62k
            && isfinite(b.real) && isfinite(b.imag))
229
1.41k
        {
230
1.41k
            const double x = copysign(isinf(a.real) ? 1.0 : 0.0, a.real);
231
1.41k
            const double y = copysign(isinf(a.imag) ? 1.0 : 0.0, a.imag);
232
1.41k
            r.real = INFINITY * (x*b.real + y*b.imag);
233
1.41k
            r.imag = INFINITY * (y*b.real - x*b.imag);
234
1.41k
        }
235
3.21k
        else if ((isinf(abs_breal) || isinf(abs_bimag))
236
3.21k
                 && isfinite(a.real) && isfinite(a.imag))
237
512
        {
238
512
            const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
239
512
            const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
240
512
            r.real = 0.0 * (a.real*x + a.imag*y);
241
512
            r.imag = 0.0 * (a.imag*x - a.real*y);
242
512
        }
243
4.62k
    }
244
245
9.03k
    return r;
246
9.03k
}
247
248
Py_complex
249
_Py_cr_quot(Py_complex a, double b)
250
3.73k
{
251
3.73k
    Py_complex r = a;
252
3.73k
    if (b) {
253
2.96k
        r.real /= b;
254
2.96k
        r.imag /= b;
255
2.96k
    }
256
771
    else {
257
771
        errno = EDOM;
258
771
        r.real = r.imag = 0.0;
259
771
    }
260
3.73k
    return r;
261
3.73k
}
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.56k
{
267
3.56k
    Py_complex r;
268
3.56k
    const double abs_breal = b.real < 0 ? -b.real : b.real;
269
3.56k
    const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
270
271
3.56k
    if (abs_breal >= abs_bimag) {
272
1.59k
        if (abs_breal == 0.0) {
273
767
            errno = EDOM;
274
767
            r.real = r.imag = 0.0;
275
767
        }
276
827
        else {
277
827
            const double ratio = b.imag / b.real;
278
827
            const double denom = b.real + b.imag * ratio;
279
827
            r.real = a / denom;
280
827
            r.imag = (-a * ratio) / denom;
281
827
        }
282
1.59k
    }
283
1.96k
    else if (abs_bimag >= abs_breal) {
284
1.88k
        const double ratio = b.real / b.imag;
285
1.88k
        const double denom = b.real * ratio + b.imag;
286
1.88k
        assert(b.imag != 0.0);
287
1.88k
        r.real = (a * ratio) / denom;
288
1.88k
        r.imag = (-a) / denom;
289
1.88k
    }
290
86
    else {
291
86
        r.real = r.imag = Py_NAN;
292
86
    }
293
294
3.56k
    if (isnan(r.real) && isnan(r.imag) && isfinite(a)
295
86
        && (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.56k
    return r;
304
3.56k
}
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
9.09k
{
312
9.09k
    Py_complex r;
313
9.09k
    double vabs,len,at,phase;
314
9.09k
    if (b.real == 0. && b.imag == 0.) {
315
0
        r.real = 1.;
316
0
        r.imag = 0.;
317
0
    }
318
9.09k
    else if (a.real == 0. && a.imag == 0.) {
319
904
        if (b.imag != 0. || b.real < 0.)
320
904
            errno = EDOM;
321
904
        r.real = 0.;
322
904
        r.imag = 0.;
323
904
    }
324
8.19k
    else {
325
8.19k
        vabs = hypot(a.real,a.imag);
326
8.19k
        len = pow(vabs,b.real);
327
8.19k
        at = atan2(a.imag, a.real);
328
8.19k
        phase = at*b.real;
329
8.19k
        if (b.imag != 0.0) {
330
4.74k
            len *= exp(-at*b.imag);
331
4.74k
            phase += b.imag*log(vabs);
332
4.74k
        }
333
8.19k
        r.real = len*cos(phase);
334
8.19k
        r.imag = len*sin(phase);
335
336
8.19k
        _Py_ADJUST_ERANGE2(r.real, r.imag);
337
8.19k
    }
338
9.09k
    return r;
339
9.09k
}
340
341
static Py_complex
342
c_powu(Py_complex x, long n)
343
5.12k
{
344
5.12k
    Py_complex r, p;
345
5.12k
    long mask = 1;
346
5.12k
    r = c_1;
347
5.12k
    p = x;
348
25.3k
    while (mask > 0 && n >= mask) {
349
20.1k
        if (n & mask)
350
11.1k
            r = _Py_c_prod(r,p);
351
20.1k
        mask <<= 1;
352
20.1k
        p = _Py_c_prod(p,p);
353
20.1k
    }
354
5.12k
    return r;
355
5.12k
}
356
357
static Py_complex
358
c_powi(Py_complex x, long n)
359
5.12k
{
360
5.12k
    if (n > 0)
361
3.09k
        return c_powu(x,n);
362
2.03k
    else
363
2.03k
        return _Py_c_quot(c_1, c_powu(x,-n));
364
365
5.12k
}
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
76.6k
        op = PyObject_Malloc(sizeof(PyComplexObject));
418
76.6k
        if (op == NULL) {
419
0
            return PyErr_NoMemory();
420
0
        }
421
76.6k
        _PyObject_Init((PyObject*)op, &PyComplex_Type);
422
76.6k
    }
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.91k
{
451
2.91k
    Py_complex c;
452
2.91k
    c.real = real;
453
2.91k
    c.imag = imag;
454
2.91k
    return PyComplex_FromCComplex(c);
455
2.91k
}
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
263k
{
540
263k
    Py_complex cv;
541
263k
    PyObject *newop = NULL;
542
543
263k
    assert(op);
544
    /* If op is already of type PyComplex_Type, return its value */
545
263k
    if (PyComplex_Check(op)) {
546
263k
        return ((PyComplexObject *)op)->cval;
547
263k
    }
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
9.64k
{
576
9.64k
    int precision = 0;
577
9.64k
    char format_code = 'r';
578
9.64k
    PyObject *result = NULL;
579
9.64k
    PyComplexObject *v = _PyComplexObject_CAST(op);
580
581
    /* If these are non-NULL, they'll need to be freed. */
582
9.64k
    char *pre = NULL;
583
9.64k
    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
9.64k
    const char *re = NULL;
589
9.64k
    const char *lead = "";
590
9.64k
    const char *tail = "";
591
592
9.64k
    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
9.64k
        re = "";
596
9.64k
        im = PyOS_double_to_string(v->cval.imag, format_code,
597
9.64k
                                   precision, 0, NULL);
598
9.64k
        if (!im) {
599
0
            PyErr_NoMemory();
600
0
            goto done;
601
0
        }
602
9.64k
    } 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
9.64k
    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
623
9.64k
  done:
624
9.64k
    PyMem_Free(im);
625
9.64k
    PyMem_Free(pre);
626
627
9.64k
    return result;
628
9.64k
}
629
630
static Py_hash_t
631
complex_hash(PyObject *op)
632
414k
{
633
414k
    Py_uhash_t hashreal, hashimag, combined;
634
414k
    PyComplexObject *v = _PyComplexObject_CAST(op);
635
414k
    hashreal = (Py_uhash_t)_Py_HashDouble(op, v->cval.real);
636
414k
    if (hashreal == (Py_uhash_t)-1)
637
0
        return -1;
638
414k
    hashimag = (Py_uhash_t)_Py_HashDouble(op, v->cval.imag);
639
414k
    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
414k
    combined = hashreal + PyHASH_IMAG * hashimag;
648
414k
    if (combined == (Py_uhash_t)-1)
649
0
        combined = (Py_uhash_t)-2;
650
414k
    return (Py_hash_t)combined;
651
414k
}
652
653
/* This macro may return! */
654
#define TO_COMPLEX(obj, c)                      \
655
170k
    if (PyComplex_Check(obj))                   \
656
170k
        c = ((PyComplexObject *)(obj))->cval;   \
657
170k
    else if (real_to_complex(&(obj), &(c)) < 0) \
658
9.87k
        return (obj)
659
660
static int
661
real_to_double(PyObject **pobj, double *dbl)
662
40.5k
{
663
40.5k
    PyObject *obj = *pobj;
664
665
40.5k
    if (PyFloat_Check(obj)) {
666
5.44k
        *dbl = PyFloat_AS_DOUBLE(obj);
667
5.44k
    }
668
35.0k
    else if (_Py_convert_int_to_double(pobj, dbl) < 0) {
669
2.49k
        return -1;
670
2.49k
    }
671
38.0k
    return 0;
672
40.5k
}
673
674
static int
675
real_to_complex(PyObject **pobj, Py_complex *pc)
676
9.87k
{
677
9.87k
    pc->imag = 0.0;
678
9.87k
    return real_to_double(pobj, &(pc->real));
679
9.87k
}
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
43.6k
    {                                                       \
700
43.6k
        Py_complex a;                                       \
701
43.6k
        errno = 0;                                          \
702
43.6k
        if (PyComplex_Check(w)) {                           \
703
21.3k
            Py_complex b = ((PyComplexObject *)w)->cval;    \
704
21.3k
            if (PyComplex_Check(v)) {                       \
705
12.9k
                a = ((PyComplexObject *)v)->cval;           \
706
12.9k
                a = _Py_c_##FUNC(a, b);                     \
707
12.9k
            }                                               \
708
21.3k
            else if (real_to_double(&v, &a.real) < 0) {     \
709
1.55k
                return v;                                   \
710
1.55k
            }                                               \
711
8.36k
            else {                                          \
712
6.80k
                a = _Py_rc_##FUNC(a.real, b);               \
713
6.80k
            }                                               \
714
21.3k
        }                                                   \
715
43.6k
        else if (!PyComplex_Check(v)) {                     \
716
0
            Py_RETURN_NOTIMPLEMENTED;                       \
717
0
        }                                                   \
718
22.3k
        else {                                              \
719
22.3k
            a = ((PyComplexObject *)v)->cval;               \
720
22.3k
            double b;                                       \
721
22.3k
            if (real_to_double(&w, &b) < 0) {               \
722
751
                return w;                                   \
723
751
            }                                               \
724
22.3k
            a = _Py_cr_##FUNC(a, b);                        \
725
21.5k
        }                                                   \
726
43.6k
        if (errno == EDOM) {                                \
727
2.16k
            PyErr_SetString(PyExc_ZeroDivisionError,        \
728
2.16k
                            "division by zero");            \
729
2.16k
            return NULL;                                    \
730
2.16k
        }                                                   \
731
41.3k
        return PyComplex_FromCComplex(a);                   \
732
41.3k
   }
733
734
9.38k
COMPLEX_BINOP(add, sum)
735
11.8k
COMPLEX_BINOP(mul, prod)
736
7.81k
COMPLEX_BINOP(sub, diff)
737
14.5k
COMPLEX_BINOP(div, quot)
738
739
static PyObject *
740
complex_pow(PyObject *v, PyObject *w, PyObject *z)
741
14.4k
{
742
14.4k
    Py_complex p;
743
14.4k
    Py_complex a, b;
744
14.4k
    TO_COMPLEX(v, a);
745
14.3k
    TO_COMPLEX(w, b);
746
747
14.2k
    if (z != Py_None) {
748
0
        PyErr_SetString(PyExc_ValueError, "complex modulo");
749
0
        return NULL;
750
0
    }
751
14.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
14.2k
    if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
755
5.12k
        p = c_powi(a, (long)b.real);
756
5.12k
        _Py_ADJUST_ERANGE2(p.real, p.imag);
757
5.12k
    }
758
9.09k
    else {
759
9.09k
        p = _Py_c_pow(a, b);
760
9.09k
    }
761
762
14.2k
    if (errno == EDOM) {
763
1.05k
        PyErr_SetString(PyExc_ZeroDivisionError,
764
1.05k
                        "zero to a negative or complex power");
765
1.05k
        return NULL;
766
1.05k
    }
767
13.1k
    else if (errno == ERANGE) {
768
2.20k
        PyErr_SetString(PyExc_OverflowError,
769
2.20k
                        "complex exponentiation");
770
2.20k
        return NULL;
771
2.20k
    }
772
10.9k
    return PyComplex_FromCComplex(p);
773
14.2k
}
774
775
static PyObject *
776
complex_neg(PyObject *op)
777
8.02k
{
778
8.02k
    PyComplexObject *v = _PyComplexObject_CAST(op);
779
8.02k
    Py_complex neg;
780
8.02k
    neg.real = -v->cval.real;
781
8.02k
    neg.imag = -v->cval.imag;
782
8.02k
    return PyComplex_FromCComplex(neg);
783
8.02k
}
784
785
static PyObject *
786
complex_pos(PyObject *op)
787
10.4k
{
788
10.4k
    PyComplexObject *v = _PyComplexObject_CAST(op);
789
10.4k
    if (PyComplex_CheckExact(v)) {
790
10.4k
        return Py_NewRef(v);
791
10.4k
    }
792
0
    return PyComplex_FromCComplex(v->cval);
793
10.4k
}
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
322
{
811
322
    PyComplexObject *v = _PyComplexObject_CAST(op);
812
322
    return v->cval.real != 0.0 || v->cval.imag != 0.0;
813
322
}
814
815
static PyObject *
816
complex_richcompare(PyObject *v, PyObject *w, int op)
817
70.7k
{
818
70.7k
    PyObject *res;
819
70.7k
    Py_complex i;
820
70.7k
    int equal;
821
822
70.7k
    if (op != Py_EQ && op != Py_NE) {
823
0
        goto Unimplemented;
824
0
    }
825
826
70.7k
    assert(PyComplex_Check(v));
827
70.7k
    TO_COMPLEX(v, i);
828
829
70.7k
    if (PyLong_Check(w)) {
830
        /* Check for 0.0 imaginary part first to avoid the rich
831
         * comparison when possible.
832
         */
833
92
        if (i.imag == 0.0) {
834
92
            PyObject *j, *sub_res;
835
92
            j = PyFloat_FromDouble(i.real);
836
92
            if (j == NULL)
837
0
                return NULL;
838
839
92
            sub_res = PyObject_RichCompare(j, w, op);
840
92
            Py_DECREF(j);
841
92
            return sub_res;
842
92
        }
843
0
        else {
844
0
            equal = 0;
845
0
        }
846
92
    }
847
70.6k
    else if (PyFloat_Check(w)) {
848
114
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
849
114
    }
850
70.5k
    else if (PyComplex_Check(w)) {
851
70.4k
        Py_complex j;
852
853
70.4k
        TO_COMPLEX(w, j);
854
70.4k
        equal = (i.real == j.real && i.imag == j.imag);
855
70.4k
    }
856
37
    else {
857
37
        goto Unimplemented;
858
37
    }
859
860
70.5k
    if (equal == (op == Py_EQ))
861
69.8k
         res = Py_True;
862
741
    else
863
741
         res = Py_False;
864
865
70.5k
    return Py_NewRef(res);
866
867
37
Unimplemented:
868
37
    Py_RETURN_NOTIMPLEMENTED;
869
70.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
};