json.cpp 11 KB

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