parsenum.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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_QSTR_NULL);
  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("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. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  129. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError,
  130. "invalid syntax for integer");
  131. raise_exc(exc, lex);
  132. } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
  133. mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  134. "invalid syntax for integer with base %d", base);
  135. raise_exc(exc, lex);
  136. } else {
  137. vstr_t vstr;
  138. mp_print_t print;
  139. vstr_init_print(&vstr, 50, &print);
  140. mp_printf(&print, "invalid syntax for integer with base %d: ", base);
  141. mp_str_print_quoted(&print, str_val_start, top - str_val_start, true);
  142. mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError,
  143. mp_obj_new_str_from_vstr(&mp_type_str, &vstr));
  144. raise_exc(exc, lex);
  145. }
  146. }
  147. typedef enum {
  148. PARSE_DEC_IN_INTG,
  149. PARSE_DEC_IN_FRAC,
  150. PARSE_DEC_IN_EXP,
  151. } parse_dec_in_t;
  152. mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) {
  153. #if MICROPY_PY_BUILTINS_FLOAT
  154. // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing
  155. // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float
  156. // EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float
  157. // Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n
  158. // so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's
  159. // exponent).
  160. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  161. #define DEC_VAL_MAX 1e20F
  162. #define SMALL_NORMAL_VAL (1e-37F)
  163. #define SMALL_NORMAL_EXP (-37)
  164. #define EXACT_POWER_OF_10 (9)
  165. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  166. #define DEC_VAL_MAX 1e200
  167. #define SMALL_NORMAL_VAL (1e-307)
  168. #define SMALL_NORMAL_EXP (-307)
  169. #define EXACT_POWER_OF_10 (22)
  170. #endif
  171. const char *top = str + len;
  172. mp_float_t dec_val = 0;
  173. bool dec_neg = false;
  174. bool imag = false;
  175. // skip leading space
  176. for (; str < top && unichar_isspace(*str); str++) {
  177. }
  178. // parse optional sign
  179. if (str < top) {
  180. if (*str == '+') {
  181. str++;
  182. } else if (*str == '-') {
  183. str++;
  184. dec_neg = true;
  185. }
  186. }
  187. const char *str_val_start = str;
  188. // determine what the string is
  189. if (str < top && (str[0] | 0x20) == 'i') {
  190. // string starts with 'i', should be 'inf' or 'infinity' (case insensitive)
  191. if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') {
  192. // inf
  193. str += 3;
  194. dec_val = INFINITY;
  195. if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') {
  196. // infinity
  197. str += 5;
  198. }
  199. }
  200. } else if (str < top && (str[0] | 0x20) == 'n') {
  201. // string starts with 'n', should be 'nan' (case insensitive)
  202. if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') {
  203. // NaN
  204. str += 3;
  205. dec_val = MICROPY_FLOAT_C_FUN(nan)("");
  206. }
  207. } else {
  208. // string should be a decimal number
  209. parse_dec_in_t in = PARSE_DEC_IN_INTG;
  210. bool exp_neg = false;
  211. int exp_val = 0;
  212. int exp_extra = 0;
  213. while (str < top) {
  214. unsigned int dig = *str++;
  215. if ('0' <= dig && dig <= '9') {
  216. dig -= '0';
  217. if (in == PARSE_DEC_IN_EXP) {
  218. // don't overflow exp_val when adding next digit, instead just truncate
  219. // it and the resulting float will still be correct, either inf or 0.0
  220. // (use INT_MAX/2 to allow adding exp_extra at the end without overflow)
  221. if (exp_val < (INT_MAX / 2 - 9) / 10) {
  222. exp_val = 10 * exp_val + dig;
  223. }
  224. } else {
  225. if (dec_val < DEC_VAL_MAX) {
  226. // dec_val won't overflow so keep accumulating
  227. dec_val = 10 * dec_val + dig;
  228. if (in == PARSE_DEC_IN_FRAC) {
  229. --exp_extra;
  230. }
  231. } else {
  232. // dec_val might overflow and we anyway can't represent more digits
  233. // of precision, so ignore the digit and just adjust the exponent
  234. if (in == PARSE_DEC_IN_INTG) {
  235. ++exp_extra;
  236. }
  237. }
  238. }
  239. } else if (in == PARSE_DEC_IN_INTG && dig == '.') {
  240. in = PARSE_DEC_IN_FRAC;
  241. } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) {
  242. in = PARSE_DEC_IN_EXP;
  243. if (str < top) {
  244. if (str[0] == '+') {
  245. str++;
  246. } else if (str[0] == '-') {
  247. str++;
  248. exp_neg = true;
  249. }
  250. }
  251. if (str == top) {
  252. goto value_error;
  253. }
  254. } else if (allow_imag && (dig | 0x20) == 'j') {
  255. imag = true;
  256. break;
  257. } else if (dig == '_') {
  258. continue;
  259. } else {
  260. // unknown character
  261. str--;
  262. break;
  263. }
  264. }
  265. // work out the exponent
  266. if (exp_neg) {
  267. exp_val = -exp_val;
  268. }
  269. // apply the exponent, making sure it's not a subnormal value
  270. exp_val += exp_extra;
  271. if (exp_val < SMALL_NORMAL_EXP) {
  272. exp_val -= SMALL_NORMAL_EXP;
  273. dec_val *= SMALL_NORMAL_VAL;
  274. }
  275. // At this point, we need to multiply the mantissa by its base 10 exponent. If possible,
  276. // we would rather manipulate numbers that have an exact representation in IEEE754. It
  277. // turns out small positive powers of 10 do, whereas small negative powers of 10 don't.
  278. // So in that case, we'll yield a division of exact values rather than a multiplication
  279. // of slightly erroneous values.
  280. if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) {
  281. dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val);
  282. } else {
  283. dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val);
  284. }
  285. }
  286. // negate value if needed
  287. if (dec_neg) {
  288. dec_val = -dec_val;
  289. }
  290. // check we parsed something
  291. if (str == str_val_start) {
  292. goto value_error;
  293. }
  294. // skip trailing space
  295. for (; str < top && unichar_isspace(*str); str++) {
  296. }
  297. // check we reached the end of the string
  298. if (str != top) {
  299. goto value_error;
  300. }
  301. // return the object
  302. #if MICROPY_PY_BUILTINS_COMPLEX
  303. if (imag) {
  304. return mp_obj_new_complex(0, dec_val);
  305. } else if (force_complex) {
  306. return mp_obj_new_complex(dec_val, 0);
  307. }
  308. #else
  309. if (imag || force_complex) {
  310. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "complex values not supported"), lex);
  311. }
  312. #endif
  313. else {
  314. return mp_obj_new_float(dec_val);
  315. }
  316. value_error:
  317. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid syntax for number"), lex);
  318. #else
  319. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "decimal numbers not supported"), lex);
  320. #endif
  321. }