From 61ce260ff73b1191a9190c8cac7a7a1bd5b2f274 Mon Sep 17 00:00:00 2001 From: Damien George Date: Tue, 21 Jun 2022 23:45:27 +1000 Subject: [PATCH] py/parsenum: Fix parsing of complex "j" and also "nanj", "infj". Prior to this commit, complex("j") would return 0j, and complex("nanj") would return nan+0j. This commit makes sure "j" is tested for after parsing the number (nan, inf or a decimal), and also supports the case of "j" on its own. Signed-off-by: Damien George --- py/parsenum.c | 12 +++++++++--- tests/float/complex1.py | 5 +++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/py/parsenum.c b/py/parsenum.c index 848a7732d9..b90dfaaafb 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -291,9 +291,6 @@ parse_start: if (str == top) { goto value_error; } - } else if (allow_imag && (dig | 0x20) == 'j') { - real_imag_state |= REAL_IMAG_STATE_HAVE_IMAG; - break; } else if (dig == '_') { continue; } else { @@ -327,6 +324,15 @@ parse_start: } } + if (allow_imag && str < top && (*str | 0x20) == 'j') { + if (str == str_val_start) { + // Convert "j" to "1j". + dec_val = 1; + } + ++str; + real_imag_state |= REAL_IMAG_STATE_HAVE_IMAG; + } + // negate value if needed if (dec_neg) { dec_val = -dec_val; diff --git a/tests/float/complex1.py b/tests/float/complex1.py index feede0eab3..f4107a1390 100644 --- a/tests/float/complex1.py +++ b/tests/float/complex1.py @@ -4,14 +4,19 @@ print(complex(1)) print(complex(1.2)) print(complex(1.2j)) +print(complex("j")) +print(complex("J")) print(complex("1")) print(complex("1.2")) print(complex("1.2j")) +print(complex("1+j")) print(complex("1+2j")) print(complex("-1-2j")) print(complex("+1-2j")) print(complex(" -1-2j ")) print(complex(" +1-2j ")) +print(complex("nanj")) +print(complex("nan-infj")) print(complex(1, 2)) print(complex(1j, 2j))