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]
17 class 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
25 static Py_complex c_1 = {1., 0.};
26
27 Py_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
36 Py_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
45 Py_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
54 Py_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
67 Py_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
128 Py_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
158 static Py_complex
159 c_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
174 static Py_complex
175 c_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
184 double
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
216 static PyObject *
217 complex_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
227 PyObject *
228 PyComplex_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
240 static PyObject *
241 complex_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
249 PyObject *
250 PyComplex_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
258 double
259 PyComplex_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
269 double
270 PyComplex_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
280 static PyObject *
281 try_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
313 Py_complex
314 PyComplex_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
349 static PyObject *
350 complex_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
405 static Py_hash_t
406 complex_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
434 static int
435 to_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 *pobj = Py_NewRef(Py_NotImplemented);
453 return -1;
454 }
455
456
457 static PyObject *
458 complex_add(PyObject *v, PyObject *w)
459 {
460 Py_complex result;
461 Py_complex a, b;
462 TO_COMPLEX(v, a);
463 TO_COMPLEX(w, b);
464 result = _Py_c_sum(a, b);
465 return PyComplex_FromCComplex(result);
466 }
467
468 static PyObject *
469 complex_sub(PyObject *v, PyObject *w)
470 {
471 Py_complex result;
472 Py_complex a, b;
473 TO_COMPLEX(v, a);
474 TO_COMPLEX(w, b);
475 result = _Py_c_diff(a, b);
476 return PyComplex_FromCComplex(result);
477 }
478
479 static PyObject *
480 complex_mul(PyObject *v, PyObject *w)
481 {
482 Py_complex result;
483 Py_complex a, b;
484 TO_COMPLEX(v, a);
485 TO_COMPLEX(w, b);
486 result = _Py_c_prod(a, b);
487 return PyComplex_FromCComplex(result);
488 }
489
490 static PyObject *
491 complex_div(PyObject *v, PyObject *w)
492 {
493 Py_complex quot;
494 Py_complex a, b;
495 TO_COMPLEX(v, a);
496 TO_COMPLEX(w, b);
497 errno = 0;
498 quot = _Py_c_quot(a, b);
499 if (errno == EDOM) {
500 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
501 return NULL;
502 }
503 return PyComplex_FromCComplex(quot);
504 }
505
506 static PyObject *
507 complex_pow(PyObject *v, PyObject *w, PyObject *z)
508 {
509 Py_complex p;
510 Py_complex a, b;
511 TO_COMPLEX(v, a);
512 TO_COMPLEX(w, b);
513
514 if (z != Py_None) {
515 PyErr_SetString(PyExc_ValueError, "complex modulo");
516 return NULL;
517 }
518 errno = 0;
519 // Check whether the exponent has a small integer value, and if so use
520 // a faster and more accurate algorithm.
521 if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
522 p = c_powi(a, (long)b.real);
523 }
524 else {
525 p = _Py_c_pow(a, b);
526 }
527
528 _Py_ADJUST_ERANGE2(p.real, p.imag);
529 if (errno == EDOM) {
530 PyErr_SetString(PyExc_ZeroDivisionError,
531 "0.0 to a negative or complex power");
532 return NULL;
533 }
534 else if (errno == ERANGE) {
535 PyErr_SetString(PyExc_OverflowError,
536 "complex exponentiation");
537 return NULL;
538 }
539 return PyComplex_FromCComplex(p);
540 }
541
542 static PyObject *
543 complex_neg(PyComplexObject *v)
544 {
545 Py_complex neg;
546 neg.real = -v->cval.real;
547 neg.imag = -v->cval.imag;
548 return PyComplex_FromCComplex(neg);
549 }
550
551 static PyObject *
552 complex_pos(PyComplexObject *v)
553 {
554 if (PyComplex_CheckExact(v)) {
555 return Py_NewRef(v);
556 }
557 else
558 return PyComplex_FromCComplex(v->cval);
559 }
560
561 static PyObject *
562 complex_abs(PyComplexObject *v)
563 {
564 double result;
565
566 result = _Py_c_abs(v->cval);
567
568 if (errno == ERANGE) {
569 PyErr_SetString(PyExc_OverflowError,
570 "absolute value too large");
571 return NULL;
572 }
573 return PyFloat_FromDouble(result);
574 }
575
576 static int
577 complex_bool(PyComplexObject *v)
578 {
579 return v->cval.real != 0.0 || v->cval.imag != 0.0;
580 }
581
582 static PyObject *
583 complex_richcompare(PyObject *v, PyObject *w, int op)
584 {
585 PyObject *res;
586 Py_complex i;
587 int equal;
588
589 if (op != Py_EQ && op != Py_NE) {
590 goto Unimplemented;
591 }
592
593 assert(PyComplex_Check(v));
594 TO_COMPLEX(v, i);
595
596 if (PyLong_Check(w)) {
597 /* Check for 0.0 imaginary part first to avoid the rich
598 * comparison when possible.
599 */
600 if (i.imag == 0.0) {
601 PyObject *j, *sub_res;
602 j = PyFloat_FromDouble(i.real);
603 if (j == NULL)
604 return NULL;
605
606 sub_res = PyObject_RichCompare(j, w, op);
607 Py_DECREF(j);
608 return sub_res;
609 }
610 else {
611 equal = 0;
612 }
613 }
614 else if (PyFloat_Check(w)) {
615 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
616 }
617 else if (PyComplex_Check(w)) {
618 Py_complex j;
619
620 TO_COMPLEX(w, j);
621 equal = (i.real == j.real && i.imag == j.imag);
622 }
623 else {
624 goto Unimplemented;
625 }
626
627 if (equal == (op == Py_EQ))
628 res = Py_True;
629 else
630 res = Py_False;
631
632 return Py_NewRef(res);
633
634 Unimplemented:
635 Py_RETURN_NOTIMPLEMENTED;
636 }
637
638 /*[clinic input]
639 complex.conjugate
640
641 Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
642 [clinic start generated code]*/
643
644 static PyObject *
645 complex_conjugate_impl(PyComplexObject *self)
646 /*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
647 {
648 Py_complex c = self->cval;
649 c.imag = -c.imag;
650 return PyComplex_FromCComplex(c);
651 }
652
653 /*[clinic input]
654 complex.__getnewargs__
655
656 [clinic start generated code]*/
657
658 static PyObject *
659 complex___getnewargs___impl(PyComplexObject *self)
660 /*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
661 {
662 Py_complex c = self->cval;
663 return Py_BuildValue("(dd)", c.real, c.imag);
664 }
665
666
667 /*[clinic input]
668 complex.__format__
669
670 format_spec: unicode
671 /
672
673 Convert to a string according to format_spec.
674 [clinic start generated code]*/
675
676 static PyObject *
677 complex___format___impl(PyComplexObject *self, PyObject *format_spec)
678 /*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
679 {
680 _PyUnicodeWriter writer;
681 int ret;
682 _PyUnicodeWriter_Init(&writer);
683 ret = _PyComplex_FormatAdvancedWriter(
684 &writer,
685 (PyObject *)self,
686 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
687 if (ret == -1) {
688 _PyUnicodeWriter_Dealloc(&writer);
689 return NULL;
690 }
691 return _PyUnicodeWriter_Finish(&writer);
692 }
693
694 /*[clinic input]
695 complex.__complex__
696
697 Convert this value to exact type complex.
698 [clinic start generated code]*/
699
700 static PyObject *
701 complex___complex___impl(PyComplexObject *self)
702 /*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
703 {
704 if (PyComplex_CheckExact(self)) {
705 return Py_NewRef(self);
706 }
707 else {
708 return PyComplex_FromCComplex(self->cval);
709 }
710 }
711
712
713 static PyMethodDef complex_methods[] = {
714 COMPLEX_CONJUGATE_METHODDEF
715 COMPLEX___COMPLEX___METHODDEF
716 COMPLEX___GETNEWARGS___METHODDEF
717 COMPLEX___FORMAT___METHODDEF
718 {NULL, NULL} /* sentinel */
719 };
720
721 static PyMemberDef complex_members[] = {
722 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
723 "the real part of a complex number"},
724 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
725 "the imaginary part of a complex number"},
726 {0},
727 };
728
729 static PyObject *
730 complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
731 {
732 double x=0.0, y=0.0, z;
733 int got_bracket=0;
734 const char *start;
735 char *end;
736
737 /* position on first nonblank */
738 start = s;
739 while (Py_ISSPACE(*s))
740 s++;
741 if (*s == '(') {
742 /* Skip over possible bracket from repr(). */
743 got_bracket = 1;
744 s++;
745 while (Py_ISSPACE(*s))
746 s++;
747 }
748
749 /* a valid complex string usually takes one of the three forms:
750
751 <float> - real part only
752 <float>j - imaginary part only
753 <float><signed-float>j - real and imaginary parts
754
755 where <float> represents any numeric string that's accepted by the
756 float constructor (including 'nan', 'inf', 'infinity', etc.), and
757 <signed-float> is any string of the form <float> whose first
758 character is '+' or '-'.
759
760 For backwards compatibility, the extra forms
761
762 <float><sign>j
763 <sign>j
764 j
765
766 are also accepted, though support for these forms may be removed from
767 a future version of Python.
768 */
769
770 /* first look for forms starting with <float> */
771 z = PyOS_string_to_double(s, &end, NULL);
772 if (z == -1.0 && PyErr_Occurred()) {
773 if (PyErr_ExceptionMatches(PyExc_ValueError))
774 PyErr_Clear();
775 else
776 return NULL;
777 }
778 if (end != s) {
779 /* all 4 forms starting with <float> land here */
780 s = end;
781 if (*s == '+' || *s == '-') {
782 /* <float><signed-float>j | <float><sign>j */
783 x = z;
784 y = PyOS_string_to_double(s, &end, NULL);
785 if (y == -1.0 && PyErr_Occurred()) {
786 if (PyErr_ExceptionMatches(PyExc_ValueError))
787 PyErr_Clear();
788 else
789 return NULL;
790 }
791 if (end != s)
792 /* <float><signed-float>j */
793 s = end;
794 else {
795 /* <float><sign>j */
796 y = *s == '+' ? 1.0 : -1.0;
797 s++;
798 }
799 if (!(*s == 'j' || *s == 'J'))
800 goto parse_error;
801 s++;
802 }
803 else if (*s == 'j' || *s == 'J') {
804 /* <float>j */
805 s++;
806 y = z;
807 }
808 else
809 /* <float> */
810 x = z;
811 }
812 else {
813 /* not starting with <float>; must be <sign>j or j */
814 if (*s == '+' || *s == '-') {
815 /* <sign>j */
816 y = *s == '+' ? 1.0 : -1.0;
817 s++;
818 }
819 else
820 /* j */
821 y = 1.0;
822 if (!(*s == 'j' || *s == 'J'))
823 goto parse_error;
824 s++;
825 }
826
827 /* trailing whitespace and closing bracket */
828 while (Py_ISSPACE(*s))
829 s++;
830 if (got_bracket) {
831 /* if there was an opening parenthesis, then the corresponding
832 closing parenthesis should be right here */
833 if (*s != ')')
834 goto parse_error;
835 s++;
836 while (Py_ISSPACE(*s))
837 s++;
838 }
839
840 /* we should now be at the end of the string */
841 if (s-start != len)
842 goto parse_error;
843
844 return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
845
846 parse_error:
847 PyErr_SetString(PyExc_ValueError,
848 "complex() arg is a malformed string");
849 return NULL;
850 }
851
852 static PyObject *
853 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
854 {
855 const char *s;
856 PyObject *s_buffer = NULL, *result = NULL;
857 Py_ssize_t len;
858
859 if (PyUnicode_Check(v)) {
860 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
861 if (s_buffer == NULL) {
862 return NULL;
863 }
864 assert(PyUnicode_IS_ASCII(s_buffer));
865 /* Simply get a pointer to existing ASCII characters. */
866 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
867 assert(s != NULL);
868 }
869 else {
870 PyErr_Format(PyExc_TypeError,
871 "complex() argument must be a string or a number, not '%.200s'",
872 Py_TYPE(v)->tp_name);
873 return NULL;
874 }
875
876 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
877 complex_from_string_inner);
878 Py_DECREF(s_buffer);
879 return result;
880 }
881
882 /*[clinic input]
883 @classmethod
884 complex.__new__ as complex_new
885 real as r: object(c_default="NULL") = 0
886 imag as i: object(c_default="NULL") = 0
887
888 Create a complex number from a real part and an optional imaginary part.
889
890 This is equivalent to (real + imag*1j) where imag defaults to 0.
891 [clinic start generated code]*/
892
893 static PyObject *
894 complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
895 /*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
896 {
897 PyObject *tmp;
898 PyNumberMethods *nbr, *nbi = NULL;
899 Py_complex cr, ci;
900 int own_r = 0;
901 int cr_is_complex = 0;
902 int ci_is_complex = 0;
903
904 if (r == NULL) {
905 r = _PyLong_GetZero();
906 }
907
908 /* Special-case for a single argument when type(arg) is complex. */
909 if (PyComplex_CheckExact(r) && i == NULL &&
910 type == &PyComplex_Type) {
911 /* Note that we can't know whether it's safe to return
912 a complex *subclass* instance as-is, hence the restriction
913 to exact complexes here. If either the input or the
914 output is a complex subclass, it will be handled below
915 as a non-orthogonal vector. */
916 return Py_NewRef(r);
917 }
918 if (PyUnicode_Check(r)) {
919 if (i != NULL) {
920 PyErr_SetString(PyExc_TypeError,
921 "complex() can't take second arg"
922 " if first is a string");
923 return NULL;
924 }
925 return complex_subtype_from_string(type, r);
926 }
927 if (i != NULL && PyUnicode_Check(i)) {
928 PyErr_SetString(PyExc_TypeError,
929 "complex() second arg can't be a string");
930 return NULL;
931 }
932
933 tmp = try_complex_special_method(r);
934 if (tmp) {
935 r = tmp;
936 own_r = 1;
937 }
938 else if (PyErr_Occurred()) {
939 return NULL;
940 }
941
942 nbr = Py_TYPE(r)->tp_as_number;
943 if (nbr == NULL ||
944 (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
945 {
946 PyErr_Format(PyExc_TypeError,
947 "complex() first argument must be a string or a number, "
948 "not '%.200s'",
949 Py_TYPE(r)->tp_name);
950 if (own_r) {
951 Py_DECREF(r);
952 }
953 return NULL;
954 }
955 if (i != NULL) {
956 nbi = Py_TYPE(i)->tp_as_number;
957 if (nbi == NULL ||
958 (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
959 {
960 PyErr_Format(PyExc_TypeError,
961 "complex() second argument must be a number, "
962 "not '%.200s'",
963 Py_TYPE(i)->tp_name);
964 if (own_r) {
965 Py_DECREF(r);
966 }
967 return NULL;
968 }
969 }
970
971 /* If we get this far, then the "real" and "imag" parts should
972 both be treated as numbers, and the constructor should return a
973 complex number equal to (real + imag*1j).
974
975 Note that we do NOT assume the input to already be in canonical
976 form; the "real" and "imag" parts might themselves be complex
977 numbers, which slightly complicates the code below. */
978 if (PyComplex_Check(r)) {
979 /* Note that if r is of a complex subtype, we're only
980 retaining its real & imag parts here, and the return
981 value is (properly) of the builtin complex type. */
982 cr = ((PyComplexObject*)r)->cval;
983 cr_is_complex = 1;
984 if (own_r) {
985 Py_DECREF(r);
986 }
987 }
988 else {
989 /* The "real" part really is entirely real, and contributes
990 nothing in the imaginary direction.
991 Just treat it as a double. */
992 tmp = PyNumber_Float(r);
993 if (own_r) {
994 /* r was a newly created complex number, rather
995 than the original "real" argument. */
996 Py_DECREF(r);
997 }
998 if (tmp == NULL)
999 return NULL;
1000 assert(PyFloat_Check(tmp));
1001 cr.real = PyFloat_AsDouble(tmp);
1002 cr.imag = 0.0;
1003 Py_DECREF(tmp);
1004 }
1005 if (i == NULL) {
1006 ci.real = cr.imag;
1007 }
1008 else if (PyComplex_Check(i)) {
1009 ci = ((PyComplexObject*)i)->cval;
1010 ci_is_complex = 1;
1011 } else {
1012 /* The "imag" part really is entirely imaginary, and
1013 contributes nothing in the real direction.
1014 Just treat it as a double. */
1015 tmp = PyNumber_Float(i);
1016 if (tmp == NULL)
1017 return NULL;
1018 ci.real = PyFloat_AsDouble(tmp);
1019 Py_DECREF(tmp);
1020 }
1021 /* If the input was in canonical form, then the "real" and "imag"
1022 parts are real numbers, so that ci.imag and cr.imag are zero.
1023 We need this correction in case they were not real numbers. */
1024
1025 if (ci_is_complex) {
1026 cr.real -= ci.imag;
1027 }
1028 if (cr_is_complex && i != NULL) {
1029 ci.real += cr.imag;
1030 }
1031 return complex_subtype_from_doubles(type, cr.real, ci.real);
1032 }
1033
1034 static PyNumberMethods complex_as_number = {
1035 (binaryfunc)complex_add, /* nb_add */
1036 (binaryfunc)complex_sub, /* nb_subtract */
1037 (binaryfunc)complex_mul, /* nb_multiply */
1038 0, /* nb_remainder */
1039 0, /* nb_divmod */
1040 (ternaryfunc)complex_pow, /* nb_power */
1041 (unaryfunc)complex_neg, /* nb_negative */
1042 (unaryfunc)complex_pos, /* nb_positive */
1043 (unaryfunc)complex_abs, /* nb_absolute */
1044 (inquiry)complex_bool, /* nb_bool */
1045 0, /* nb_invert */
1046 0, /* nb_lshift */
1047 0, /* nb_rshift */
1048 0, /* nb_and */
1049 0, /* nb_xor */
1050 0, /* nb_or */
1051 0, /* nb_int */
1052 0, /* nb_reserved */
1053 0, /* nb_float */
1054 0, /* nb_inplace_add */
1055 0, /* nb_inplace_subtract */
1056 0, /* nb_inplace_multiply*/
1057 0, /* nb_inplace_remainder */
1058 0, /* nb_inplace_power */
1059 0, /* nb_inplace_lshift */
1060 0, /* nb_inplace_rshift */
1061 0, /* nb_inplace_and */
1062 0, /* nb_inplace_xor */
1063 0, /* nb_inplace_or */
1064 0, /* nb_floor_divide */
1065 (binaryfunc)complex_div, /* nb_true_divide */
1066 0, /* nb_inplace_floor_divide */
1067 0, /* nb_inplace_true_divide */
1068 };
1069
1070 PyTypeObject PyComplex_Type = {
1071 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1072 "complex",
1073 sizeof(PyComplexObject),
1074 0,
1075 0, /* tp_dealloc */
1076 0, /* tp_vectorcall_offset */
1077 0, /* tp_getattr */
1078 0, /* tp_setattr */
1079 0, /* tp_as_async */
1080 (reprfunc)complex_repr, /* tp_repr */
1081 &complex_as_number, /* tp_as_number */
1082 0, /* tp_as_sequence */
1083 0, /* tp_as_mapping */
1084 (hashfunc)complex_hash, /* tp_hash */
1085 0, /* tp_call */
1086 0, /* tp_str */
1087 PyObject_GenericGetAttr, /* tp_getattro */
1088 0, /* tp_setattro */
1089 0, /* tp_as_buffer */
1090 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1091 complex_new__doc__, /* tp_doc */
1092 0, /* tp_traverse */
1093 0, /* tp_clear */
1094 complex_richcompare, /* tp_richcompare */
1095 0, /* tp_weaklistoffset */
1096 0, /* tp_iter */
1097 0, /* tp_iternext */
1098 complex_methods, /* tp_methods */
1099 complex_members, /* tp_members */
1100 0, /* tp_getset */
1101 0, /* tp_base */
1102 0, /* tp_dict */
1103 0, /* tp_descr_get */
1104 0, /* tp_descr_set */
1105 0, /* tp_dictoffset */
1106 0, /* tp_init */
1107 PyType_GenericAlloc, /* tp_alloc */
1108 complex_new, /* tp_new */
1109 PyObject_Del, /* tp_free */
1110 };