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