1
2/* Complex object implementation */
3
4/* Borrows heavily from floatobject.c */
5
6/* Submitted by Jim Hugunin */
7
8#include "Python.h"
9#include "pycore_call.h"          // _PyObject_CallNoArgs()
10#include "pycore_long.h"          // _PyLong_GetZero()
11#include "pycore_object.h"        // _PyObject_Init()
12#include "pycore_pymath.h"        // _Py_ADJUST_ERANGE2()
13#include "structmember.h"         // PyMemberDef
14
15
16/*[clinic input]
17class complex "PyComplexObject *" "&PyComplex_Type"
18[clinic start generated code]*/
19/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
20
21#include "clinic/complexobject.c.h"
22
23/* elementary operations on complex numbers */
24
25static Py_complex c_1 = {1., 0.};
26
27Py_complex
28_Py_c_sum(Py_complex a, Py_complex b)
29{
30    Py_complex r;
31    r.real = a.real + b.real;
32    r.imag = a.imag + b.imag;
33    return r;
34}
35
36Py_complex
37_Py_c_diff(Py_complex a, Py_complex b)
38{
39    Py_complex r;
40    r.real = a.real - b.real;
41    r.imag = a.imag - b.imag;
42    return r;
43}
44
45Py_complex
46_Py_c_neg(Py_complex a)
47{
48    Py_complex r;
49    r.real = -a.real;
50    r.imag = -a.imag;
51    return r;
52}
53
54Py_complex
55_Py_c_prod(Py_complex a, Py_complex b)
56{
57    Py_complex r;
58    r.real = a.real*b.real - a.imag*b.imag;
59    r.imag = a.real*b.imag + a.imag*b.real;
60    return r;
61}
62
63/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
64#ifdef _M_ARM64
65#pragma optimize("", off)
66#endif
67Py_complex
68_Py_c_quot(Py_complex a, Py_complex b)
69{
70    /******************************************************************
71    This was the original algorithm.  It's grossly prone to spurious
72    overflow and underflow errors.  It also merrily divides by 0 despite
73    checking for that(!).  The code still serves a doc purpose here, as
74    the algorithm following is a simple by-cases transformation of this
75    one:
76
77    Py_complex r;
78    double d = b.real*b.real + b.imag*b.imag;
79    if (d == 0.)
80        errno = EDOM;
81    r.real = (a.real*b.real + a.imag*b.imag)/d;
82    r.imag = (a.imag*b.real - a.real*b.imag)/d;
83    return r;
84    ******************************************************************/
85
86    /* This algorithm is better, and is pretty obvious:  first divide the
87     * numerators and denominator by whichever of {b.real, b.imag} has
88     * larger magnitude.  The earliest reference I found was to CACM
89     * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
90     * University).  As usual, though, we're still ignoring all IEEE
91     * endcases.
92     */
93     Py_complex r;      /* the result */
94     const double abs_breal = b.real < 0 ? -b.real : b.real;
95     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
96
97    if (abs_breal >= abs_bimag) {
98        /* divide tops and bottom by b.real */
99        if (abs_breal == 0.0) {
100            errno = EDOM;
101            r.real = r.imag = 0.0;
102        }
103        else {
104            const double ratio = b.imag / b.real;
105            const double denom = b.real + b.imag * ratio;
106            r.real = (a.real + a.imag * ratio) / denom;
107            r.imag = (a.imag - a.real * ratio) / denom;
108        }
109    }
110    else if (abs_bimag >= abs_breal) {
111        /* divide tops and bottom by b.imag */
112        const double ratio = b.real / b.imag;
113        const double denom = b.real * ratio + b.imag;
114        assert(b.imag != 0.0);
115        r.real = (a.real * ratio + a.imag) / denom;
116        r.imag = (a.imag * ratio - a.real) / denom;
117    }
118    else {
119        /* At least one of b.real or b.imag is a NaN */
120        r.real = r.imag = Py_NAN;
121    }
122    return r;
123}
124#ifdef _M_ARM64
125#pragma optimize("", on)
126#endif
127
128Py_complex
129_Py_c_pow(Py_complex a, Py_complex b)
130{
131    Py_complex r;
132    double vabs,len,at,phase;
133    if (b.real == 0. && b.imag == 0.) {
134        r.real = 1.;
135        r.imag = 0.;
136    }
137    else if (a.real == 0. && a.imag == 0.) {
138        if (b.imag != 0. || b.real < 0.)
139            errno = EDOM;
140        r.real = 0.;
141        r.imag = 0.;
142    }
143    else {
144        vabs = hypot(a.real,a.imag);
145        len = pow(vabs,b.real);
146        at = atan2(a.imag, a.real);
147        phase = at*b.real;
148        if (b.imag != 0.0) {
149            len /= exp(at*b.imag);
150            phase += b.imag*log(vabs);
151        }
152        r.real = len*cos(phase);
153        r.imag = len*sin(phase);
154    }
155    return r;
156}
157
158static Py_complex
159c_powu(Py_complex x, long n)
160{
161    Py_complex r, p;
162    long mask = 1;
163    r = c_1;
164    p = x;
165    while (mask > 0 && n >= mask) {
166        if (n & mask)
167            r = _Py_c_prod(r,p);
168        mask <<= 1;
169        p = _Py_c_prod(p,p);
170    }
171    return r;
172}
173
174static Py_complex
175c_powi(Py_complex x, long n)
176{
177    if (n > 0)
178        return c_powu(x,n);
179    else
180        return _Py_c_quot(c_1, c_powu(x,-n));
181
182}
183
184double
185_Py_c_abs(Py_complex z)
186{
187    /* sets errno = ERANGE on overflow;  otherwise errno = 0 */
188    double result;
189
190    if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
191        /* C99 rules: if either the real or the imaginary part is an
192           infinity, return infinity, even if the other part is a
193           NaN. */
194        if (Py_IS_INFINITY(z.real)) {
195            result = fabs(z.real);
196            errno = 0;
197            return result;
198        }
199        if (Py_IS_INFINITY(z.imag)) {
200            result = fabs(z.imag);
201            errno = 0;
202            return result;
203        }
204        /* either the real or imaginary part is a NaN,
205           and neither is infinite. Result should be NaN. */
206        return Py_NAN;
207    }
208    result = hypot(z.real, z.imag);
209    if (!Py_IS_FINITE(result))
210        errno = ERANGE;
211    else
212        errno = 0;
213    return result;
214}
215
216static PyObject *
217complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
218{
219    PyObject *op;
220
221    op = type->tp_alloc(type, 0);
222    if (op != NULL)
223        ((PyComplexObject *)op)->cval = cval;
224    return op;
225}
226
227PyObject *
228PyComplex_FromCComplex(Py_complex cval)
229{
230    /* Inline PyObject_New */
231    PyComplexObject *op = PyObject_Malloc(sizeof(PyComplexObject));
232    if (op == NULL) {
233        return PyErr_NoMemory();
234    }
235    _PyObject_Init((PyObject*)op, &PyComplex_Type);
236    op->cval = cval;
237    return (PyObject *) op;
238}
239
240static PyObject *
241complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
242{
243    Py_complex c;
244    c.real = real;
245    c.imag = imag;
246    return complex_subtype_from_c_complex(type, c);
247}
248
249PyObject *
250PyComplex_FromDoubles(double real, double imag)
251{
252    Py_complex c;
253    c.real = real;
254    c.imag = imag;
255    return PyComplex_FromCComplex(c);
256}
257
258double
259PyComplex_RealAsDouble(PyObject *op)
260{
261    if (PyComplex_Check(op)) {
262        return ((PyComplexObject *)op)->cval.real;
263    }
264    else {
265        return PyFloat_AsDouble(op);
266    }
267}
268
269double
270PyComplex_ImagAsDouble(PyObject *op)
271{
272    if (PyComplex_Check(op)) {
273        return ((PyComplexObject *)op)->cval.imag;
274    }
275    else {
276        return 0.0;
277    }
278}
279
280static PyObject *
281try_complex_special_method(PyObject *op)
282{
283    PyObject *f;
284
285    f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__));
286    if (f) {
287        PyObject *res = _PyObject_CallNoArgs(f);
288        Py_DECREF(f);
289        if (!res || PyComplex_CheckExact(res)) {
290            return res;
291        }
292        if (!PyComplex_Check(res)) {
293            PyErr_Format(PyExc_TypeError,
294                "__complex__ returned non-complex (type %.200s)",
295                Py_TYPE(res)->tp_name);
296            Py_DECREF(res);
297            return NULL;
298        }
299        /* Issue #29894: warn if 'res' not of exact type complex. */
300        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
301                "__complex__ returned non-complex (type %.200s).  "
302                "The ability to return an instance of a strict subclass of complex "
303                "is deprecated, and may be removed in a future version of Python.",
304                Py_TYPE(res)->tp_name)) {
305            Py_DECREF(res);
306            return NULL;
307        }
308        return res;
309    }
310    return NULL;
311}
312
313Py_complex
314PyComplex_AsCComplex(PyObject *op)
315{
316    Py_complex cv;
317    PyObject *newop = NULL;
318
319    assert(op);
320    /* If op is already of type PyComplex_Type, return its value */
321    if (PyComplex_Check(op)) {
322        return ((PyComplexObject *)op)->cval;
323    }
324    /* If not, use op's __complex__  method, if it exists */
325
326    /* return -1 on failure */
327    cv.real = -1.;
328    cv.imag = 0.;
329
330    newop = try_complex_special_method(op);
331
332    if (newop) {
333        cv = ((PyComplexObject *)newop)->cval;
334        Py_DECREF(newop);
335        return cv;
336    }
337    else if (PyErr_Occurred()) {
338        return cv;
339    }
340    /* If neither of the above works, interpret op as a float giving the
341       real part of the result, and fill in the imaginary part as 0. */
342    else {
343        /* PyFloat_AsDouble will return -1 on failure */
344        cv.real = PyFloat_AsDouble(op);
345        return cv;
346    }
347}
348
349static PyObject *
350complex_repr(PyComplexObject *v)
351{
352    int precision = 0;
353    char format_code = 'r';
354    PyObject *result = NULL;
355
356    /* If these are non-NULL, they'll need to be freed. */
357    char *pre = NULL;
358    char *im = NULL;
359
360    /* These do not need to be freed. re is either an alias
361       for pre or a pointer to a constant.  lead and tail
362       are pointers to constants. */
363    const char *re = NULL;
364    const char *lead = "";
365    const char *tail = "";
366
367    if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
368        /* Real part is +0: just output the imaginary part and do not
369           include parens. */
370        re = "";
371        im = PyOS_double_to_string(v->cval.imag, format_code,
372                                   precision, 0, NULL);
373        if (!im) {
374            PyErr_NoMemory();
375            goto done;
376        }
377    } else {
378        /* Format imaginary part with sign, real part without. Include
379           parens in the result. */
380        pre = PyOS_double_to_string(v->cval.real, format_code,
381                                    precision, 0, NULL);
382        if (!pre) {
383            PyErr_NoMemory();
384            goto done;
385        }
386        re = pre;
387
388        im = PyOS_double_to_string(v->cval.imag, format_code,
389                                   precision, Py_DTSF_SIGN, NULL);
390        if (!im) {
391            PyErr_NoMemory();
392            goto done;
393        }
394        lead = "(";
395        tail = ")";
396    }
397    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
398  done:
399    PyMem_Free(im);
400    PyMem_Free(pre);
401
402    return result;
403}
404
405static Py_hash_t
406complex_hash(PyComplexObject *v)
407{
408    Py_uhash_t hashreal, hashimag, combined;
409    hashreal = (Py_uhash_t)_Py_HashDouble((PyObject *) v, v->cval.real);
410    if (hashreal == (Py_uhash_t)-1)
411        return -1;
412    hashimag = (Py_uhash_t)_Py_HashDouble((PyObject *)v, v->cval.imag);
413    if (hashimag == (Py_uhash_t)-1)
414        return -1;
415    /* Note:  if the imaginary part is 0, hashimag is 0 now,
416     * so the following returns hashreal unchanged.  This is
417     * important because numbers of different types that
418     * compare equal must have the same hash value, so that
419     * hash(x + 0*j) must equal hash(x).
420     */
421    combined = hashreal + _PyHASH_IMAG * hashimag;
422    if (combined == (Py_uhash_t)-1)
423        combined = (Py_uhash_t)-2;
424    return (Py_hash_t)combined;
425}
426
427/* This macro may return! */
428#define TO_COMPLEX(obj, c) \
429    if (PyComplex_Check(obj)) \
430        c = ((PyComplexObject *)(obj))->cval; \
431    else if (to_complex(&(obj), &(c)) < 0) \
432        return (obj)
433
434static int
435to_complex(PyObject **pobj, Py_complex *pc)
436{
437    PyObject *obj = *pobj;
438
439    pc->real = pc->imag = 0.0;
440    if (PyLong_Check(obj)) {
441        pc->real = PyLong_AsDouble(obj);
442        if (pc->real == -1.0 && PyErr_Occurred()) {
443            *pobj = NULL;
444            return -1;
445        }
446        return 0;
447    }
448    if (PyFloat_Check(obj)) {
449        pc->real = PyFloat_AsDouble(obj);
450        return 0;
451    }
452    Py_INCREF(Py_NotImplemented);
453    *pobj = Py_NotImplemented;
454    return -1;
455}
456
457
458static PyObject *
459complex_add(PyObject *v, PyObject *w)
460{
461    Py_complex result;
462    Py_complex a, b;
463    TO_COMPLEX(v, a);
464    TO_COMPLEX(w, b);
465    result = _Py_c_sum(a, b);
466    return PyComplex_FromCComplex(result);
467}
468
469static PyObject *
470complex_sub(PyObject *v, PyObject *w)
471{
472    Py_complex result;
473    Py_complex a, b;
474    TO_COMPLEX(v, a);
475    TO_COMPLEX(w, b);
476    result = _Py_c_diff(a, b);
477    return PyComplex_FromCComplex(result);
478}
479
480static PyObject *
481complex_mul(PyObject *v, PyObject *w)
482{
483    Py_complex result;
484    Py_complex a, b;
485    TO_COMPLEX(v, a);
486    TO_COMPLEX(w, b);
487    result = _Py_c_prod(a, b);
488    return PyComplex_FromCComplex(result);
489}
490
491static PyObject *
492complex_div(PyObject *v, PyObject *w)
493{
494    Py_complex quot;
495    Py_complex a, b;
496    TO_COMPLEX(v, a);
497    TO_COMPLEX(w, b);
498    errno = 0;
499    quot = _Py_c_quot(a, b);
500    if (errno == EDOM) {
501        PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
502        return NULL;
503    }
504    return PyComplex_FromCComplex(quot);
505}
506
507static PyObject *
508complex_pow(PyObject *v, PyObject *w, PyObject *z)
509{
510    Py_complex p;
511    Py_complex a, b;
512    TO_COMPLEX(v, a);
513    TO_COMPLEX(w, b);
514
515    if (z != Py_None) {
516        PyErr_SetString(PyExc_ValueError, "complex modulo");
517        return NULL;
518    }
519    errno = 0;
520    // Check whether the exponent has a small integer value, and if so use
521    // a faster and more accurate algorithm.
522    if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
523        p = c_powi(a, (long)b.real);
524    }
525    else {
526        p = _Py_c_pow(a, b);
527    }
528
529    _Py_ADJUST_ERANGE2(p.real, p.imag);
530    if (errno == EDOM) {
531        PyErr_SetString(PyExc_ZeroDivisionError,
532                        "0.0 to a negative or complex power");
533        return NULL;
534    }
535    else if (errno == ERANGE) {
536        PyErr_SetString(PyExc_OverflowError,
537                        "complex exponentiation");
538        return NULL;
539    }
540    return PyComplex_FromCComplex(p);
541}
542
543static PyObject *
544complex_neg(PyComplexObject *v)
545{
546    Py_complex neg;
547    neg.real = -v->cval.real;
548    neg.imag = -v->cval.imag;
549    return PyComplex_FromCComplex(neg);
550}
551
552static PyObject *
553complex_pos(PyComplexObject *v)
554{
555    if (PyComplex_CheckExact(v)) {
556        Py_INCREF(v);
557        return (PyObject *)v;
558    }
559    else
560        return PyComplex_FromCComplex(v->cval);
561}
562
563static PyObject *
564complex_abs(PyComplexObject *v)
565{
566    double result;
567
568    result = _Py_c_abs(v->cval);
569
570    if (errno == ERANGE) {
571        PyErr_SetString(PyExc_OverflowError,
572                        "absolute value too large");
573        return NULL;
574    }
575    return PyFloat_FromDouble(result);
576}
577
578static int
579complex_bool(PyComplexObject *v)
580{
581    return v->cval.real != 0.0 || v->cval.imag != 0.0;
582}
583
584static PyObject *
585complex_richcompare(PyObject *v, PyObject *w, int op)
586{
587    PyObject *res;
588    Py_complex i;
589    int equal;
590
591    if (op != Py_EQ && op != Py_NE) {
592        goto Unimplemented;
593    }
594
595    assert(PyComplex_Check(v));
596    TO_COMPLEX(v, i);
597
598    if (PyLong_Check(w)) {
599        /* Check for 0.0 imaginary part first to avoid the rich
600         * comparison when possible.
601         */
602        if (i.imag == 0.0) {
603            PyObject *j, *sub_res;
604            j = PyFloat_FromDouble(i.real);
605            if (j == NULL)
606                return NULL;
607
608            sub_res = PyObject_RichCompare(j, w, op);
609            Py_DECREF(j);
610            return sub_res;
611        }
612        else {
613            equal = 0;
614        }
615    }
616    else if (PyFloat_Check(w)) {
617        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
618    }
619    else if (PyComplex_Check(w)) {
620        Py_complex j;
621
622        TO_COMPLEX(w, j);
623        equal = (i.real == j.real && i.imag == j.imag);
624    }
625    else {
626        goto Unimplemented;
627    }
628
629    if (equal == (op == Py_EQ))
630         res = Py_True;
631    else
632         res = Py_False;
633
634    Py_INCREF(res);
635    return res;
636
637Unimplemented:
638    Py_RETURN_NOTIMPLEMENTED;
639}
640
641/*[clinic input]
642complex.conjugate
643
644Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
645[clinic start generated code]*/
646
647static PyObject *
648complex_conjugate_impl(PyComplexObject *self)
649/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
650{
651    Py_complex c = self->cval;
652    c.imag = -c.imag;
653    return PyComplex_FromCComplex(c);
654}
655
656/*[clinic input]
657complex.__getnewargs__
658
659[clinic start generated code]*/
660
661static PyObject *
662complex___getnewargs___impl(PyComplexObject *self)
663/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
664{
665    Py_complex c = self->cval;
666    return Py_BuildValue("(dd)", c.real, c.imag);
667}
668
669
670/*[clinic input]
671complex.__format__
672
673    format_spec: unicode
674    /
675
676Convert to a string according to format_spec.
677[clinic start generated code]*/
678
679static PyObject *
680complex___format___impl(PyComplexObject *self, PyObject *format_spec)
681/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
682{
683    _PyUnicodeWriter writer;
684    int ret;
685    _PyUnicodeWriter_Init(&writer);
686    ret = _PyComplex_FormatAdvancedWriter(
687        &writer,
688        (PyObject *)self,
689        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
690    if (ret == -1) {
691        _PyUnicodeWriter_Dealloc(&writer);
692        return NULL;
693    }
694    return _PyUnicodeWriter_Finish(&writer);
695}
696
697/*[clinic input]
698complex.__complex__
699
700Convert this value to exact type complex.
701[clinic start generated code]*/
702
703static PyObject *
704complex___complex___impl(PyComplexObject *self)
705/*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
706{
707    if (PyComplex_CheckExact(self)) {
708        Py_INCREF(self);
709        return (PyObject *)self;
710    }
711    else {
712        return PyComplex_FromCComplex(self->cval);
713    }
714}
715
716
717static PyMethodDef complex_methods[] = {
718    COMPLEX_CONJUGATE_METHODDEF
719    COMPLEX___COMPLEX___METHODDEF
720    COMPLEX___GETNEWARGS___METHODDEF
721    COMPLEX___FORMAT___METHODDEF
722    {NULL,              NULL}           /* sentinel */
723};
724
725static PyMemberDef complex_members[] = {
726    {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
727     "the real part of a complex number"},
728    {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
729     "the imaginary part of a complex number"},
730    {0},
731};
732
733static PyObject *
734complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
735{
736    double x=0.0, y=0.0, z;
737    int got_bracket=0;
738    const char *start;
739    char *end;
740
741    /* position on first nonblank */
742    start = s;
743    while (Py_ISSPACE(*s))
744        s++;
745    if (*s == '(') {
746        /* Skip over possible bracket from repr(). */
747        got_bracket = 1;
748        s++;
749        while (Py_ISSPACE(*s))
750            s++;
751    }
752
753    /* a valid complex string usually takes one of the three forms:
754
755         <float>                  - real part only
756         <float>j                 - imaginary part only
757         <float><signed-float>j   - real and imaginary parts
758
759       where <float> represents any numeric string that's accepted by the
760       float constructor (including 'nan', 'inf', 'infinity', etc.), and
761       <signed-float> is any string of the form <float> whose first
762       character is '+' or '-'.
763
764       For backwards compatibility, the extra forms
765
766         <float><sign>j
767         <sign>j
768         j
769
770       are also accepted, though support for these forms may be removed from
771       a future version of Python.
772    */
773
774    /* first look for forms starting with <float> */
775    z = PyOS_string_to_double(s, &end, NULL);
776    if (z == -1.0 && PyErr_Occurred()) {
777        if (PyErr_ExceptionMatches(PyExc_ValueError))
778            PyErr_Clear();
779        else
780            return NULL;
781    }
782    if (end != s) {
783        /* all 4 forms starting with <float> land here */
784        s = end;
785        if (*s == '+' || *s == '-') {
786            /* <float><signed-float>j | <float><sign>j */
787            x = z;
788            y = PyOS_string_to_double(s, &end, NULL);
789            if (y == -1.0 && PyErr_Occurred()) {
790                if (PyErr_ExceptionMatches(PyExc_ValueError))
791                    PyErr_Clear();
792                else
793                    return NULL;
794            }
795            if (end != s)
796                /* <float><signed-float>j */
797                s = end;
798            else {
799                /* <float><sign>j */
800                y = *s == '+' ? 1.0 : -1.0;
801                s++;
802            }
803            if (!(*s == 'j' || *s == 'J'))
804                goto parse_error;
805            s++;
806        }
807        else if (*s == 'j' || *s == 'J') {
808            /* <float>j */
809            s++;
810            y = z;
811        }
812        else
813            /* <float> */
814            x = z;
815    }
816    else {
817        /* not starting with <float>; must be <sign>j or j */
818        if (*s == '+' || *s == '-') {
819            /* <sign>j */
820            y = *s == '+' ? 1.0 : -1.0;
821            s++;
822        }
823        else
824            /* j */
825            y = 1.0;
826        if (!(*s == 'j' || *s == 'J'))
827            goto parse_error;
828        s++;
829    }
830
831    /* trailing whitespace and closing bracket */
832    while (Py_ISSPACE(*s))
833        s++;
834    if (got_bracket) {
835        /* if there was an opening parenthesis, then the corresponding
836           closing parenthesis should be right here */
837        if (*s != ')')
838            goto parse_error;
839        s++;
840        while (Py_ISSPACE(*s))
841            s++;
842    }
843
844    /* we should now be at the end of the string */
845    if (s-start != len)
846        goto parse_error;
847
848    return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
849
850  parse_error:
851    PyErr_SetString(PyExc_ValueError,
852                    "complex() arg is a malformed string");
853    return NULL;
854}
855
856static PyObject *
857complex_subtype_from_string(PyTypeObject *type, PyObject *v)
858{
859    const char *s;
860    PyObject *s_buffer = NULL, *result = NULL;
861    Py_ssize_t len;
862
863    if (PyUnicode_Check(v)) {
864        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
865        if (s_buffer == NULL) {
866            return NULL;
867        }
868        assert(PyUnicode_IS_ASCII(s_buffer));
869        /* Simply get a pointer to existing ASCII characters. */
870        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
871        assert(s != NULL);
872    }
873    else {
874        PyErr_Format(PyExc_TypeError,
875            "complex() argument must be a string or a number, not '%.200s'",
876            Py_TYPE(v)->tp_name);
877        return NULL;
878    }
879
880    result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
881                                                   complex_from_string_inner);
882    Py_DECREF(s_buffer);
883    return result;
884}
885
886/*[clinic input]
887@classmethod
888complex.__new__ as complex_new
889    real as r: object(c_default="NULL") = 0
890    imag as i: object(c_default="NULL") = 0
891
892Create a complex number from a real part and an optional imaginary part.
893
894This is equivalent to (real + imag*1j) where imag defaults to 0.
895[clinic start generated code]*/
896
897static PyObject *
898complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
899/*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
900{
901    PyObject *tmp;
902    PyNumberMethods *nbr, *nbi = NULL;
903    Py_complex cr, ci;
904    int own_r = 0;
905    int cr_is_complex = 0;
906    int ci_is_complex = 0;
907
908    if (r == NULL) {
909        r = _PyLong_GetZero();
910    }
911
912    /* Special-case for a single argument when type(arg) is complex. */
913    if (PyComplex_CheckExact(r) && i == NULL &&
914        type == &PyComplex_Type) {
915        /* Note that we can't know whether it's safe to return
916           a complex *subclass* instance as-is, hence the restriction
917           to exact complexes here.  If either the input or the
918           output is a complex subclass, it will be handled below
919           as a non-orthogonal vector.  */
920        Py_INCREF(r);
921        return r;
922    }
923    if (PyUnicode_Check(r)) {
924        if (i != NULL) {
925            PyErr_SetString(PyExc_TypeError,
926                            "complex() can't take second arg"
927                            " if first is a string");
928            return NULL;
929        }
930        return complex_subtype_from_string(type, r);
931    }
932    if (i != NULL && PyUnicode_Check(i)) {
933        PyErr_SetString(PyExc_TypeError,
934                        "complex() second arg can't be a string");
935        return NULL;
936    }
937
938    tmp = try_complex_special_method(r);
939    if (tmp) {
940        r = tmp;
941        own_r = 1;
942    }
943    else if (PyErr_Occurred()) {
944        return NULL;
945    }
946
947    nbr = Py_TYPE(r)->tp_as_number;
948    if (nbr == NULL ||
949        (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
950    {
951        PyErr_Format(PyExc_TypeError,
952                     "complex() first argument must be a string or a number, "
953                     "not '%.200s'",
954                     Py_TYPE(r)->tp_name);
955        if (own_r) {
956            Py_DECREF(r);
957        }
958        return NULL;
959    }
960    if (i != NULL) {
961        nbi = Py_TYPE(i)->tp_as_number;
962        if (nbi == NULL ||
963            (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
964        {
965            PyErr_Format(PyExc_TypeError,
966                         "complex() second argument must be a number, "
967                         "not '%.200s'",
968                         Py_TYPE(i)->tp_name);
969            if (own_r) {
970                Py_DECREF(r);
971            }
972            return NULL;
973        }
974    }
975
976    /* If we get this far, then the "real" and "imag" parts should
977       both be treated as numbers, and the constructor should return a
978       complex number equal to (real + imag*1j).
979
980       Note that we do NOT assume the input to already be in canonical
981       form; the "real" and "imag" parts might themselves be complex
982       numbers, which slightly complicates the code below. */
983    if (PyComplex_Check(r)) {
984        /* Note that if r is of a complex subtype, we're only
985           retaining its real & imag parts here, and the return
986           value is (properly) of the builtin complex type. */
987        cr = ((PyComplexObject*)r)->cval;
988        cr_is_complex = 1;
989        if (own_r) {
990            Py_DECREF(r);
991        }
992    }
993    else {
994        /* The "real" part really is entirely real, and contributes
995           nothing in the imaginary direction.
996           Just treat it as a double. */
997        tmp = PyNumber_Float(r);
998        if (own_r) {
999            /* r was a newly created complex number, rather
1000               than the original "real" argument. */
1001            Py_DECREF(r);
1002        }
1003        if (tmp == NULL)
1004            return NULL;
1005        assert(PyFloat_Check(tmp));
1006        cr.real = PyFloat_AsDouble(tmp);
1007        cr.imag = 0.0;
1008        Py_DECREF(tmp);
1009    }
1010    if (i == NULL) {
1011        ci.real = cr.imag;
1012    }
1013    else if (PyComplex_Check(i)) {
1014        ci = ((PyComplexObject*)i)->cval;
1015        ci_is_complex = 1;
1016    } else {
1017        /* The "imag" part really is entirely imaginary, and
1018           contributes nothing in the real direction.
1019           Just treat it as a double. */
1020        tmp = PyNumber_Float(i);
1021        if (tmp == NULL)
1022            return NULL;
1023        ci.real = PyFloat_AsDouble(tmp);
1024        Py_DECREF(tmp);
1025    }
1026    /*  If the input was in canonical form, then the "real" and "imag"
1027        parts are real numbers, so that ci.imag and cr.imag are zero.
1028        We need this correction in case they were not real numbers. */
1029
1030    if (ci_is_complex) {
1031        cr.real -= ci.imag;
1032    }
1033    if (cr_is_complex && i != NULL) {
1034        ci.real += cr.imag;
1035    }
1036    return complex_subtype_from_doubles(type, cr.real, ci.real);
1037}
1038
1039static PyNumberMethods complex_as_number = {
1040    (binaryfunc)complex_add,                    /* nb_add */
1041    (binaryfunc)complex_sub,                    /* nb_subtract */
1042    (binaryfunc)complex_mul,                    /* nb_multiply */
1043    0,                                          /* nb_remainder */
1044    0,                                          /* nb_divmod */
1045    (ternaryfunc)complex_pow,                   /* nb_power */
1046    (unaryfunc)complex_neg,                     /* nb_negative */
1047    (unaryfunc)complex_pos,                     /* nb_positive */
1048    (unaryfunc)complex_abs,                     /* nb_absolute */
1049    (inquiry)complex_bool,                      /* nb_bool */
1050    0,                                          /* nb_invert */
1051    0,                                          /* nb_lshift */
1052    0,                                          /* nb_rshift */
1053    0,                                          /* nb_and */
1054    0,                                          /* nb_xor */
1055    0,                                          /* nb_or */
1056    0,                                          /* nb_int */
1057    0,                                          /* nb_reserved */
1058    0,                                          /* nb_float */
1059    0,                                          /* nb_inplace_add */
1060    0,                                          /* nb_inplace_subtract */
1061    0,                                          /* nb_inplace_multiply*/
1062    0,                                          /* nb_inplace_remainder */
1063    0,                                          /* nb_inplace_power */
1064    0,                                          /* nb_inplace_lshift */
1065    0,                                          /* nb_inplace_rshift */
1066    0,                                          /* nb_inplace_and */
1067    0,                                          /* nb_inplace_xor */
1068    0,                                          /* nb_inplace_or */
1069    0,                                          /* nb_floor_divide */
1070    (binaryfunc)complex_div,                    /* nb_true_divide */
1071    0,                                          /* nb_inplace_floor_divide */
1072    0,                                          /* nb_inplace_true_divide */
1073};
1074
1075PyTypeObject PyComplex_Type = {
1076    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1077    "complex",
1078    sizeof(PyComplexObject),
1079    0,
1080    0,                                          /* tp_dealloc */
1081    0,                                          /* tp_vectorcall_offset */
1082    0,                                          /* tp_getattr */
1083    0,                                          /* tp_setattr */
1084    0,                                          /* tp_as_async */
1085    (reprfunc)complex_repr,                     /* tp_repr */
1086    &complex_as_number,                         /* tp_as_number */
1087    0,                                          /* tp_as_sequence */
1088    0,                                          /* tp_as_mapping */
1089    (hashfunc)complex_hash,                     /* tp_hash */
1090    0,                                          /* tp_call */
1091    0,                                          /* tp_str */
1092    PyObject_GenericGetAttr,                    /* tp_getattro */
1093    0,                                          /* tp_setattro */
1094    0,                                          /* tp_as_buffer */
1095    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
1096    complex_new__doc__,                         /* tp_doc */
1097    0,                                          /* tp_traverse */
1098    0,                                          /* tp_clear */
1099    complex_richcompare,                        /* tp_richcompare */
1100    0,                                          /* tp_weaklistoffset */
1101    0,                                          /* tp_iter */
1102    0,                                          /* tp_iternext */
1103    complex_methods,                            /* tp_methods */
1104    complex_members,                            /* tp_members */
1105    0,                                          /* tp_getset */
1106    0,                                          /* tp_base */
1107    0,                                          /* tp_dict */
1108    0,                                          /* tp_descr_get */
1109    0,                                          /* tp_descr_set */
1110    0,                                          /* tp_dictoffset */
1111    0,                                          /* tp_init */
1112    PyType_GenericAlloc,                        /* tp_alloc */
1113    complex_new,                                /* tp_new */
1114    PyObject_Del,                               /* tp_free */
1115};
1116