json.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*************************************************************************/
  2. /* json.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "json.h"
  31. #include "print_string.h"
  32. const char *JSON::tk_name[TK_MAX] = {
  33. "'{'",
  34. "'}'",
  35. "'['",
  36. "']'",
  37. "identifier",
  38. "string",
  39. "number",
  40. "':'",
  41. "','",
  42. "EOF",
  43. };
  44. String JSON::_print_var(const Variant &p_var) {
  45. switch (p_var.get_type()) {
  46. case Variant::NIL: return "null";
  47. case Variant::BOOL: return p_var.operator bool() ? "true" : "false";
  48. case Variant::INT: return itos(p_var);
  49. case Variant::REAL: return rtos(p_var);
  50. case Variant::INT_ARRAY:
  51. case Variant::REAL_ARRAY:
  52. case Variant::STRING_ARRAY:
  53. case Variant::ARRAY: {
  54. String s = "[";
  55. Array a = p_var;
  56. for (int i = 0; i < a.size(); i++) {
  57. if (i > 0)
  58. s += ", ";
  59. s += _print_var(a[i]);
  60. }
  61. s += "]";
  62. return s;
  63. };
  64. case Variant::DICTIONARY: {
  65. String s = "{";
  66. Dictionary d = p_var;
  67. List<Variant> keys;
  68. d.get_key_list(&keys);
  69. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  70. if (E != keys.front())
  71. s += ", ";
  72. s += _print_var(String(E->get()));
  73. s += ":";
  74. s += _print_var(d[E->get()]);
  75. }
  76. s += "}";
  77. return s;
  78. };
  79. default: return "\"" + String(p_var).json_escape() + "\"";
  80. }
  81. }
  82. String JSON::print(const Dictionary &p_dict) {
  83. return _print_var(p_dict);
  84. }
  85. Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) {
  86. while (true) {
  87. switch (p_str[idx]) {
  88. case '\n': {
  89. line++;
  90. idx++;
  91. break;
  92. };
  93. case 0: {
  94. r_token.type = TK_EOF;
  95. return OK;
  96. } break;
  97. case '{': {
  98. r_token.type = TK_CURLY_BRACKET_OPEN;
  99. idx++;
  100. return OK;
  101. };
  102. case '}': {
  103. r_token.type = TK_CURLY_BRACKET_CLOSE;
  104. idx++;
  105. return OK;
  106. };
  107. case '[': {
  108. r_token.type = TK_BRACKET_OPEN;
  109. idx++;
  110. return OK;
  111. };
  112. case ']': {
  113. r_token.type = TK_BRACKET_CLOSE;
  114. idx++;
  115. return OK;
  116. };
  117. case ':': {
  118. r_token.type = TK_COLON;
  119. idx++;
  120. return OK;
  121. };
  122. case ',': {
  123. r_token.type = TK_COMMA;
  124. idx++;
  125. return OK;
  126. };
  127. case '"': {
  128. idx++;
  129. String str;
  130. while (true) {
  131. if (p_str[idx] == 0) {
  132. r_err_str = "Unterminated String";
  133. return ERR_PARSE_ERROR;
  134. } else if (p_str[idx] == '"') {
  135. idx++;
  136. break;
  137. } else if (p_str[idx] == '\\') {
  138. //escaped characters...
  139. idx++;
  140. CharType next = p_str[idx];
  141. if (next == 0) {
  142. r_err_str = "Unterminated String";
  143. return ERR_PARSE_ERROR;
  144. }
  145. CharType res = 0;
  146. switch (next) {
  147. case 'b': res = 8; break;
  148. case 't': res = 9; break;
  149. case 'n': res = 10; break;
  150. case 'f': res = 12; break;
  151. case 'r': res = 13; break;
  152. case 'u': {
  153. //hexnumbarh - oct is deprecated
  154. for (int j = 0; j < 4; j++) {
  155. CharType c = p_str[idx + j + 1];
  156. if (c == 0) {
  157. r_err_str = "Unterminated String";
  158. return ERR_PARSE_ERROR;
  159. }
  160. if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
  161. r_err_str = "Malformed hex constant in string";
  162. return ERR_PARSE_ERROR;
  163. }
  164. CharType v;
  165. if (c >= '0' && c <= '9') {
  166. v = c - '0';
  167. } else if (c >= 'a' && c <= 'f') {
  168. v = c - 'a';
  169. v += 10;
  170. } else if (c >= 'A' && c <= 'F') {
  171. v = c - 'A';
  172. v += 10;
  173. } else {
  174. ERR_PRINT("BUG");
  175. v = 0;
  176. }
  177. res <<= 4;
  178. res |= v;
  179. }
  180. idx += 4; //will add at the end anyway
  181. } break;
  182. //case '\"': res='\"'; break;
  183. //case '\\': res='\\'; break;
  184. //case '/': res='/'; break;
  185. default: {
  186. res = next;
  187. //r_err_str="Invalid escape sequence";
  188. //return ERR_PARSE_ERROR;
  189. } break;
  190. }
  191. str += res;
  192. } else {
  193. if (p_str[idx] == '\n')
  194. line++;
  195. str += p_str[idx];
  196. }
  197. idx++;
  198. }
  199. r_token.type = TK_STRING;
  200. r_token.value = str;
  201. return OK;
  202. } break;
  203. default: {
  204. if (p_str[idx] <= 32) {
  205. idx++;
  206. break;
  207. }
  208. if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) {
  209. //a number
  210. const CharType *rptr;
  211. double number = String::to_double(&p_str[idx], &rptr);
  212. idx += (rptr - &p_str[idx]);
  213. r_token.type = TK_NUMBER;
  214. r_token.value = number;
  215. return OK;
  216. } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
  217. String id;
  218. while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
  219. id += p_str[idx];
  220. idx++;
  221. }
  222. r_token.type = TK_IDENTIFIER;
  223. r_token.value = id;
  224. return OK;
  225. } else {
  226. r_err_str = "Unexpected character.";
  227. return ERR_PARSE_ERROR;
  228. }
  229. }
  230. }
  231. }
  232. return ERR_PARSE_ERROR;
  233. }
  234. Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  235. if (token.type == TK_CURLY_BRACKET_OPEN) {
  236. Dictionary d(true);
  237. Error err = _parse_object(d, p_str, index, p_len, line, r_err_str);
  238. if (err)
  239. return err;
  240. value = d;
  241. return OK;
  242. } else if (token.type == TK_BRACKET_OPEN) {
  243. Array a(true);
  244. Error err = _parse_array(a, p_str, index, p_len, line, r_err_str);
  245. if (err)
  246. return err;
  247. value = a;
  248. return OK;
  249. } else if (token.type == TK_IDENTIFIER) {
  250. String id = token.value;
  251. if (id == "true")
  252. value = true;
  253. else if (id == "false")
  254. value = false;
  255. else if (id == "null")
  256. value = Variant();
  257. else {
  258. r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
  259. return ERR_PARSE_ERROR;
  260. }
  261. return OK;
  262. } else if (token.type == TK_NUMBER) {
  263. value = token.value;
  264. return OK;
  265. } else if (token.type == TK_STRING) {
  266. value = token.value;
  267. return OK;
  268. } else {
  269. r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
  270. return ERR_PARSE_ERROR;
  271. }
  272. return ERR_PARSE_ERROR;
  273. }
  274. Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  275. Token token;
  276. bool need_comma = false;
  277. while (index < p_len) {
  278. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  279. if (err != OK)
  280. return err;
  281. if (token.type == TK_BRACKET_CLOSE) {
  282. return OK;
  283. }
  284. if (need_comma) {
  285. if (token.type != TK_COMMA) {
  286. r_err_str = "Expected ','";
  287. return ERR_PARSE_ERROR;
  288. } else {
  289. need_comma = false;
  290. continue;
  291. }
  292. }
  293. Variant v;
  294. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  295. if (err)
  296. return err;
  297. array.push_back(v);
  298. need_comma = true;
  299. }
  300. return ERR_PARSE_ERROR;
  301. }
  302. Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  303. bool at_key = true;
  304. String key;
  305. Token token;
  306. bool need_comma = false;
  307. while (index < p_len) {
  308. if (at_key) {
  309. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  310. if (err != OK)
  311. return err;
  312. if (token.type == TK_CURLY_BRACKET_CLOSE) {
  313. return OK;
  314. }
  315. if (need_comma) {
  316. if (token.type != TK_COMMA) {
  317. r_err_str = "Expected '}' or ','";
  318. return ERR_PARSE_ERROR;
  319. } else {
  320. need_comma = false;
  321. continue;
  322. }
  323. }
  324. if (token.type != TK_STRING) {
  325. r_err_str = "Expected key";
  326. return ERR_PARSE_ERROR;
  327. }
  328. key = token.value;
  329. err = _get_token(p_str, index, p_len, token, line, r_err_str);
  330. if (err != OK)
  331. return err;
  332. if (token.type != TK_COLON) {
  333. r_err_str = "Expected ':'";
  334. return ERR_PARSE_ERROR;
  335. }
  336. at_key = false;
  337. } else {
  338. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  339. if (err != OK)
  340. return err;
  341. Variant v;
  342. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  343. if (err)
  344. return err;
  345. object[key] = v;
  346. need_comma = true;
  347. at_key = true;
  348. }
  349. }
  350. return ERR_PARSE_ERROR;
  351. }
  352. Error JSON::parse(const String &p_json, Dictionary &r_ret, String &r_err_str, int &r_err_line) {
  353. const CharType *str = p_json.ptr();
  354. int idx = 0;
  355. int len = p_json.length();
  356. Token token;
  357. int line = 0;
  358. String aux_key;
  359. Error err = _get_token(str, idx, len, token, line, r_err_str);
  360. if (err)
  361. return err;
  362. if (token.type != TK_CURLY_BRACKET_OPEN) {
  363. r_err_str = "Expected '{'";
  364. return ERR_PARSE_ERROR;
  365. }
  366. return _parse_object(r_ret, str, idx, len, r_err_line, r_err_str);
  367. }