py/parsenum: Fix parsing complex literals with negative real part.

If a complex literal had a negative real part and a positive imaginary
part, it was not parsed properly because the imaginary part also came out
negative.

Includes a test of complex parsing, which fails without this fix.

Co-authored-by: ComplexSymbol <141301057+ComplexSymbol@users.noreply.github.com>
Signed-off-by: Jeff Epler <jepler@gmail.com>
This commit is contained in:
Jeff Epler 2025-05-28 20:49:29 +02:00 committed by Damien George
parent 0a98f3a911
commit 2ce63b1420
2 changed files with 4 additions and 2 deletions

View file

@ -227,13 +227,13 @@ mp_obj_t mp_parse_num_float(const char *str, size_t len, bool allow_imag, mp_lex
const char *top = str + len; const char *top = str + len;
mp_float_t dec_val = 0; mp_float_t dec_val = 0;
bool dec_neg = false;
#if MICROPY_PY_BUILTINS_COMPLEX #if MICROPY_PY_BUILTINS_COMPLEX
unsigned int real_imag_state = REAL_IMAG_STATE_START; unsigned int real_imag_state = REAL_IMAG_STATE_START;
mp_float_t dec_real = 0; mp_float_t dec_real = 0;
parse_start: parse_start:;
#endif #endif
bool dec_neg = false;
// skip leading space // skip leading space
for (; str < top && unichar_isspace(*str); str++) { for (; str < top && unichar_isspace(*str); str++) {

View file

@ -12,9 +12,11 @@ print(complex("1.2j"))
print(complex("1+j")) 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("+1-2j")) print(complex("+1-2j"))
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("nanj"))
print(complex("nan-infj")) print(complex("nan-infj"))
print(complex(1, 2)) print(complex(1, 2))