json.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*************************************************************************/
  2. /* json.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "core/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. static String _make_indent(const String &p_indent, int p_size) {
  45. String indent_text = "";
  46. if (!p_indent.empty()) {
  47. for (int i = 0; i < p_size; i++)
  48. indent_text += p_indent;
  49. }
  50. return indent_text;
  51. }
  52. String JSON::_print_var(const Variant &p_var, const String &p_indent, int p_cur_indent, bool p_sort_keys) {
  53. String colon = ":";
  54. String end_statement = "";
  55. if (!p_indent.empty()) {
  56. colon += " ";
  57. end_statement += "\n";
  58. }
  59. switch (p_var.get_type()) {
  60. case Variant::NIL:
  61. return "null";
  62. case Variant::BOOL:
  63. return p_var.operator bool() ? "true" : "false";
  64. case Variant::INT:
  65. return itos(p_var);
  66. case Variant::REAL:
  67. return rtos(p_var);
  68. case Variant::POOL_INT_ARRAY:
  69. case Variant::POOL_REAL_ARRAY:
  70. case Variant::POOL_STRING_ARRAY:
  71. case Variant::ARRAY: {
  72. String s = "[";
  73. s += end_statement;
  74. Array a = p_var;
  75. for (int i = 0; i < a.size(); i++) {
  76. if (i > 0) {
  77. s += ",";
  78. s += end_statement;
  79. }
  80. s += _make_indent(p_indent, p_cur_indent + 1) + _print_var(a[i], p_indent, p_cur_indent + 1, p_sort_keys);
  81. }
  82. s += end_statement + _make_indent(p_indent, p_cur_indent) + "]";
  83. return s;
  84. };
  85. case Variant::DICTIONARY: {
  86. String s = "{";
  87. s += end_statement;
  88. Dictionary d = p_var;
  89. List<Variant> keys;
  90. d.get_key_list(&keys);
  91. if (p_sort_keys)
  92. keys.sort();
  93. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  94. if (E != keys.front()) {
  95. s += ",";
  96. s += end_statement;
  97. }
  98. s += _make_indent(p_indent, p_cur_indent + 1) + _print_var(String(E->get()), p_indent, p_cur_indent + 1, p_sort_keys);
  99. s += colon;
  100. s += _print_var(d[E->get()], p_indent, p_cur_indent + 1, p_sort_keys);
  101. }
  102. s += end_statement + _make_indent(p_indent, p_cur_indent) + "}";
  103. return s;
  104. };
  105. default:
  106. return "\"" + String(p_var).json_escape() + "\"";
  107. }
  108. }
  109. String JSON::print(const Variant &p_var, const String &p_indent, bool p_sort_keys) {
  110. return _print_var(p_var, p_indent, 0, p_sort_keys);
  111. }
  112. Error JSON::_get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str) {
  113. while (p_len > 0) {
  114. switch (p_str[index]) {
  115. case '\n': {
  116. line++;
  117. index++;
  118. break;
  119. };
  120. case 0: {
  121. r_token.type = TK_EOF;
  122. return OK;
  123. } break;
  124. case '{': {
  125. r_token.type = TK_CURLY_BRACKET_OPEN;
  126. index++;
  127. return OK;
  128. };
  129. case '}': {
  130. r_token.type = TK_CURLY_BRACKET_CLOSE;
  131. index++;
  132. return OK;
  133. };
  134. case '[': {
  135. r_token.type = TK_BRACKET_OPEN;
  136. index++;
  137. return OK;
  138. };
  139. case ']': {
  140. r_token.type = TK_BRACKET_CLOSE;
  141. index++;
  142. return OK;
  143. };
  144. case ':': {
  145. r_token.type = TK_COLON;
  146. index++;
  147. return OK;
  148. };
  149. case ',': {
  150. r_token.type = TK_COMMA;
  151. index++;
  152. return OK;
  153. };
  154. case '"': {
  155. index++;
  156. String str;
  157. while (true) {
  158. if (p_str[index] == 0) {
  159. r_err_str = "Unterminated String";
  160. return ERR_PARSE_ERROR;
  161. } else if (p_str[index] == '"') {
  162. index++;
  163. break;
  164. } else if (p_str[index] == '\\') {
  165. //escaped characters...
  166. index++;
  167. CharType next = p_str[index];
  168. if (next == 0) {
  169. r_err_str = "Unterminated String";
  170. return ERR_PARSE_ERROR;
  171. }
  172. CharType res = 0;
  173. switch (next) {
  174. case 'b':
  175. res = 8;
  176. break;
  177. case 't':
  178. res = 9;
  179. break;
  180. case 'n':
  181. res = 10;
  182. break;
  183. case 'f':
  184. res = 12;
  185. break;
  186. case 'r':
  187. res = 13;
  188. break;
  189. case 'u': {
  190. //hexnumbarh - oct is deprecated
  191. for (int j = 0; j < 4; j++) {
  192. CharType c = p_str[index + j + 1];
  193. if (c == 0) {
  194. r_err_str = "Unterminated String";
  195. return ERR_PARSE_ERROR;
  196. }
  197. if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
  198. r_err_str = "Malformed hex constant in string";
  199. return ERR_PARSE_ERROR;
  200. }
  201. CharType v;
  202. if (c >= '0' && c <= '9') {
  203. v = c - '0';
  204. } else if (c >= 'a' && c <= 'f') {
  205. v = c - 'a';
  206. v += 10;
  207. } else if (c >= 'A' && c <= 'F') {
  208. v = c - 'A';
  209. v += 10;
  210. } else {
  211. ERR_PRINT("BUG");
  212. v = 0;
  213. }
  214. res <<= 4;
  215. res |= v;
  216. }
  217. index += 4; //will add at the end anyway
  218. } break;
  219. //case '\"': res='\"'; break;
  220. //case '\\': res='\\'; break;
  221. //case '/': res='/'; break;
  222. default: {
  223. res = next;
  224. //r_err_str="Invalid escape sequence";
  225. //return ERR_PARSE_ERROR;
  226. } break;
  227. }
  228. str += res;
  229. } else {
  230. if (p_str[index] == '\n')
  231. line++;
  232. str += p_str[index];
  233. }
  234. index++;
  235. }
  236. r_token.type = TK_STRING;
  237. r_token.value = str;
  238. return OK;
  239. } break;
  240. default: {
  241. if (p_str[index] <= 32) {
  242. index++;
  243. break;
  244. }
  245. if (p_str[index] == '-' || (p_str[index] >= '0' && p_str[index] <= '9')) {
  246. //a number
  247. const CharType *rptr;
  248. double number = String::to_double(&p_str[index], &rptr);
  249. index += (rptr - &p_str[index]);
  250. r_token.type = TK_NUMBER;
  251. r_token.value = number;
  252. return OK;
  253. } else if ((p_str[index] >= 'A' && p_str[index] <= 'Z') || (p_str[index] >= 'a' && p_str[index] <= 'z')) {
  254. String id;
  255. while ((p_str[index] >= 'A' && p_str[index] <= 'Z') || (p_str[index] >= 'a' && p_str[index] <= 'z')) {
  256. id += p_str[index];
  257. index++;
  258. }
  259. r_token.type = TK_IDENTIFIER;
  260. r_token.value = id;
  261. return OK;
  262. } else {
  263. r_err_str = "Unexpected character.";
  264. return ERR_PARSE_ERROR;
  265. }
  266. }
  267. }
  268. }
  269. return ERR_PARSE_ERROR;
  270. }
  271. Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  272. if (token.type == TK_CURLY_BRACKET_OPEN) {
  273. Dictionary d;
  274. Error err = _parse_object(d, p_str, index, p_len, line, r_err_str);
  275. if (err)
  276. return err;
  277. value = d;
  278. } else if (token.type == TK_BRACKET_OPEN) {
  279. Array a;
  280. Error err = _parse_array(a, p_str, index, p_len, line, r_err_str);
  281. if (err)
  282. return err;
  283. value = a;
  284. } else if (token.type == TK_IDENTIFIER) {
  285. String id = token.value;
  286. if (id == "true")
  287. value = true;
  288. else if (id == "false")
  289. value = false;
  290. else if (id == "null")
  291. value = Variant();
  292. else {
  293. r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
  294. return ERR_PARSE_ERROR;
  295. }
  296. } else if (token.type == TK_NUMBER) {
  297. value = token.value;
  298. } else if (token.type == TK_STRING) {
  299. value = token.value;
  300. } else {
  301. r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
  302. return ERR_PARSE_ERROR;
  303. }
  304. return OK;
  305. }
  306. Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  307. Token token;
  308. bool need_comma = false;
  309. while (index < p_len) {
  310. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  311. if (err != OK)
  312. return err;
  313. if (token.type == TK_BRACKET_CLOSE) {
  314. return OK;
  315. }
  316. if (need_comma) {
  317. if (token.type != TK_COMMA) {
  318. r_err_str = "Expected ','";
  319. return ERR_PARSE_ERROR;
  320. } else {
  321. need_comma = false;
  322. continue;
  323. }
  324. }
  325. Variant v;
  326. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  327. if (err)
  328. return err;
  329. array.push_back(v);
  330. need_comma = true;
  331. }
  332. r_err_str = "Expected ']'";
  333. return ERR_PARSE_ERROR;
  334. }
  335. Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
  336. bool at_key = true;
  337. String key;
  338. Token token;
  339. bool need_comma = false;
  340. while (index < p_len) {
  341. if (at_key) {
  342. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  343. if (err != OK)
  344. return err;
  345. if (token.type == TK_CURLY_BRACKET_CLOSE) {
  346. return OK;
  347. }
  348. if (need_comma) {
  349. if (token.type != TK_COMMA) {
  350. r_err_str = "Expected '}' or ','";
  351. return ERR_PARSE_ERROR;
  352. } else {
  353. need_comma = false;
  354. continue;
  355. }
  356. }
  357. if (token.type != TK_STRING) {
  358. r_err_str = "Expected key";
  359. return ERR_PARSE_ERROR;
  360. }
  361. key = token.value;
  362. err = _get_token(p_str, index, p_len, token, line, r_err_str);
  363. if (err != OK)
  364. return err;
  365. if (token.type != TK_COLON) {
  366. r_err_str = "Expected ':'";
  367. return ERR_PARSE_ERROR;
  368. }
  369. at_key = false;
  370. } else {
  371. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  372. if (err != OK)
  373. return err;
  374. Variant v;
  375. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  376. if (err)
  377. return err;
  378. object[key] = v;
  379. need_comma = true;
  380. at_key = true;
  381. }
  382. }
  383. r_err_str = "Expected '}'";
  384. return ERR_PARSE_ERROR;
  385. }
  386. Error JSON::parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) {
  387. const CharType *str = p_json.ptr();
  388. int idx = 0;
  389. int len = p_json.length();
  390. Token token;
  391. r_err_line = 0;
  392. String aux_key;
  393. Error err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  394. if (err)
  395. return err;
  396. err = _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str);
  397. // Check if EOF is reached
  398. // or it's a type of the next token.
  399. if (err == OK && idx < len) {
  400. err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  401. if (err || token.type != TK_EOF) {
  402. r_err_str = "Expected 'EOF'";
  403. // Reset return value to empty `Variant`
  404. r_ret = Variant();
  405. return ERR_PARSE_ERROR;
  406. }
  407. }
  408. return err;
  409. }