parsenum.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdbool.h>
  27. #include <stdlib.h>
  28. #include "py/runtime.h"
  29. #include "py/parsenumbase.h"
  30. #include "py/parsenum.h"
  31. #include "py/smallint.h"
  32. #if MICROPY_PY_BUILTINS_FLOAT
  33. #include <math.h>
  34. #endif
  35. STATIC NORETURN void raise_exc(mp_obj_t exc, mp_lexer_t *lex) {
  36. // if lex!=NULL then the parser called us and we need to convert the
  37. // exception's type from ValueError to SyntaxError and add traceback info
  38. if (lex != NULL) {
  39. ((mp_obj_base_t *)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError;
  40. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
  41. }
  42. nlr_raise(exc);
  43. }
  44. mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, mp_lexer_t *lex) {
  45. const byte *restrict str = (const byte *)str_;
  46. const byte *restrict top = str + len;
  47. bool neg = false;
  48. mp_obj_t ret_val;
  49. // check radix base
  50. if ((base != 0 && base < 2) || base > 36) {
  51. // this won't be reached if lex!=NULL
  52. mp_raise_ValueError(MP_ERROR_TEXT("int() arg 2 must be >= 2 and <= 36"));
  53. }
  54. // skip leading space
  55. for (; str < top && unichar_isspace(*str); str++) {
  56. }
  57. // parse optional sign
  58. if (str < top) {
  59. if (*str == '+') {
  60. str++;
  61. } else if (*str == '-') {
  62. str++;
  63. neg = true;
  64. }
  65. }
  66. // parse optional base prefix
  67. str += mp_parse_num_base((const char *)str, top - str, &base);
  68. // string should be an integer number
  69. mp_int_t int_val = 0;
  70. const byte *restrict str_val_start = str;
  71. for (; str < top; str++) {
  72. // get next digit as a value
  73. mp_uint_t dig = *str;
  74. if ('0' <= dig && dig <= '9') {
  75. dig -= '0';
  76. } else if (dig == '_') {
  77. continue;
  78. } else {
  79. dig |= 0x20; // make digit lower-case
  80. if ('a' <= dig && dig <= 'z') {
  81. dig -= 'a' - 10;
  82. } else {
  83. // unknown character
  84. break;
  85. }
  86. }
  87. if (dig >= (mp_uint_t)base) {
  88. break;
  89. }
  90. // add next digi and check for overflow
  91. if (mp_small_int_mul_overflow(int_val, base)) {
  92. goto overflow;
  93. }
  94. int_val = int_val * base + dig;
  95. if (!MP_SMALL_INT_FITS(int_val)) {
  96. goto overflow;
  97. }
  98. }
  99. // negate value if needed
  100. if (neg) {
  101. int_val = -int_val;
  102. }
  103. // create the small int
  104. ret_val = MP_OBJ_NEW_SMALL_INT(int_val);
  105. have_ret_val:
  106. // check we parsed something
  107. if (str == str_val_start) {
  108. goto value_error;
  109. }
  110. // skip trailing space
  111. for (; str < top && unichar_isspace(*str); str++) {
  112. }
  113. // check we reached the end of the string
  114. if (str != top) {
  115. goto value_error;
  116. }
  117. // return the object
  118. return ret_val;
  119. overflow:
  120. // reparse using long int
  121. {
  122. const char *s2 = (const char *)str_val_start;
  123. ret_val = mp_obj_new_int_from_str_len(&s2, top - str_val_start, neg, base);
  124. str = (const byte *)s2;
  125. goto have_ret_val;
  126. }
  127. value_error:
  128. {
  129. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  130. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError,
  131. MP_ERROR_TEXT("invalid syntax for integer"));
  132. raise_exc(exc, lex);
  133. #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
  134. mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  135. MP_ERROR_TEXT("invalid syntax for integer with base %d"), base);
  136. raise_exc(exc, lex);
  137. #else
  138. vstr_t vstr;
  139. mp_print_t print;
  140. vstr_init_print(&vstr, 50, &print);
  141. mp_printf(&print, "invalid syntax for integer with base %d: ", base);
  142. mp_str_print_quoted(&print, str_val_start, top - str_val_start, true);
  143. mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError,
  144. mp_obj_new_str_from_vstr(&mp_type_str, &vstr));
  145. raise_exc(exc, lex);
  146. #endif
  147. }
  148. }
  149. typedef enum {
  150. PARSE_DEC_IN_INTG,
  151. PARSE_DEC_IN_FRAC,
  152. PARSE_DEC_IN_EXP,
  153. } parse_dec_in_t;
  154. mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) {
  155. #if MICROPY_PY_BUILTINS_FLOAT
  156. // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing
  157. // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float
  158. // EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float
  159. // Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n
  160. // so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's
  161. // exponent).
  162. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  163. #define DEC_VAL_MAX 1e20F
  164. #define SMALL_NORMAL_VAL (1e-37F)
  165. #define SMALL_NORMAL_EXP (-37)
  166. #define EXACT_POWER_OF_10 (9)
  167. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  168. #define DEC_VAL_MAX 1e200
  169. #define SMALL_NORMAL_VAL (1e-307)
  170. #define SMALL_NORMAL_EXP (-307)
  171. #define EXACT_POWER_OF_10 (22)
  172. #endif
  173. const char *top = str + len;
  174. mp_float_t dec_val = 0;
  175. bool dec_neg = false;
  176. bool imag = false;
  177. // skip leading space
  178. for (; str < top && unichar_isspace(*str); str++) {
  179. }
  180. // parse optional sign
  181. if (str < top) {
  182. if (*str == '+') {
  183. str++;
  184. } else if (*str == '-') {
  185. str++;
  186. dec_neg = true;
  187. }
  188. }
  189. const char *str_val_start = str;
  190. // determine what the string is
  191. if (str < top && (str[0] | 0x20) == 'i') {
  192. // string starts with 'i', should be 'inf' or 'infinity' (case insensitive)
  193. if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') {
  194. // inf
  195. str += 3;
  196. dec_val = (mp_float_t)INFINITY;
  197. if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') {
  198. // infinity
  199. str += 5;
  200. }
  201. }
  202. } else if (str < top && (str[0] | 0x20) == 'n') {
  203. // string starts with 'n', should be 'nan' (case insensitive)
  204. if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') {
  205. // NaN
  206. str += 3;
  207. dec_val = MICROPY_FLOAT_C_FUN(nan)("");
  208. }
  209. } else {
  210. // string should be a decimal number
  211. parse_dec_in_t in = PARSE_DEC_IN_INTG;
  212. bool exp_neg = false;
  213. int exp_val = 0;
  214. int exp_extra = 0;
  215. while (str < top) {
  216. unsigned int dig = *str++;
  217. if ('0' <= dig && dig <= '9') {
  218. dig -= '0';
  219. if (in == PARSE_DEC_IN_EXP) {
  220. // don't overflow exp_val when adding next digit, instead just truncate
  221. // it and the resulting float will still be correct, either inf or 0.0
  222. // (use INT_MAX/2 to allow adding exp_extra at the end without overflow)
  223. if (exp_val < (INT_MAX / 2 - 9) / 10) {
  224. exp_val = 10 * exp_val + dig;
  225. }
  226. } else {
  227. if (dec_val < DEC_VAL_MAX) {
  228. // dec_val won't overflow so keep accumulating
  229. dec_val = 10 * dec_val + dig;
  230. if (in == PARSE_DEC_IN_FRAC) {
  231. --exp_extra;
  232. }
  233. } else {
  234. // dec_val might overflow and we anyway can't represent more digits
  235. // of precision, so ignore the digit and just adjust the exponent
  236. if (in == PARSE_DEC_IN_INTG) {
  237. ++exp_extra;
  238. }
  239. }
  240. }
  241. } else if (in == PARSE_DEC_IN_INTG && dig == '.') {
  242. in = PARSE_DEC_IN_FRAC;
  243. } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) {
  244. in = PARSE_DEC_IN_EXP;
  245. if (str < top) {
  246. if (str[0] == '+') {
  247. str++;
  248. } else if (str[0] == '-') {
  249. str++;
  250. exp_neg = true;
  251. }
  252. }
  253. if (str == top) {
  254. goto value_error;
  255. }
  256. } else if (allow_imag && (dig | 0x20) == 'j') {
  257. imag = true;
  258. break;
  259. } else if (dig == '_') {
  260. continue;
  261. } else {
  262. // unknown character
  263. str--;
  264. break;
  265. }
  266. }
  267. // work out the exponent
  268. if (exp_neg) {
  269. exp_val = -exp_val;
  270. }
  271. // apply the exponent, making sure it's not a subnormal value
  272. exp_val += exp_extra;
  273. if (exp_val < SMALL_NORMAL_EXP) {
  274. exp_val -= SMALL_NORMAL_EXP;
  275. dec_val *= SMALL_NORMAL_VAL;
  276. }
  277. // At this point, we need to multiply the mantissa by its base 10 exponent. If possible,
  278. // we would rather manipulate numbers that have an exact representation in IEEE754. It
  279. // turns out small positive powers of 10 do, whereas small negative powers of 10 don't.
  280. // So in that case, we'll yield a division of exact values rather than a multiplication
  281. // of slightly erroneous values.
  282. if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) {
  283. dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val);
  284. } else {
  285. dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val);
  286. }
  287. }
  288. // negate value if needed
  289. if (dec_neg) {
  290. dec_val = -dec_val;
  291. }
  292. // check we parsed something
  293. if (str == str_val_start) {
  294. goto value_error;
  295. }
  296. // skip trailing space
  297. for (; str < top && unichar_isspace(*str); str++) {
  298. }
  299. // check we reached the end of the string
  300. if (str != top) {
  301. goto value_error;
  302. }
  303. // return the object
  304. #if MICROPY_PY_BUILTINS_COMPLEX
  305. if (imag) {
  306. return mp_obj_new_complex(0, dec_val);
  307. } else if (force_complex) {
  308. return mp_obj_new_complex(dec_val, 0);
  309. }
  310. #else
  311. if (imag || force_complex) {
  312. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("complex values not supported")), lex);
  313. }
  314. #endif
  315. else {
  316. return mp_obj_new_float(dec_val);
  317. }
  318. value_error:
  319. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid syntax for number")), lex);
  320. #else
  321. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("decimal numbers not supported")), lex);
  322. #endif
  323. }