parsenum.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  157. #define DEC_VAL_MAX 1e20F
  158. #define SMALL_NORMAL_VAL (1e-37F)
  159. #define SMALL_NORMAL_EXP (-37)
  160. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  161. #define DEC_VAL_MAX 1e200
  162. #define SMALL_NORMAL_VAL (1e-307)
  163. #define SMALL_NORMAL_EXP (-307)
  164. #endif
  165. const char *top = str + len;
  166. mp_float_t dec_val = 0;
  167. bool dec_neg = false;
  168. bool imag = false;
  169. // skip leading space
  170. for (; str < top && unichar_isspace(*str); str++) {
  171. }
  172. // parse optional sign
  173. if (str < top) {
  174. if (*str == '+') {
  175. str++;
  176. } else if (*str == '-') {
  177. str++;
  178. dec_neg = true;
  179. }
  180. }
  181. const char *str_val_start = str;
  182. // determine what the string is
  183. if (str < top && (str[0] | 0x20) == 'i') {
  184. // string starts with 'i', should be 'inf' or 'infinity' (case insensitive)
  185. if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') {
  186. // inf
  187. str += 3;
  188. dec_val = INFINITY;
  189. if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') {
  190. // infinity
  191. str += 5;
  192. }
  193. }
  194. } else if (str < top && (str[0] | 0x20) == 'n') {
  195. // string starts with 'n', should be 'nan' (case insensitive)
  196. if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') {
  197. // NaN
  198. str += 3;
  199. dec_val = MICROPY_FLOAT_C_FUN(nan)("");
  200. }
  201. } else {
  202. // string should be a decimal number
  203. parse_dec_in_t in = PARSE_DEC_IN_INTG;
  204. bool exp_neg = false;
  205. int exp_val = 0;
  206. int exp_extra = 0;
  207. while (str < top) {
  208. unsigned int dig = *str++;
  209. if ('0' <= dig && dig <= '9') {
  210. dig -= '0';
  211. if (in == PARSE_DEC_IN_EXP) {
  212. // don't overflow exp_val when adding next digit, instead just truncate
  213. // it and the resulting float will still be correct, either inf or 0.0
  214. // (use INT_MAX/2 to allow adding exp_extra at the end without overflow)
  215. if (exp_val < (INT_MAX / 2 - 9) / 10) {
  216. exp_val = 10 * exp_val + dig;
  217. }
  218. } else {
  219. if (dec_val < DEC_VAL_MAX) {
  220. // dec_val won't overflow so keep accumulating
  221. dec_val = 10 * dec_val + dig;
  222. if (in == PARSE_DEC_IN_FRAC) {
  223. --exp_extra;
  224. }
  225. } else {
  226. // dec_val might overflow and we anyway can't represent more digits
  227. // of precision, so ignore the digit and just adjust the exponent
  228. if (in == PARSE_DEC_IN_INTG) {
  229. ++exp_extra;
  230. }
  231. }
  232. }
  233. } else if (in == PARSE_DEC_IN_INTG && dig == '.') {
  234. in = PARSE_DEC_IN_FRAC;
  235. } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) {
  236. in = PARSE_DEC_IN_EXP;
  237. if (str < top) {
  238. if (str[0] == '+') {
  239. str++;
  240. } else if (str[0] == '-') {
  241. str++;
  242. exp_neg = true;
  243. }
  244. }
  245. if (str == top) {
  246. goto value_error;
  247. }
  248. } else if (allow_imag && (dig | 0x20) == 'j') {
  249. imag = true;
  250. break;
  251. } else if (dig == '_') {
  252. continue;
  253. } else {
  254. // unknown character
  255. str--;
  256. break;
  257. }
  258. }
  259. // work out the exponent
  260. if (exp_neg) {
  261. exp_val = -exp_val;
  262. }
  263. // apply the exponent, making sure it's not a subnormal value
  264. exp_val += exp_extra;
  265. if (exp_val < SMALL_NORMAL_EXP) {
  266. exp_val -= SMALL_NORMAL_EXP;
  267. dec_val *= SMALL_NORMAL_VAL;
  268. }
  269. dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val);
  270. }
  271. // negate value if needed
  272. if (dec_neg) {
  273. dec_val = -dec_val;
  274. }
  275. // check we parsed something
  276. if (str == str_val_start) {
  277. goto value_error;
  278. }
  279. // skip trailing space
  280. for (; str < top && unichar_isspace(*str); str++) {
  281. }
  282. // check we reached the end of the string
  283. if (str != top) {
  284. goto value_error;
  285. }
  286. // return the object
  287. #if MICROPY_PY_BUILTINS_COMPLEX
  288. if (imag) {
  289. return mp_obj_new_complex(0, dec_val);
  290. } else if (force_complex) {
  291. return mp_obj_new_complex(dec_val, 0);
  292. }
  293. #else
  294. if (imag || force_complex) {
  295. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "complex values not supported"), lex);
  296. }
  297. #endif
  298. else {
  299. return mp_obj_new_float(dec_val);
  300. }
  301. value_error:
  302. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid syntax for number"), lex);
  303. #else
  304. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "decimal numbers not supported"), lex);
  305. #endif
  306. }