@@ -166,6 +166,12 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m
166
166
}
167
167
}
168
168
169
+ enum {
170
+ REAL_IMAG_STATE_START = 0 ,
171
+ REAL_IMAG_STATE_HAVE_REAL = 1 ,
172
+ REAL_IMAG_STATE_HAVE_IMAG = 2 ,
173
+ };
174
+
169
175
typedef enum {
170
176
PARSE_DEC_IN_INTG ,
171
177
PARSE_DEC_IN_FRAC ,
@@ -196,7 +202,12 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
196
202
const char * top = str + len ;
197
203
mp_float_t dec_val = 0 ;
198
204
bool dec_neg = false;
199
- bool imag = false;
205
+ unsigned int real_imag_state = REAL_IMAG_STATE_START ;
206
+
207
+ #if MICROPY_PY_BUILTINS_COMPLEX
208
+ mp_float_t dec_real = 0 ;
209
+ parse_start :
210
+ #endif
10000
200
211
201
212
// skip leading space
202
213
for (; str < top && unichar_isspace (* str ); str ++ ) {
@@ -281,7 +292,7 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
281
292
goto value_error ;
282
293
}
283
294
} else if (allow_imag && (dig | 0x20 ) == 'j' ) {
284
- imag = true ;
295
+ real_imag_state |= REAL_IMAG_STATE_HAVE_IMAG ;
285
296
break ;
286
297
} else if (dig == '_' ) {
287
298
continue ;
@@ -332,18 +343,34 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
332
343
333
344
// check we reached the end of the string
334
345
if (str != top ) {
346
+ #if MICROPY_PY_BUILTINS_COMPLEX
347
+ if (force_complex && real_imag_state == REAL_IMAG_STATE_START ) {
348
+ // If we've only seen a real so far, keep parsing for the imaginary part.
349
+ dec_real = dec_val ;
350
+ dec_val = 0 ;
351
+ real_imag_state |= REAL_IMAG_STATE_HAVE_REAL ;
352
+ goto parse_start ;
353
+ }
354
+ #endif
335
355
goto value_error ;
336
356
}
337
357
358
+ #if MICROPY_PY_BUILTINS_COMPLEX
359
+ if (real_imag_state == REAL_IMAG_STATE_HAVE_REAL ) {
360
+ // We're on the second part, but didn't get the expected imaginary number.
361
+ goto value_error ;
362
+ }
363
+ #endif
364
+
338
365
// return the object
339
366
#if MICROPY_PY_BUILTINS_COMPLEX
340
- if (imag ) {
341
- return mp_obj_new_complex (0 , dec_val );
367
+ if (real_imag_state != REAL_IMAG_STATE_START ) {
368
+ return mp_obj_new_complex (dec_real , dec_val );
342
369
} else if (force_complex ) {
343
370
return mp_obj_new_complex (dec_val , 0 );
344
371
}
345
372
#else
346
- if (imag || force_complex ) {
373
+ if (real_imag_state != REAL_IMAG_STATE_START || force_complex ) {
347
374
raise_exc (mp_obj_new_exception_msg (& mp_type_ValueError , MP_ERROR_TEXT ("complex values not supported" )), lex );
348
375
}
349
376
#endif
0 commit comments