gdscript_tokenizer_buffer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /**************************************************************************/
  2. /* gdscript_tokenizer_buffer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "gdscript_tokenizer_buffer.h"
  31. #include "core/io/compression.h"
  32. #include "core/io/marshalls.h"
  33. #define TOKENIZER_VERSION 100
  34. int GDScriptTokenizerBuffer::_token_to_binary(const Token &p_token, Vector<uint8_t> &r_buffer, int p_start, HashMap<StringName, uint32_t> &r_identifiers_map, HashMap<Variant, uint32_t, VariantHasher, VariantComparator> &r_constants_map) {
  35. int pos = p_start;
  36. int token_type = p_token.type & TOKEN_MASK;
  37. switch (p_token.type) {
  38. case GDScriptTokenizer::Token::ANNOTATION:
  39. case GDScriptTokenizer::Token::IDENTIFIER: {
  40. // Add identifier to map.
  41. int identifier_pos;
  42. StringName id = p_token.get_identifier();
  43. if (r_identifiers_map.has(id)) {
  44. identifier_pos = r_identifiers_map[id];
  45. } else {
  46. identifier_pos = r_identifiers_map.size();
  47. r_identifiers_map[id] = identifier_pos;
  48. }
  49. token_type |= identifier_pos << TOKEN_BITS;
  50. } break;
  51. case GDScriptTokenizer::Token::ERROR:
  52. case GDScriptTokenizer::Token::LITERAL: {
  53. // Add literal to map.
  54. int constant_pos;
  55. if (r_constants_map.has(p_token.literal)) {
  56. constant_pos = r_constants_map[p_token.literal];
  57. } else {
  58. constant_pos = r_constants_map.size();
  59. r_constants_map[p_token.literal] = constant_pos;
  60. }
  61. token_type |= constant_pos << TOKEN_BITS;
  62. } break;
  63. default:
  64. break;
  65. }
  66. // Encode token.
  67. int token_len;
  68. if (token_type & TOKEN_MASK) {
  69. token_len = 8;
  70. r_buffer.resize(pos + token_len);
  71. encode_uint32(token_type | TOKEN_BYTE_MASK, &r_buffer.write[pos]);
  72. pos += 4;
  73. } else {
  74. token_len = 5;
  75. r_buffer.resize(pos + token_len);
  76. r_buffer.write[pos] = token_type;
  77. pos++;
  78. }
  79. encode_uint32(p_token.start_line, &r_buffer.write[pos]);
  80. return token_len;
  81. }
  82. GDScriptTokenizer::Token GDScriptTokenizerBuffer::_binary_to_token(const uint8_t *p_buffer) {
  83. Token token;
  84. const uint8_t *b = p_buffer;
  85. uint32_t token_type = decode_uint32(b);
  86. token.type = (Token::Type)(token_type & TOKEN_MASK);
  87. if (token_type & TOKEN_BYTE_MASK) {
  88. b += 4;
  89. } else {
  90. b++;
  91. }
  92. token.start_line = decode_uint32(b);
  93. token.end_line = token.start_line;
  94. token.literal = token.get_name();
  95. if (token.type == Token::CONST_NAN) {
  96. token.literal = String("NAN"); // Special case since name and notation are different.
  97. }
  98. switch (token.type) {
  99. case GDScriptTokenizer::Token::ANNOTATION:
  100. case GDScriptTokenizer::Token::IDENTIFIER: {
  101. // Get name from map.
  102. int identifier_pos = token_type >> TOKEN_BITS;
  103. if (unlikely(identifier_pos >= identifiers.size())) {
  104. Token error;
  105. error.type = Token::ERROR;
  106. error.literal = "Identifier index out of bounds.";
  107. return error;
  108. }
  109. token.literal = identifiers[identifier_pos];
  110. } break;
  111. case GDScriptTokenizer::Token::ERROR:
  112. case GDScriptTokenizer::Token::LITERAL: {
  113. // Get literal from map.
  114. int constant_pos = token_type >> TOKEN_BITS;
  115. if (unlikely(constant_pos >= constants.size())) {
  116. Token error;
  117. error.type = Token::ERROR;
  118. error.literal = "Constant index out of bounds.";
  119. return error;
  120. }
  121. token.literal = constants[constant_pos];
  122. } break;
  123. default:
  124. break;
  125. }
  126. return token;
  127. }
  128. Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) {
  129. const uint8_t *buf = p_buffer.ptr();
  130. ERR_FAIL_COND_V(p_buffer.size() < 12 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA);
  131. int version = decode_uint32(&buf[4]);
  132. ERR_FAIL_COND_V_MSG(version > TOKENIZER_VERSION, ERR_INVALID_DATA, "Binary GDScript is too recent! Please use a newer engine version.");
  133. int decompressed_size = decode_uint32(&buf[8]);
  134. Vector<uint8_t> contents;
  135. if (decompressed_size == 0) {
  136. contents = p_buffer.slice(12);
  137. } else {
  138. contents.resize(decompressed_size);
  139. int result = Compression::decompress(contents.ptrw(), contents.size(), &buf[12], p_buffer.size() - 12, Compression::MODE_ZSTD);
  140. ERR_FAIL_COND_V_MSG(result != decompressed_size, ERR_INVALID_DATA, "Error decompressing GDScript tokenizer buffer.");
  141. }
  142. int total_len = contents.size();
  143. buf = contents.ptr();
  144. uint32_t identifier_count = decode_uint32(&buf[0]);
  145. uint32_t constant_count = decode_uint32(&buf[4]);
  146. uint32_t token_line_count = decode_uint32(&buf[8]);
  147. uint32_t token_count = decode_uint32(&buf[16]);
  148. const uint8_t *b = &buf[20];
  149. total_len -= 20;
  150. identifiers.resize(identifier_count);
  151. for (uint32_t i = 0; i < identifier_count; i++) {
  152. uint32_t len = decode_uint32(b);
  153. total_len -= 4;
  154. ERR_FAIL_COND_V((len * 4u) > (uint32_t)total_len, ERR_INVALID_DATA);
  155. b += 4;
  156. Vector<uint32_t> cs;
  157. cs.resize(len);
  158. for (uint32_t j = 0; j < len; j++) {
  159. uint8_t tmp[4];
  160. for (uint32_t k = 0; k < 4; k++) {
  161. tmp[k] = b[j * 4 + k] ^ 0xb6;
  162. }
  163. cs.write[j] = decode_uint32(tmp);
  164. }
  165. String s(reinterpret_cast<const char32_t *>(cs.ptr()), len);
  166. b += len * 4;
  167. total_len -= len * 4;
  168. identifiers.write[i] = s;
  169. }
  170. constants.resize(constant_count);
  171. for (uint32_t i = 0; i < constant_count; i++) {
  172. Variant v;
  173. int len;
  174. Error err = decode_variant(v, b, total_len, &len, false);
  175. if (err) {
  176. return err;
  177. }
  178. b += len;
  179. total_len -= len;
  180. constants.write[i] = v;
  181. }
  182. for (uint32_t i = 0; i < token_line_count; i++) {
  183. ERR_FAIL_COND_V(total_len < 8, ERR_INVALID_DATA);
  184. uint32_t token_index = decode_uint32(b);
  185. b += 4;
  186. uint32_t line = decode_uint32(b);
  187. b += 4;
  188. total_len -= 8;
  189. token_lines[token_index] = line;
  190. }
  191. for (uint32_t i = 0; i < token_line_count; i++) {
  192. ERR_FAIL_COND_V(total_len < 8, ERR_INVALID_DATA);
  193. uint32_t token_index = decode_uint32(b);
  194. b += 4;
  195. uint32_t column = decode_uint32(b);
  196. b += 4;
  197. total_len -= 8;
  198. token_columns[token_index] = column;
  199. }
  200. tokens.resize(token_count);
  201. for (uint32_t i = 0; i < token_count; i++) {
  202. int token_len = 5;
  203. if ((*b) & TOKEN_BYTE_MASK) {
  204. token_len = 8;
  205. }
  206. ERR_FAIL_COND_V(total_len < token_len, ERR_INVALID_DATA);
  207. Token token = _binary_to_token(b);
  208. b += token_len;
  209. ERR_FAIL_INDEX_V(token.type, Token::TK_MAX, ERR_INVALID_DATA);
  210. tokens.write[i] = token;
  211. total_len -= token_len;
  212. }
  213. ERR_FAIL_COND_V(total_len > 0, ERR_INVALID_DATA);
  214. return OK;
  215. }
  216. Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code, CompressMode p_compress_mode) {
  217. HashMap<StringName, uint32_t> identifier_map;
  218. HashMap<Variant, uint32_t, VariantHasher, VariantComparator> constant_map;
  219. Vector<uint8_t> token_buffer;
  220. HashMap<uint32_t, uint32_t> token_lines;
  221. HashMap<uint32_t, uint32_t> token_columns;
  222. GDScriptTokenizerText tokenizer;
  223. tokenizer.set_source_code(p_code);
  224. tokenizer.set_multiline_mode(true); // Ignore whitespace tokens.
  225. Token current = tokenizer.scan();
  226. int token_pos = 0;
  227. int last_token_line = 0;
  228. int token_counter = 0;
  229. while (current.type != Token::TK_EOF) {
  230. int token_len = _token_to_binary(current, token_buffer, token_pos, identifier_map, constant_map);
  231. token_pos += token_len;
  232. if (token_counter > 0 && current.start_line > last_token_line) {
  233. token_lines[token_counter] = current.start_line;
  234. token_columns[token_counter] = current.start_column;
  235. }
  236. last_token_line = current.end_line;
  237. current = tokenizer.scan();
  238. token_counter++;
  239. }
  240. // Reverse maps.
  241. Vector<StringName> rev_identifier_map;
  242. rev_identifier_map.resize(identifier_map.size());
  243. for (const KeyValue<StringName, uint32_t> &E : identifier_map) {
  244. rev_identifier_map.write[E.value] = E.key;
  245. }
  246. Vector<Variant> rev_constant_map;
  247. rev_constant_map.resize(constant_map.size());
  248. for (const KeyValue<Variant, uint32_t> &E : constant_map) {
  249. rev_constant_map.write[E.value] = E.key;
  250. }
  251. HashMap<uint32_t, uint32_t> rev_token_lines;
  252. for (const KeyValue<uint32_t, uint32_t> &E : token_lines) {
  253. rev_token_lines[E.value] = E.key;
  254. }
  255. // Remove continuation lines from map.
  256. for (int line : tokenizer.get_continuation_lines()) {
  257. if (rev_token_lines.has(line)) {
  258. token_lines.erase(rev_token_lines[line]);
  259. token_columns.erase(rev_token_lines[line]);
  260. }
  261. }
  262. Vector<uint8_t> contents;
  263. contents.resize(20);
  264. encode_uint32(identifier_map.size(), &contents.write[0]);
  265. encode_uint32(constant_map.size(), &contents.write[4]);
  266. encode_uint32(token_lines.size(), &contents.write[8]);
  267. encode_uint32(0, &contents.write[12]); // Unused, kept for compatibility. Please remove at next `TOKENIZER_VERSION` increment.
  268. encode_uint32(token_counter, &contents.write[16]);
  269. int buf_pos = 20;
  270. // Save identifiers.
  271. for (const StringName &id : rev_identifier_map) {
  272. String s = id.operator String();
  273. int len = s.length();
  274. contents.resize(buf_pos + (len + 1) * 4);
  275. encode_uint32(len, &contents.write[buf_pos]);
  276. buf_pos += 4;
  277. for (int i = 0; i < len; i++) {
  278. uint8_t tmp[4];
  279. encode_uint32(s[i], tmp);
  280. for (int b = 0; b < 4; b++) {
  281. contents.write[buf_pos + b] = tmp[b] ^ 0xb6;
  282. }
  283. buf_pos += 4;
  284. }
  285. }
  286. // Save constants.
  287. for (const Variant &v : rev_constant_map) {
  288. int len;
  289. // Objects cannot be constant, never encode objects.
  290. Error err = encode_variant(v, nullptr, len, false);
  291. ERR_FAIL_COND_V_MSG(err != OK, Vector<uint8_t>(), "Error when trying to encode Variant.");
  292. contents.resize(buf_pos + len);
  293. encode_variant(v, &contents.write[buf_pos], len, false);
  294. buf_pos += len;
  295. }
  296. // Save lines and columns.
  297. contents.resize(buf_pos + token_lines.size() * 16);
  298. for (const KeyValue<uint32_t, uint32_t> &e : token_lines) {
  299. encode_uint32(e.key, &contents.write[buf_pos]);
  300. buf_pos += 4;
  301. encode_uint32(e.value, &contents.write[buf_pos]);
  302. buf_pos += 4;
  303. }
  304. for (const KeyValue<uint32_t, uint32_t> &e : token_columns) {
  305. encode_uint32(e.key, &contents.write[buf_pos]);
  306. buf_pos += 4;
  307. encode_uint32(e.value, &contents.write[buf_pos]);
  308. buf_pos += 4;
  309. }
  310. // Store tokens.
  311. contents.append_array(token_buffer);
  312. Vector<uint8_t> buf;
  313. // Save header.
  314. buf.resize(12);
  315. buf.write[0] = 'G';
  316. buf.write[1] = 'D';
  317. buf.write[2] = 'S';
  318. buf.write[3] = 'C';
  319. encode_uint32(TOKENIZER_VERSION, &buf.write[4]);
  320. switch (p_compress_mode) {
  321. case COMPRESS_NONE:
  322. encode_uint32(0u, &buf.write[8]);
  323. buf.append_array(contents);
  324. break;
  325. case COMPRESS_ZSTD: {
  326. encode_uint32(contents.size(), &buf.write[8]);
  327. Vector<uint8_t> compressed;
  328. int max_size = Compression::get_max_compressed_buffer_size(contents.size(), Compression::MODE_ZSTD);
  329. compressed.resize(max_size);
  330. int compressed_size = Compression::compress(compressed.ptrw(), contents.ptr(), contents.size(), Compression::MODE_ZSTD);
  331. ERR_FAIL_COND_V_MSG(compressed_size < 0, Vector<uint8_t>(), "Error compressing GDScript tokenizer buffer.");
  332. compressed.resize(compressed_size);
  333. buf.append_array(compressed);
  334. } break;
  335. }
  336. return buf;
  337. }
  338. int GDScriptTokenizerBuffer::get_cursor_line() const {
  339. return 0;
  340. }
  341. int GDScriptTokenizerBuffer::get_cursor_column() const {
  342. return 0;
  343. }
  344. void GDScriptTokenizerBuffer::set_cursor_position(int p_line, int p_column) {
  345. }
  346. void GDScriptTokenizerBuffer::set_multiline_mode(bool p_state) {
  347. multiline_mode = p_state;
  348. }
  349. bool GDScriptTokenizerBuffer::is_past_cursor() const {
  350. return false;
  351. }
  352. void GDScriptTokenizerBuffer::push_expression_indented_block() {
  353. indent_stack_stack.push_back(indent_stack);
  354. }
  355. void GDScriptTokenizerBuffer::pop_expression_indented_block() {
  356. ERR_FAIL_COND(indent_stack_stack.is_empty());
  357. indent_stack = indent_stack_stack.back()->get();
  358. indent_stack_stack.pop_back();
  359. }
  360. GDScriptTokenizer::Token GDScriptTokenizerBuffer::scan() {
  361. // Add final newline.
  362. if (current >= tokens.size() && !last_token_was_newline) {
  363. Token newline;
  364. newline.type = Token::NEWLINE;
  365. newline.start_line = current_line;
  366. newline.end_line = current_line;
  367. last_token_was_newline = true;
  368. return newline;
  369. }
  370. // Resolve pending indentation change.
  371. if (pending_indents > 0) {
  372. pending_indents--;
  373. Token indent;
  374. indent.type = Token::INDENT;
  375. indent.start_line = current_line;
  376. indent.end_line = current_line;
  377. return indent;
  378. } else if (pending_indents < 0) {
  379. pending_indents++;
  380. Token dedent;
  381. dedent.type = Token::DEDENT;
  382. dedent.start_line = current_line;
  383. dedent.end_line = current_line;
  384. return dedent;
  385. }
  386. if (current >= tokens.size()) {
  387. if (!indent_stack.is_empty()) {
  388. pending_indents -= indent_stack.size();
  389. indent_stack.clear();
  390. return scan();
  391. }
  392. Token eof;
  393. eof.type = Token::TK_EOF;
  394. return eof;
  395. };
  396. if (!last_token_was_newline && token_lines.has(current)) {
  397. current_line = token_lines[current];
  398. uint32_t current_column = token_columns[current];
  399. // Check if there's a need to indent/dedent.
  400. if (!multiline_mode) {
  401. uint32_t previous_indent = 0;
  402. if (!indent_stack.is_empty()) {
  403. previous_indent = indent_stack.back()->get();
  404. }
  405. if (current_column - 1 > previous_indent) {
  406. pending_indents++;
  407. indent_stack.push_back(current_column - 1);
  408. } else {
  409. while (current_column - 1 < previous_indent) {
  410. pending_indents--;
  411. indent_stack.pop_back();
  412. if (indent_stack.is_empty()) {
  413. break;
  414. }
  415. previous_indent = indent_stack.back()->get();
  416. }
  417. }
  418. Token newline;
  419. newline.type = Token::NEWLINE;
  420. newline.start_line = current_line;
  421. newline.end_line = current_line;
  422. last_token_was_newline = true;
  423. return newline;
  424. }
  425. }
  426. last_token_was_newline = false;
  427. Token token = tokens[current++];
  428. return token;
  429. }