parsenum.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 {
  77. dig |= 0x20; // make digit lower-case
  78. if ('a' <= dig && dig <= 'z') {
  79. dig -= 'a' - 10;
  80. } else {
  81. // unknown character
  82. break;
  83. }
  84. }
  85. if (dig >= (mp_uint_t)base) {
  86. break;
  87. }
  88. // add next digi and check for overflow
  89. if (mp_small_int_mul_overflow(int_val, base)) {
  90. goto overflow;
  91. }
  92. int_val = int_val * base + dig;
  93. if (!MP_SMALL_INT_FITS(int_val)) {
  94. goto overflow;
  95. }
  96. }
  97. // negate value if needed
  98. if (neg) {
  99. int_val = -int_val;
  100. }
  101. // create the small int
  102. ret_val = MP_OBJ_NEW_SMALL_INT(int_val);
  103. have_ret_val:
  104. // check we parsed something
  105. if (str == str_val_start) {
  106. goto value_error;
  107. }
  108. // skip trailing space
  109. for (; str < top && unichar_isspace(*str); str++) {
  110. }
  111. // check we reached the end of the string
  112. if (str != top) {
  113. goto value_error;
  114. }
  115. // return the object
  116. return ret_val;
  117. overflow:
  118. // reparse using long int
  119. {
  120. const char *s2 = (const char*)str_val_start;
  121. ret_val = mp_obj_new_int_from_str_len(&s2, top - str_val_start, neg, base);
  122. str = (const byte*)s2;
  123. goto have_ret_val;
  124. }
  125. value_error:
  126. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  127. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError,
  128. "invalid syntax for integer");
  129. raise_exc(exc, lex);
  130. } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
  131. mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  132. "invalid syntax for integer with base %d", base);
  133. raise_exc(exc, lex);
  134. } else {
  135. vstr_t vstr;
  136. mp_print_t print;
  137. vstr_init_print(&vstr, 50, &print);
  138. mp_printf(&print, "invalid syntax for integer with base %d: ", base);
  139. mp_str_print_quoted(&print, str_val_start, top - str_val_start, true);
  140. mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError,
  141. mp_obj_new_str_from_vstr(&mp_type_str, &vstr));
  142. raise_exc(exc, lex);
  143. }
  144. }
  145. typedef enum {
  146. PARSE_DEC_IN_INTG,
  147. PARSE_DEC_IN_FRAC,
  148. PARSE_DEC_IN_EXP,
  149. } parse_dec_in_t;
  150. mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) {
  151. #if MICROPY_PY_BUILTINS_FLOAT
  152. const char *top = str + len;
  153. mp_float_t dec_val = 0;
  154. bool dec_neg = false;
  155. bool imag = false;
  156. // skip leading space
  157. for (; str < top && unichar_isspace(*str); str++) {
  158. }
  159. // parse optional sign
  160. if (str < top) {
  161. if (*str == '+') {
  162. str++;
  163. } else if (*str == '-') {
  164. str++;
  165. dec_neg = true;
  166. }
  167. }
  168. const char *str_val_start = str;
  169. // determine what the string is
  170. if (str < top && (str[0] | 0x20) == 'i') {
  171. // string starts with 'i', should be 'inf' or 'infinity' (case insensitive)
  172. if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') {
  173. // inf
  174. str += 3;
  175. dec_val = INFINITY;
  176. if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') {
  177. // infinity
  178. str += 5;
  179. }
  180. }
  181. } else if (str < top && (str[0] | 0x20) == 'n') {
  182. // string starts with 'n', should be 'nan' (case insensitive)
  183. if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') {
  184. // NaN
  185. str += 3;
  186. dec_val = MICROPY_FLOAT_C_FUN(nan)("");
  187. }
  188. } else {
  189. // string should be a decimal number
  190. parse_dec_in_t in = PARSE_DEC_IN_INTG;
  191. bool exp_neg = false;
  192. mp_float_t frac_mult = 0.1;
  193. mp_int_t exp_val = 0;
  194. while (str < top) {
  195. mp_uint_t dig = *str++;
  196. if ('0' <= dig && dig <= '9') {
  197. dig -= '0';
  198. if (in == PARSE_DEC_IN_EXP) {
  199. exp_val = 10 * exp_val + dig;
  200. } else {
  201. if (in == PARSE_DEC_IN_FRAC) {
  202. dec_val += dig * frac_mult;
  203. frac_mult *= MICROPY_FLOAT_CONST(0.1);
  204. } else {
  205. dec_val = 10 * dec_val + dig;
  206. }
  207. }
  208. } else if (in == PARSE_DEC_IN_INTG && dig == '.') {
  209. in = PARSE_DEC_IN_FRAC;
  210. } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) {
  211. in = PARSE_DEC_IN_EXP;
  212. if (str < top) {
  213. if (str[0] == '+') {
  214. str++;
  215. } else if (str[0] == '-') {
  216. str++;
  217. exp_neg = true;
  218. }
  219. }
  220. if (str == top) {
  221. goto value_error;
  222. }
  223. } else if (allow_imag && (dig | 0x20) == 'j') {
  224. imag = true;
  225. break;
  226. } else {
  227. // unknown character
  228. str--;
  229. break;
  230. }
  231. }
  232. // work out the exponent
  233. if (exp_neg) {
  234. exp_val = -exp_val;
  235. }
  236. // apply the exponent
  237. dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val);
  238. }
  239. // negate value if needed
  240. if (dec_neg) {
  241. dec_val = -dec_val;
  242. }
  243. // check we parsed something
  244. if (str == str_val_start) {
  245. goto value_error;
  246. }
  247. // skip trailing space
  248. for (; str < top && unichar_isspace(*str); str++) {
  249. }
  250. // check we reached the end of the string
  251. if (str != top) {
  252. goto value_error;
  253. }
  254. // return the object
  255. #if MICROPY_PY_BUILTINS_COMPLEX
  256. if (imag) {
  257. return mp_obj_new_complex(0, dec_val);
  258. } else if (force_complex) {
  259. return mp_obj_new_complex(dec_val, 0);
  260. #else
  261. if (imag || force_complex) {
  262. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "complex values not supported"), lex);
  263. #endif
  264. } else {
  265. return mp_obj_new_float(dec_val);
  266. }
  267. value_error:
  268. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid syntax for number"), lex);
  269. #else
  270. raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "decimal numbers not supported"), lex);
  271. #endif
  272. }