json.cpp 11 KB

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