modujson.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2014-2016 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 <stdio.h>
  27. #include "py/objlist.h"
  28. #include "py/objstringio.h"
  29. #include "py/parsenum.h"
  30. #include "py/runtime.h"
  31. #include "py/stream.h"
  32. #if MICROPY_PY_UJSON
  33. STATIC mp_obj_t mod_ujson_dump(mp_obj_t obj, mp_obj_t stream) {
  34. mp_get_stream_raise(stream, MP_STREAM_OP_WRITE);
  35. mp_print_t print = {MP_OBJ_TO_PTR(stream), mp_stream_write_adaptor};
  36. mp_obj_print_helper(&print, obj, PRINT_JSON);
  37. return mp_const_none;
  38. }
  39. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ujson_dump_obj, mod_ujson_dump);
  40. STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) {
  41. vstr_t vstr;
  42. mp_print_t print;
  43. vstr_init_print(&vstr, 8, &print);
  44. mp_obj_print_helper(&print, obj, PRINT_JSON);
  45. return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
  46. }
  47. STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_dumps_obj, mod_ujson_dumps);
  48. // The function below implements a simple non-recursive JSON parser.
  49. //
  50. // The JSON specification is at http://www.ietf.org/rfc/rfc4627.txt
  51. // The parser here will parse any valid JSON and return the correct
  52. // corresponding Python object. It allows through a superset of JSON, since
  53. // it treats commas and colons as "whitespace", and doesn't care if
  54. // brackets/braces are correctly paired. It will raise a ValueError if the
  55. // input is outside it's specs.
  56. //
  57. // Most of the work is parsing the primitives (null, false, true, numbers,
  58. // strings). It does 1 pass over the input stream. It tries to be fast and
  59. // small in code size, while not using more RAM than necessary.
  60. typedef struct _ujson_stream_t {
  61. mp_obj_t stream_obj;
  62. mp_uint_t (*read)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode);
  63. int errcode;
  64. byte cur;
  65. } ujson_stream_t;
  66. #define S_EOF (0) // null is not allowed in json stream so is ok as EOF marker
  67. #define S_END(s) ((s).cur == S_EOF)
  68. #define S_CUR(s) ((s).cur)
  69. #define S_NEXT(s) (ujson_stream_next(&(s)))
  70. STATIC byte ujson_stream_next(ujson_stream_t *s) {
  71. mp_uint_t ret = s->read(s->stream_obj, &s->cur, 1, &s->errcode);
  72. if (s->errcode != 0) {
  73. mp_raise_OSError(s->errcode);
  74. }
  75. if (ret == 0) {
  76. s->cur = S_EOF;
  77. }
  78. return s->cur;
  79. }
  80. STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
  81. const mp_stream_p_t *stream_p = mp_get_stream_raise(stream_obj, MP_STREAM_OP_READ);
  82. ujson_stream_t s = {stream_obj, stream_p->read, 0, 0};
  83. vstr_t vstr;
  84. vstr_init(&vstr, 8);
  85. mp_obj_list_t stack; // we use a list as a simple stack for nested JSON
  86. stack.len = 0;
  87. stack.items = NULL;
  88. mp_obj_t stack_top = MP_OBJ_NULL;
  89. mp_obj_type_t *stack_top_type = NULL;
  90. mp_obj_t stack_key = MP_OBJ_NULL;
  91. S_NEXT(s);
  92. for (;;) {
  93. cont:
  94. if (S_END(s)) {
  95. break;
  96. }
  97. mp_obj_t next = MP_OBJ_NULL;
  98. bool enter = false;
  99. byte cur = S_CUR(s);
  100. S_NEXT(s);
  101. switch (cur) {
  102. case ',':
  103. case ':':
  104. case ' ':
  105. case '\t':
  106. case '\n':
  107. case '\r':
  108. goto cont;
  109. case 'n':
  110. if (S_CUR(s) == 'u' && S_NEXT(s) == 'l' && S_NEXT(s) == 'l') {
  111. S_NEXT(s);
  112. next = mp_const_none;
  113. } else {
  114. goto fail;
  115. }
  116. break;
  117. case 'f':
  118. if (S_CUR(s) == 'a' && S_NEXT(s) == 'l' && S_NEXT(s) == 's' && S_NEXT(s) == 'e') {
  119. S_NEXT(s);
  120. next = mp_const_false;
  121. } else {
  122. goto fail;
  123. }
  124. break;
  125. case 't':
  126. if (S_CUR(s) == 'r' && S_NEXT(s) == 'u' && S_NEXT(s) == 'e') {
  127. S_NEXT(s);
  128. next = mp_const_true;
  129. } else {
  130. goto fail;
  131. }
  132. break;
  133. case '"':
  134. vstr_reset(&vstr);
  135. for (; !S_END(s) && S_CUR(s) != '"';) {
  136. byte c = S_CUR(s);
  137. if (c == '\\') {
  138. c = S_NEXT(s);
  139. switch (c) {
  140. case 'b': c = 0x08; break;
  141. case 'f': c = 0x0c; break;
  142. case 'n': c = 0x0a; break;
  143. case 'r': c = 0x0d; break;
  144. case 't': c = 0x09; break;
  145. case 'u': {
  146. mp_uint_t num = 0;
  147. for (int i = 0; i < 4; i++) {
  148. c = (S_NEXT(s) | 0x20) - '0';
  149. if (c > 9) {
  150. c -= ('a' - ('9' + 1));
  151. }
  152. num = (num << 4) | c;
  153. }
  154. vstr_add_char(&vstr, num);
  155. goto str_cont;
  156. }
  157. }
  158. }
  159. vstr_add_byte(&vstr, c);
  160. str_cont:
  161. S_NEXT(s);
  162. }
  163. if (S_END(s)) {
  164. goto fail;
  165. }
  166. S_NEXT(s);
  167. next = mp_obj_new_str(vstr.buf, vstr.len);
  168. break;
  169. case '-':
  170. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': {
  171. bool flt = false;
  172. vstr_reset(&vstr);
  173. for (;;) {
  174. vstr_add_byte(&vstr, cur);
  175. cur = S_CUR(s);
  176. if (cur == '.' || cur == 'E' || cur == 'e') {
  177. flt = true;
  178. } else if (cur == '-' || unichar_isdigit(cur)) {
  179. // pass
  180. } else {
  181. break;
  182. }
  183. S_NEXT(s);
  184. }
  185. if (flt) {
  186. next = mp_parse_num_decimal(vstr.buf, vstr.len, false, false, NULL);
  187. } else {
  188. next = mp_parse_num_integer(vstr.buf, vstr.len, 10, NULL);
  189. }
  190. break;
  191. }
  192. case '[':
  193. next = mp_obj_new_list(0, NULL);
  194. enter = true;
  195. break;
  196. case '{':
  197. next = mp_obj_new_dict(0);
  198. enter = true;
  199. break;
  200. case '}':
  201. case ']': {
  202. if (stack_top == MP_OBJ_NULL) {
  203. // no object at all
  204. goto fail;
  205. }
  206. if (stack.len == 0) {
  207. // finished; compound object
  208. goto success;
  209. }
  210. stack.len -= 1;
  211. stack_top = stack.items[stack.len];
  212. stack_top_type = mp_obj_get_type(stack_top);
  213. goto cont;
  214. }
  215. default:
  216. goto fail;
  217. }
  218. if (stack_top == MP_OBJ_NULL) {
  219. stack_top = next;
  220. stack_top_type = mp_obj_get_type(stack_top);
  221. if (!enter) {
  222. // finished; single primitive only
  223. goto success;
  224. }
  225. } else {
  226. // append to list or dict
  227. if (stack_top_type == &mp_type_list) {
  228. mp_obj_list_append(stack_top, next);
  229. } else {
  230. if (stack_key == MP_OBJ_NULL) {
  231. stack_key = next;
  232. if (enter) {
  233. goto fail;
  234. }
  235. } else {
  236. mp_obj_dict_store(stack_top, stack_key, next);
  237. stack_key = MP_OBJ_NULL;
  238. }
  239. }
  240. if (enter) {
  241. if (stack.items == NULL) {
  242. mp_obj_list_init(&stack, 1);
  243. stack.items[0] = stack_top;
  244. } else {
  245. mp_obj_list_append(MP_OBJ_FROM_PTR(&stack), stack_top);
  246. }
  247. stack_top = next;
  248. stack_top_type = mp_obj_get_type(stack_top);
  249. }
  250. }
  251. }
  252. success:
  253. // eat trailing whitespace
  254. while (unichar_isspace(S_CUR(s))) {
  255. S_NEXT(s);
  256. }
  257. if (!S_END(s)) {
  258. // unexpected chars
  259. goto fail;
  260. }
  261. if (stack_top == MP_OBJ_NULL || stack.len != 0) {
  262. // not exactly 1 object
  263. goto fail;
  264. }
  265. vstr_clear(&vstr);
  266. return stack_top;
  267. fail:
  268. mp_raise_ValueError("syntax error in JSON");
  269. }
  270. STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load);
  271. STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) {
  272. size_t len;
  273. const char *buf = mp_obj_str_get_data(obj, &len);
  274. vstr_t vstr = {len, len, (char*)buf, true};
  275. mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL};
  276. return mod_ujson_load(MP_OBJ_FROM_PTR(&sio));
  277. }
  278. STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_loads_obj, mod_ujson_loads);
  279. STATIC const mp_rom_map_elem_t mp_module_ujson_globals_table[] = {
  280. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ujson) },
  281. { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_ujson_dump_obj) },
  282. { MP_ROM_QSTR(MP_QSTR_dumps), MP_ROM_PTR(&mod_ujson_dumps_obj) },
  283. { MP_ROM_QSTR(MP_QSTR_load), MP_ROM_PTR(&mod_ujson_load_obj) },
  284. { MP_ROM_QSTR(MP_QSTR_loads), MP_ROM_PTR(&mod_ujson_loads_obj) },
  285. };
  286. STATIC MP_DEFINE_CONST_DICT(mp_module_ujson_globals, mp_module_ujson_globals_table);
  287. const mp_obj_module_t mp_module_ujson = {
  288. .base = { &mp_type_module },
  289. .globals = (mp_obj_dict_t*)&mp_module_ujson_globals,
  290. };
  291. #endif //MICROPY_PY_UJSON