gdscript_tokenizer.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. /*************************************************************************/
  2. /* gdscript_tokenizer.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 "gdscript_tokenizer.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/map.h"
  33. #include "core/print_string.h"
  34. #include "gdscript_functions.h"
  35. const char *GDScriptTokenizer::token_names[TK_MAX] = {
  36. "Empty",
  37. "Identifier",
  38. "Constant",
  39. "Self",
  40. "Built-In Type",
  41. "Built-In Func",
  42. "In",
  43. "'=='",
  44. "'!='",
  45. "'<'",
  46. "'<='",
  47. "'>'",
  48. "'>='",
  49. "'and'",
  50. "'or'",
  51. "'not'",
  52. "'+'",
  53. "'-'",
  54. "'*'",
  55. "'/'",
  56. "'%'",
  57. "'<<'",
  58. "'>>'",
  59. "'='",
  60. "'+='",
  61. "'-='",
  62. "'*='",
  63. "'/='",
  64. "'%='",
  65. "'<<='",
  66. "'>>='",
  67. "'&='",
  68. "'|='",
  69. "'^='",
  70. "'&'",
  71. "'|'",
  72. "'^'",
  73. "'~'",
  74. //"Plus Plus",
  75. //"Minus Minus",
  76. "if",
  77. "elif",
  78. "else",
  79. "for",
  80. "while",
  81. "break",
  82. "continue",
  83. "pass",
  84. "return",
  85. "match",
  86. "func",
  87. "class",
  88. "class_name",
  89. "extends",
  90. "is",
  91. "onready",
  92. "tool",
  93. "static",
  94. "export",
  95. "setget",
  96. "const",
  97. "var",
  98. "as",
  99. "void",
  100. "enum",
  101. "preload",
  102. "assert",
  103. "yield",
  104. "signal",
  105. "breakpoint",
  106. "remote",
  107. "master",
  108. "puppet",
  109. "remotesync",
  110. "mastersync",
  111. "puppetsync",
  112. "'['",
  113. "']'",
  114. "'{'",
  115. "'}'",
  116. "'('",
  117. "')'",
  118. "','",
  119. "';'",
  120. "'.'",
  121. "'?'",
  122. "':'",
  123. "'$'",
  124. "'->'",
  125. "'\\n'",
  126. "PI",
  127. "TAU",
  128. "_",
  129. "INF",
  130. "NAN",
  131. "Error",
  132. "EOF",
  133. "Cursor"
  134. };
  135. struct _bit {
  136. Variant::Type type;
  137. const char *text;
  138. };
  139. //built in types
  140. static const _bit _type_list[] = {
  141. //types
  142. { Variant::BOOL, "bool" },
  143. { Variant::INT, "int" },
  144. { Variant::REAL, "float" },
  145. { Variant::STRING, "String" },
  146. { Variant::VECTOR2, "Vector2" },
  147. { Variant::RECT2, "Rect2" },
  148. { Variant::TRANSFORM2D, "Transform2D" },
  149. { Variant::VECTOR3, "Vector3" },
  150. { Variant::AABB, "AABB" },
  151. { Variant::PLANE, "Plane" },
  152. { Variant::QUAT, "Quat" },
  153. { Variant::BASIS, "Basis" },
  154. { Variant::TRANSFORM, "Transform" },
  155. { Variant::COLOR, "Color" },
  156. { Variant::_RID, "RID" },
  157. { Variant::OBJECT, "Object" },
  158. { Variant::NODE_PATH, "NodePath" },
  159. { Variant::DICTIONARY, "Dictionary" },
  160. { Variant::ARRAY, "Array" },
  161. { Variant::POOL_BYTE_ARRAY, "PoolByteArray" },
  162. { Variant::POOL_INT_ARRAY, "PoolIntArray" },
  163. { Variant::POOL_REAL_ARRAY, "PoolRealArray" },
  164. { Variant::POOL_STRING_ARRAY, "PoolStringArray" },
  165. { Variant::POOL_VECTOR2_ARRAY, "PoolVector2Array" },
  166. { Variant::POOL_VECTOR3_ARRAY, "PoolVector3Array" },
  167. { Variant::POOL_COLOR_ARRAY, "PoolColorArray" },
  168. { Variant::VARIANT_MAX, NULL },
  169. };
  170. struct _kws {
  171. GDScriptTokenizer::Token token;
  172. const char *text;
  173. };
  174. static const _kws _keyword_list[] = {
  175. //ops
  176. { GDScriptTokenizer::TK_OP_IN, "in" },
  177. { GDScriptTokenizer::TK_OP_NOT, "not" },
  178. { GDScriptTokenizer::TK_OP_OR, "or" },
  179. { GDScriptTokenizer::TK_OP_AND, "and" },
  180. //func
  181. { GDScriptTokenizer::TK_PR_FUNCTION, "func" },
  182. { GDScriptTokenizer::TK_PR_CLASS, "class" },
  183. { GDScriptTokenizer::TK_PR_CLASS_NAME, "class_name" },
  184. { GDScriptTokenizer::TK_PR_EXTENDS, "extends" },
  185. { GDScriptTokenizer::TK_PR_IS, "is" },
  186. { GDScriptTokenizer::TK_PR_ONREADY, "onready" },
  187. { GDScriptTokenizer::TK_PR_TOOL, "tool" },
  188. { GDScriptTokenizer::TK_PR_STATIC, "static" },
  189. { GDScriptTokenizer::TK_PR_EXPORT, "export" },
  190. { GDScriptTokenizer::TK_PR_SETGET, "setget" },
  191. { GDScriptTokenizer::TK_PR_VAR, "var" },
  192. { GDScriptTokenizer::TK_PR_AS, "as" },
  193. { GDScriptTokenizer::TK_PR_VOID, "void" },
  194. { GDScriptTokenizer::TK_PR_PRELOAD, "preload" },
  195. { GDScriptTokenizer::TK_PR_ASSERT, "assert" },
  196. { GDScriptTokenizer::TK_PR_YIELD, "yield" },
  197. { GDScriptTokenizer::TK_PR_SIGNAL, "signal" },
  198. { GDScriptTokenizer::TK_PR_BREAKPOINT, "breakpoint" },
  199. { GDScriptTokenizer::TK_PR_REMOTE, "remote" },
  200. { GDScriptTokenizer::TK_PR_MASTER, "master" },
  201. { GDScriptTokenizer::TK_PR_PUPPET, "puppet" },
  202. { GDScriptTokenizer::TK_PR_REMOTESYNC, "remotesync" },
  203. { GDScriptTokenizer::TK_PR_MASTERSYNC, "mastersync" },
  204. { GDScriptTokenizer::TK_PR_PUPPETSYNC, "puppetsync" },
  205. { GDScriptTokenizer::TK_PR_CONST, "const" },
  206. { GDScriptTokenizer::TK_PR_ENUM, "enum" },
  207. //controlflow
  208. { GDScriptTokenizer::TK_CF_IF, "if" },
  209. { GDScriptTokenizer::TK_CF_ELIF, "elif" },
  210. { GDScriptTokenizer::TK_CF_ELSE, "else" },
  211. { GDScriptTokenizer::TK_CF_FOR, "for" },
  212. { GDScriptTokenizer::TK_CF_WHILE, "while" },
  213. { GDScriptTokenizer::TK_CF_BREAK, "break" },
  214. { GDScriptTokenizer::TK_CF_CONTINUE, "continue" },
  215. { GDScriptTokenizer::TK_CF_RETURN, "return" },
  216. { GDScriptTokenizer::TK_CF_MATCH, "match" },
  217. { GDScriptTokenizer::TK_CF_PASS, "pass" },
  218. { GDScriptTokenizer::TK_SELF, "self" },
  219. { GDScriptTokenizer::TK_CONST_PI, "PI" },
  220. { GDScriptTokenizer::TK_CONST_TAU, "TAU" },
  221. { GDScriptTokenizer::TK_WILDCARD, "_" },
  222. { GDScriptTokenizer::TK_CONST_INF, "INF" },
  223. { GDScriptTokenizer::TK_CONST_NAN, "NAN" },
  224. { GDScriptTokenizer::TK_ERROR, NULL }
  225. };
  226. const char *GDScriptTokenizer::get_token_name(Token p_token) {
  227. ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>");
  228. return token_names[p_token];
  229. }
  230. bool GDScriptTokenizer::is_token_literal(int p_offset, bool variable_safe) const {
  231. switch (get_token(p_offset)) {
  232. // Can always be literal:
  233. case TK_IDENTIFIER:
  234. case TK_PR_ONREADY:
  235. case TK_PR_TOOL:
  236. case TK_PR_STATIC:
  237. case TK_PR_EXPORT:
  238. case TK_PR_SETGET:
  239. case TK_PR_SIGNAL:
  240. case TK_PR_REMOTE:
  241. case TK_PR_MASTER:
  242. case TK_PR_PUPPET:
  243. case TK_PR_REMOTESYNC:
  244. case TK_PR_MASTERSYNC:
  245. case TK_PR_PUPPETSYNC:
  246. return true;
  247. // Literal for non-variables only:
  248. case TK_BUILT_IN_TYPE:
  249. case TK_BUILT_IN_FUNC:
  250. case TK_OP_IN:
  251. //case TK_OP_NOT:
  252. //case TK_OP_OR:
  253. //case TK_OP_AND:
  254. case TK_PR_CLASS:
  255. case TK_PR_CONST:
  256. case TK_PR_ENUM:
  257. case TK_PR_PRELOAD:
  258. case TK_PR_FUNCTION:
  259. case TK_PR_EXTENDS:
  260. case TK_PR_ASSERT:
  261. case TK_PR_YIELD:
  262. case TK_PR_VAR:
  263. case TK_CF_IF:
  264. case TK_CF_ELIF:
  265. case TK_CF_ELSE:
  266. case TK_CF_FOR:
  267. case TK_CF_WHILE:
  268. case TK_CF_BREAK:
  269. case TK_CF_CONTINUE:
  270. case TK_CF_RETURN:
  271. case TK_CF_MATCH:
  272. case TK_CF_PASS:
  273. case TK_SELF:
  274. case TK_CONST_PI:
  275. case TK_CONST_TAU:
  276. case TK_WILDCARD:
  277. case TK_CONST_INF:
  278. case TK_CONST_NAN:
  279. case TK_ERROR:
  280. return !variable_safe;
  281. case TK_CONSTANT: {
  282. switch (get_token_constant(p_offset).get_type()) {
  283. case Variant::NIL:
  284. case Variant::BOOL:
  285. return true;
  286. default:
  287. return false;
  288. }
  289. }
  290. default:
  291. return false;
  292. }
  293. }
  294. StringName GDScriptTokenizer::get_token_literal(int p_offset) const {
  295. Token token = get_token(p_offset);
  296. switch (token) {
  297. case TK_IDENTIFIER:
  298. return get_token_identifier(p_offset);
  299. case TK_BUILT_IN_TYPE: {
  300. Variant::Type type = get_token_type(p_offset);
  301. int idx = 0;
  302. while (_type_list[idx].text) {
  303. if (type == _type_list[idx].type) {
  304. return _type_list[idx].text;
  305. }
  306. idx++;
  307. }
  308. } break; // Shouldn't get here, stuff happens
  309. case TK_BUILT_IN_FUNC:
  310. return GDScriptFunctions::get_func_name(get_token_built_in_func(p_offset));
  311. case TK_CONSTANT: {
  312. const Variant value = get_token_constant(p_offset);
  313. switch (value.get_type()) {
  314. case Variant::NIL:
  315. return "null";
  316. case Variant::BOOL:
  317. return value ? "true" : "false";
  318. default: {
  319. }
  320. }
  321. }
  322. case TK_OP_AND:
  323. case TK_OP_OR:
  324. break; // Don't get into default, since they can be non-literal
  325. default: {
  326. int idx = 0;
  327. while (_keyword_list[idx].text) {
  328. if (token == _keyword_list[idx].token) {
  329. return _keyword_list[idx].text;
  330. }
  331. idx++;
  332. }
  333. }
  334. }
  335. ERR_FAIL_V_MSG("", "Failed to get token literal.");
  336. }
  337. static bool _is_text_char(CharType c) {
  338. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
  339. }
  340. static bool _is_number(CharType c) {
  341. return (c >= '0' && c <= '9');
  342. }
  343. static bool _is_hex(CharType c) {
  344. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  345. }
  346. static bool _is_bin(CharType c) {
  347. return (c == '0' || c == '1');
  348. }
  349. void GDScriptTokenizerText::_make_token(Token p_type) {
  350. TokenData &tk = tk_rb[tk_rb_pos];
  351. tk.type = p_type;
  352. tk.line = line;
  353. tk.col = column;
  354. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  355. }
  356. void GDScriptTokenizerText::_make_identifier(const StringName &p_identifier) {
  357. TokenData &tk = tk_rb[tk_rb_pos];
  358. tk.type = TK_IDENTIFIER;
  359. tk.identifier = p_identifier;
  360. tk.line = line;
  361. tk.col = column;
  362. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  363. }
  364. void GDScriptTokenizerText::_make_built_in_func(GDScriptFunctions::Function p_func) {
  365. TokenData &tk = tk_rb[tk_rb_pos];
  366. tk.type = TK_BUILT_IN_FUNC;
  367. tk.func = p_func;
  368. tk.line = line;
  369. tk.col = column;
  370. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  371. }
  372. void GDScriptTokenizerText::_make_constant(const Variant &p_constant) {
  373. TokenData &tk = tk_rb[tk_rb_pos];
  374. tk.type = TK_CONSTANT;
  375. tk.constant = p_constant;
  376. tk.line = line;
  377. tk.col = column;
  378. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  379. }
  380. void GDScriptTokenizerText::_make_type(const Variant::Type &p_type) {
  381. TokenData &tk = tk_rb[tk_rb_pos];
  382. tk.type = TK_BUILT_IN_TYPE;
  383. tk.vtype = p_type;
  384. tk.line = line;
  385. tk.col = column;
  386. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  387. }
  388. void GDScriptTokenizerText::_make_error(const String &p_error) {
  389. error_flag = true;
  390. last_error = p_error;
  391. TokenData &tk = tk_rb[tk_rb_pos];
  392. tk.type = TK_ERROR;
  393. tk.constant = p_error;
  394. tk.line = line;
  395. tk.col = column;
  396. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  397. }
  398. void GDScriptTokenizerText::_make_newline(int p_indentation, int p_tabs) {
  399. TokenData &tk = tk_rb[tk_rb_pos];
  400. tk.type = TK_NEWLINE;
  401. tk.constant = Vector2(p_indentation, p_tabs);
  402. tk.line = line;
  403. tk.col = column;
  404. tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
  405. }
  406. void GDScriptTokenizerText::_advance() {
  407. if (error_flag) {
  408. //parser broke
  409. _make_error(last_error);
  410. return;
  411. }
  412. if (code_pos >= len) {
  413. _make_token(TK_EOF);
  414. return;
  415. }
  416. #define GETCHAR(m_ofs) ((m_ofs + code_pos) >= len ? 0 : _code[m_ofs + code_pos])
  417. #define INCPOS(m_amount) \
  418. { \
  419. code_pos += m_amount; \
  420. column += m_amount; \
  421. }
  422. while (true) {
  423. bool is_node_path = false;
  424. StringMode string_mode = STRING_DOUBLE_QUOTE;
  425. switch (GETCHAR(0)) {
  426. case 0:
  427. _make_token(TK_EOF);
  428. break;
  429. case '\\':
  430. INCPOS(1);
  431. if (GETCHAR(0) == '\r') {
  432. INCPOS(1);
  433. }
  434. if (GETCHAR(0) != '\n') {
  435. _make_error("Expected newline after '\\'.");
  436. return;
  437. }
  438. INCPOS(1);
  439. line++;
  440. while (GETCHAR(0) == ' ' || GETCHAR(0) == '\t') {
  441. INCPOS(1);
  442. }
  443. continue;
  444. case '\t':
  445. case '\r':
  446. case ' ':
  447. INCPOS(1);
  448. continue;
  449. case '#': { // line comment skip
  450. #ifdef DEBUG_ENABLED
  451. String comment;
  452. #endif // DEBUG_ENABLED
  453. while (GETCHAR(0) != '\n') {
  454. #ifdef DEBUG_ENABLED
  455. comment += GETCHAR(0);
  456. #endif // DEBUG_ENABLED
  457. code_pos++;
  458. if (GETCHAR(0) == 0) { //end of file
  459. //_make_error("Unterminated Comment");
  460. _make_token(TK_EOF);
  461. return;
  462. }
  463. }
  464. #ifdef DEBUG_ENABLED
  465. String comment_content = comment.trim_prefix("#").trim_prefix(" ");
  466. if (comment_content.begins_with("warning-ignore:")) {
  467. String code = comment_content.get_slice(":", 1);
  468. warning_skips.push_back(Pair<int, String>(line, code.strip_edges().to_lower()));
  469. } else if (comment_content.begins_with("warning-ignore-all:")) {
  470. String code = comment_content.get_slice(":", 1);
  471. warning_global_skips.insert(code.strip_edges().to_lower());
  472. } else if (comment_content.strip_edges() == "warnings-disable") {
  473. ignore_warnings = true;
  474. }
  475. #endif // DEBUG_ENABLED
  476. FALLTHROUGH;
  477. }
  478. case '\n': {
  479. line++;
  480. INCPOS(1);
  481. bool used_spaces = false;
  482. int tabs = 0;
  483. column = 1;
  484. int i = 0;
  485. while (true) {
  486. if (GETCHAR(i) == ' ') {
  487. i++;
  488. used_spaces = true;
  489. } else if (GETCHAR(i) == '\t') {
  490. if (used_spaces) {
  491. _make_error("Spaces used before tabs on a line");
  492. return;
  493. }
  494. i++;
  495. tabs++;
  496. } else {
  497. break; // not indentation anymore
  498. }
  499. }
  500. _make_newline(i, tabs);
  501. return;
  502. }
  503. case '/': {
  504. switch (GETCHAR(1)) {
  505. case '=': { // diveq
  506. _make_token(TK_OP_ASSIGN_DIV);
  507. INCPOS(1);
  508. } break;
  509. default:
  510. _make_token(TK_OP_DIV);
  511. }
  512. } break;
  513. case '=': {
  514. if (GETCHAR(1) == '=') {
  515. _make_token(TK_OP_EQUAL);
  516. INCPOS(1);
  517. } else
  518. _make_token(TK_OP_ASSIGN);
  519. } break;
  520. case '<': {
  521. if (GETCHAR(1) == '=') {
  522. _make_token(TK_OP_LESS_EQUAL);
  523. INCPOS(1);
  524. } else if (GETCHAR(1) == '<') {
  525. if (GETCHAR(2) == '=') {
  526. _make_token(TK_OP_ASSIGN_SHIFT_LEFT);
  527. INCPOS(1);
  528. } else {
  529. _make_token(TK_OP_SHIFT_LEFT);
  530. }
  531. INCPOS(1);
  532. } else
  533. _make_token(TK_OP_LESS);
  534. } break;
  535. case '>': {
  536. if (GETCHAR(1) == '=') {
  537. _make_token(TK_OP_GREATER_EQUAL);
  538. INCPOS(1);
  539. } else if (GETCHAR(1) == '>') {
  540. if (GETCHAR(2) == '=') {
  541. _make_token(TK_OP_ASSIGN_SHIFT_RIGHT);
  542. INCPOS(1);
  543. } else {
  544. _make_token(TK_OP_SHIFT_RIGHT);
  545. }
  546. INCPOS(1);
  547. } else {
  548. _make_token(TK_OP_GREATER);
  549. }
  550. } break;
  551. case '!': {
  552. if (GETCHAR(1) == '=') {
  553. _make_token(TK_OP_NOT_EQUAL);
  554. INCPOS(1);
  555. } else {
  556. _make_token(TK_OP_NOT);
  557. }
  558. } break;
  559. //case '"' //string - no strings in shader
  560. //case '\'' //string - no strings in shader
  561. case '{':
  562. _make_token(TK_CURLY_BRACKET_OPEN);
  563. break;
  564. case '}':
  565. _make_token(TK_CURLY_BRACKET_CLOSE);
  566. break;
  567. case '[':
  568. _make_token(TK_BRACKET_OPEN);
  569. break;
  570. case ']':
  571. _make_token(TK_BRACKET_CLOSE);
  572. break;
  573. case '(':
  574. _make_token(TK_PARENTHESIS_OPEN);
  575. break;
  576. case ')':
  577. _make_token(TK_PARENTHESIS_CLOSE);
  578. break;
  579. case ',':
  580. _make_token(TK_COMMA);
  581. break;
  582. case ';':
  583. _make_token(TK_SEMICOLON);
  584. break;
  585. case '?':
  586. _make_token(TK_QUESTION_MARK);
  587. break;
  588. case ':':
  589. _make_token(TK_COLON); //for methods maybe but now useless.
  590. break;
  591. case '$':
  592. _make_token(TK_DOLLAR); //for the get_node() shortener
  593. break;
  594. case '^': {
  595. if (GETCHAR(1) == '=') {
  596. _make_token(TK_OP_ASSIGN_BIT_XOR);
  597. INCPOS(1);
  598. } else {
  599. _make_token(TK_OP_BIT_XOR);
  600. }
  601. } break;
  602. case '~':
  603. _make_token(TK_OP_BIT_INVERT);
  604. break;
  605. case '&': {
  606. if (GETCHAR(1) == '&') {
  607. _make_token(TK_OP_AND);
  608. INCPOS(1);
  609. } else if (GETCHAR(1) == '=') {
  610. _make_token(TK_OP_ASSIGN_BIT_AND);
  611. INCPOS(1);
  612. } else {
  613. _make_token(TK_OP_BIT_AND);
  614. }
  615. } break;
  616. case '|': {
  617. if (GETCHAR(1) == '|') {
  618. _make_token(TK_OP_OR);
  619. INCPOS(1);
  620. } else if (GETCHAR(1) == '=') {
  621. _make_token(TK_OP_ASSIGN_BIT_OR);
  622. INCPOS(1);
  623. } else {
  624. _make_token(TK_OP_BIT_OR);
  625. }
  626. } break;
  627. case '*': {
  628. if (GETCHAR(1) == '=') {
  629. _make_token(TK_OP_ASSIGN_MUL);
  630. INCPOS(1);
  631. } else {
  632. _make_token(TK_OP_MUL);
  633. }
  634. } break;
  635. case '+': {
  636. if (GETCHAR(1) == '=') {
  637. _make_token(TK_OP_ASSIGN_ADD);
  638. INCPOS(1);
  639. /*
  640. } else if (GETCHAR(1)=='+') {
  641. _make_token(TK_OP_PLUS_PLUS);
  642. INCPOS(1);
  643. */
  644. } else {
  645. _make_token(TK_OP_ADD);
  646. }
  647. } break;
  648. case '-': {
  649. if (GETCHAR(1) == '=') {
  650. _make_token(TK_OP_ASSIGN_SUB);
  651. INCPOS(1);
  652. } else if (GETCHAR(1) == '>') {
  653. _make_token(TK_FORWARD_ARROW);
  654. INCPOS(1);
  655. } else {
  656. _make_token(TK_OP_SUB);
  657. }
  658. } break;
  659. case '%': {
  660. if (GETCHAR(1) == '=') {
  661. _make_token(TK_OP_ASSIGN_MOD);
  662. INCPOS(1);
  663. } else {
  664. _make_token(TK_OP_MOD);
  665. }
  666. } break;
  667. case '@':
  668. if (CharType(GETCHAR(1)) != '"' && CharType(GETCHAR(1)) != '\'') {
  669. _make_error("Unexpected '@'");
  670. return;
  671. }
  672. INCPOS(1);
  673. is_node_path = true;
  674. FALLTHROUGH;
  675. case '\'':
  676. case '"': {
  677. if (GETCHAR(0) == '\'')
  678. string_mode = STRING_SINGLE_QUOTE;
  679. int i = 1;
  680. if (string_mode == STRING_DOUBLE_QUOTE && GETCHAR(i) == '"' && GETCHAR(i + 1) == '"') {
  681. i += 2;
  682. string_mode = STRING_MULTILINE;
  683. }
  684. String str;
  685. while (true) {
  686. if (CharType(GETCHAR(i)) == 0) {
  687. _make_error("Unterminated String");
  688. return;
  689. } else if (string_mode == STRING_DOUBLE_QUOTE && CharType(GETCHAR(i)) == '"') {
  690. break;
  691. } else if (string_mode == STRING_SINGLE_QUOTE && CharType(GETCHAR(i)) == '\'') {
  692. break;
  693. } else if (string_mode == STRING_MULTILINE && CharType(GETCHAR(i)) == '\"' && CharType(GETCHAR(i + 1)) == '\"' && CharType(GETCHAR(i + 2)) == '\"') {
  694. i += 2;
  695. break;
  696. } else if (string_mode != STRING_MULTILINE && CharType(GETCHAR(i)) == '\n') {
  697. _make_error("Unexpected EOL at String.");
  698. return;
  699. } else if (CharType(GETCHAR(i)) == 0xFFFF) {
  700. //string ends here, next will be TK
  701. i--;
  702. break;
  703. } else if (CharType(GETCHAR(i)) == '\\') {
  704. //escaped characters...
  705. i++;
  706. CharType next = GETCHAR(i);
  707. if (next == 0) {
  708. _make_error("Unterminated String");
  709. return;
  710. }
  711. CharType res = 0;
  712. switch (next) {
  713. case 'a': res = 7; break;
  714. case 'b': res = 8; break;
  715. case 't': res = 9; break;
  716. case 'n': res = 10; break;
  717. case 'v': res = 11; break;
  718. case 'f': res = 12; break;
  719. case 'r': res = 13; break;
  720. case '\'': res = '\''; break;
  721. case '\"': res = '\"'; break;
  722. case '\\': res = '\\'; break;
  723. case '/':
  724. res = '/';
  725. break; //wtf
  726. case 'u': {
  727. //hexnumbarh - oct is deprecated
  728. i += 1;
  729. for (int j = 0; j < 4; j++) {
  730. CharType c = GETCHAR(i + j);
  731. if (c == 0) {
  732. _make_error("Unterminated String");
  733. return;
  734. }
  735. CharType v = 0;
  736. if (c >= '0' && c <= '9') {
  737. v = c - '0';
  738. } else if (c >= 'a' && c <= 'f') {
  739. v = c - 'a';
  740. v += 10;
  741. } else if (c >= 'A' && c <= 'F') {
  742. v = c - 'A';
  743. v += 10;
  744. } else {
  745. _make_error("Malformed hex constant in string");
  746. return;
  747. }
  748. res <<= 4;
  749. res |= v;
  750. }
  751. i += 3;
  752. } break;
  753. default: {
  754. _make_error("Invalid escape sequence");
  755. return;
  756. } break;
  757. }
  758. str += res;
  759. } else {
  760. if (CharType(GETCHAR(i)) == '\n') {
  761. line++;
  762. column = 1;
  763. }
  764. str += CharType(GETCHAR(i));
  765. }
  766. i++;
  767. }
  768. INCPOS(i);
  769. if (is_node_path) {
  770. _make_constant(NodePath(str));
  771. } else {
  772. _make_constant(str);
  773. }
  774. } break;
  775. case 0xFFFF: {
  776. _make_token(TK_CURSOR);
  777. } break;
  778. default: {
  779. if (_is_number(GETCHAR(0)) || (GETCHAR(0) == '.' && _is_number(GETCHAR(1)))) {
  780. // parse number
  781. bool period_found = false;
  782. bool exponent_found = false;
  783. bool hexa_found = false;
  784. bool bin_found = false;
  785. bool sign_found = false;
  786. String str;
  787. int i = 0;
  788. while (true) {
  789. if (GETCHAR(i) == '.') {
  790. if (period_found || exponent_found) {
  791. _make_error("Invalid numeric constant at '.'");
  792. return;
  793. } else if (bin_found) {
  794. _make_error("Invalid binary constant at '.'");
  795. return;
  796. } else if (hexa_found) {
  797. _make_error("Invalid hexadecimal constant at '.'");
  798. return;
  799. }
  800. period_found = true;
  801. } else if (GETCHAR(i) == 'x') {
  802. if (hexa_found || bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
  803. _make_error("Invalid numeric constant at 'x'");
  804. return;
  805. }
  806. hexa_found = true;
  807. } else if (hexa_found && _is_hex(GETCHAR(i))) {
  808. } else if (!hexa_found && GETCHAR(i) == 'b') {
  809. if (bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
  810. _make_error("Invalid numeric constant at 'b'");
  811. return;
  812. }
  813. bin_found = true;
  814. } else if (!hexa_found && GETCHAR(i) == 'e') {
  815. if (exponent_found || bin_found) {
  816. _make_error("Invalid numeric constant at 'e'");
  817. return;
  818. }
  819. exponent_found = true;
  820. } else if (_is_number(GETCHAR(i))) {
  821. //all ok
  822. } else if (bin_found && _is_bin(GETCHAR(i))) {
  823. } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) {
  824. if (sign_found) {
  825. _make_error("Invalid numeric constant at '-'");
  826. return;
  827. }
  828. sign_found = true;
  829. } else if (GETCHAR(i) == '_') {
  830. i++;
  831. continue; // Included for readability, shouldn't be a part of the string
  832. } else
  833. break;
  834. str += CharType(GETCHAR(i));
  835. i++;
  836. }
  837. if (!(_is_number(str[str.length() - 1]) || (hexa_found && _is_hex(str[str.length() - 1])))) {
  838. _make_error("Invalid numeric constant: " + str);
  839. return;
  840. }
  841. INCPOS(i);
  842. if (hexa_found) {
  843. int64_t val = str.hex_to_int64();
  844. _make_constant(val);
  845. } else if (bin_found) {
  846. int64_t val = str.bin_to_int64();
  847. _make_constant(val);
  848. } else if (period_found || exponent_found) {
  849. double val = str.to_double();
  850. _make_constant(val);
  851. } else {
  852. int64_t val = str.to_int64();
  853. _make_constant(val);
  854. }
  855. return;
  856. }
  857. if (GETCHAR(0) == '.') {
  858. //parse period
  859. _make_token(TK_PERIOD);
  860. break;
  861. }
  862. if (_is_text_char(GETCHAR(0))) {
  863. // parse identifier
  864. String str;
  865. str += CharType(GETCHAR(0));
  866. int i = 1;
  867. while (_is_text_char(GETCHAR(i))) {
  868. str += CharType(GETCHAR(i));
  869. i++;
  870. }
  871. bool identifier = false;
  872. if (str == "null") {
  873. _make_constant(Variant());
  874. } else if (str == "true") {
  875. _make_constant(true);
  876. } else if (str == "false") {
  877. _make_constant(false);
  878. } else {
  879. bool found = false;
  880. {
  881. int idx = 0;
  882. while (_type_list[idx].text) {
  883. if (str == _type_list[idx].text) {
  884. _make_type(_type_list[idx].type);
  885. found = true;
  886. break;
  887. }
  888. idx++;
  889. }
  890. }
  891. if (!found) {
  892. //built in func?
  893. for (int j = 0; j < GDScriptFunctions::FUNC_MAX; j++) {
  894. if (str == GDScriptFunctions::get_func_name(GDScriptFunctions::Function(j))) {
  895. _make_built_in_func(GDScriptFunctions::Function(j));
  896. found = true;
  897. break;
  898. }
  899. }
  900. }
  901. if (!found) {
  902. //keyword
  903. int idx = 0;
  904. found = false;
  905. while (_keyword_list[idx].text) {
  906. if (str == _keyword_list[idx].text) {
  907. _make_token(_keyword_list[idx].token);
  908. found = true;
  909. break;
  910. }
  911. idx++;
  912. }
  913. }
  914. if (!found)
  915. identifier = true;
  916. }
  917. if (identifier) {
  918. _make_identifier(str);
  919. }
  920. INCPOS(str.length());
  921. return;
  922. }
  923. _make_error("Unknown character");
  924. return;
  925. } break;
  926. }
  927. INCPOS(1);
  928. break;
  929. }
  930. }
  931. void GDScriptTokenizerText::set_code(const String &p_code) {
  932. code = p_code;
  933. len = p_code.length();
  934. if (len) {
  935. _code = &code[0];
  936. } else {
  937. _code = NULL;
  938. }
  939. code_pos = 0;
  940. line = 1; //it is stand-ar-ized that lines begin in 1 in code..
  941. column = 1; //the same holds for columns
  942. tk_rb_pos = 0;
  943. error_flag = false;
  944. #ifdef DEBUG_ENABLED
  945. ignore_warnings = false;
  946. #endif // DEBUG_ENABLED
  947. last_error = "";
  948. for (int i = 0; i < MAX_LOOKAHEAD + 1; i++)
  949. _advance();
  950. }
  951. GDScriptTokenizerText::Token GDScriptTokenizerText::get_token(int p_offset) const {
  952. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, TK_ERROR);
  953. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, TK_ERROR);
  954. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  955. return tk_rb[ofs].type;
  956. }
  957. int GDScriptTokenizerText::get_token_line(int p_offset) const {
  958. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1);
  959. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1);
  960. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  961. return tk_rb[ofs].line;
  962. }
  963. int GDScriptTokenizerText::get_token_column(int p_offset) const {
  964. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1);
  965. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1);
  966. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  967. return tk_rb[ofs].col;
  968. }
  969. const Variant &GDScriptTokenizerText::get_token_constant(int p_offset) const {
  970. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant);
  971. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant);
  972. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  973. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_CONSTANT, tk_rb[0].constant);
  974. return tk_rb[ofs].constant;
  975. }
  976. StringName GDScriptTokenizerText::get_token_identifier(int p_offset) const {
  977. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, StringName());
  978. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, StringName());
  979. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  980. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_IDENTIFIER, StringName());
  981. return tk_rb[ofs].identifier;
  982. }
  983. GDScriptFunctions::Function GDScriptTokenizerText::get_token_built_in_func(int p_offset) const {
  984. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, GDScriptFunctions::FUNC_MAX);
  985. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, GDScriptFunctions::FUNC_MAX);
  986. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  987. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_FUNC, GDScriptFunctions::FUNC_MAX);
  988. return tk_rb[ofs].func;
  989. }
  990. Variant::Type GDScriptTokenizerText::get_token_type(int p_offset) const {
  991. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, Variant::NIL);
  992. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, Variant::NIL);
  993. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  994. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_TYPE, Variant::NIL);
  995. return tk_rb[ofs].vtype;
  996. }
  997. int GDScriptTokenizerText::get_token_line_indent(int p_offset) const {
  998. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0);
  999. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0);
  1000. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  1001. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0);
  1002. return tk_rb[ofs].constant.operator Vector2().x;
  1003. }
  1004. int GDScriptTokenizerText::get_token_line_tab_indent(int p_offset) const {
  1005. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0);
  1006. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0);
  1007. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  1008. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0);
  1009. return tk_rb[ofs].constant.operator Vector2().y;
  1010. }
  1011. String GDScriptTokenizerText::get_token_error(int p_offset) const {
  1012. ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, String());
  1013. ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, String());
  1014. int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
  1015. ERR_FAIL_COND_V(tk_rb[ofs].type != TK_ERROR, String());
  1016. return tk_rb[ofs].constant;
  1017. }
  1018. void GDScriptTokenizerText::advance(int p_amount) {
  1019. ERR_FAIL_COND(p_amount <= 0);
  1020. for (int i = 0; i < p_amount; i++)
  1021. _advance();
  1022. }
  1023. //////////////////////////////////////////////////////////////////////////////////////////////////////
  1024. #define BYTECODE_VERSION 13
  1025. Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) {
  1026. const uint8_t *buf = p_buffer.ptr();
  1027. int total_len = p_buffer.size();
  1028. ERR_FAIL_COND_V(p_buffer.size() < 24 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA);
  1029. int version = decode_uint32(&buf[4]);
  1030. ERR_FAIL_COND_V_MSG(version > BYTECODE_VERSION, ERR_INVALID_DATA, "Bytecode is too recent! Please use a newer engine version.");
  1031. int identifier_count = decode_uint32(&buf[8]);
  1032. int constant_count = decode_uint32(&buf[12]);
  1033. int line_count = decode_uint32(&buf[16]);
  1034. int token_count = decode_uint32(&buf[20]);
  1035. const uint8_t *b = &buf[24];
  1036. total_len -= 24;
  1037. identifiers.resize(identifier_count);
  1038. for (int i = 0; i < identifier_count; i++) {
  1039. int len = decode_uint32(b);
  1040. ERR_FAIL_COND_V(len > total_len, ERR_INVALID_DATA);
  1041. b += 4;
  1042. Vector<uint8_t> cs;
  1043. cs.resize(len);
  1044. for (int j = 0; j < len; j++) {
  1045. cs.write[j] = b[j] ^ 0xb6;
  1046. }
  1047. cs.write[cs.size() - 1] = 0;
  1048. String s;
  1049. s.parse_utf8((const char *)cs.ptr());
  1050. b += len;
  1051. total_len -= len + 4;
  1052. identifiers.write[i] = s;
  1053. }
  1054. constants.resize(constant_count);
  1055. for (int i = 0; i < constant_count; i++) {
  1056. Variant v;
  1057. int len;
  1058. // An object cannot be constant, never decode objects
  1059. Error err = decode_variant(v, b, total_len, &len, false);
  1060. if (err)
  1061. return err;
  1062. b += len;
  1063. total_len -= len;
  1064. constants.write[i] = v;
  1065. }
  1066. ERR_FAIL_COND_V(line_count * 8 > total_len, ERR_INVALID_DATA);
  1067. for (int i = 0; i < line_count; i++) {
  1068. uint32_t token = decode_uint32(b);
  1069. b += 4;
  1070. uint32_t linecol = decode_uint32(b);
  1071. b += 4;
  1072. lines.insert(token, linecol);
  1073. total_len -= 8;
  1074. }
  1075. tokens.resize(token_count);
  1076. for (int i = 0; i < token_count; i++) {
  1077. ERR_FAIL_COND_V(total_len < 1, ERR_INVALID_DATA);
  1078. if ((*b) & TOKEN_BYTE_MASK) { //little endian always
  1079. ERR_FAIL_COND_V(total_len < 4, ERR_INVALID_DATA);
  1080. tokens.write[i] = decode_uint32(b) & ~TOKEN_BYTE_MASK;
  1081. b += 4;
  1082. } else {
  1083. tokens.write[i] = *b;
  1084. b += 1;
  1085. total_len--;
  1086. }
  1087. }
  1088. token = 0;
  1089. return OK;
  1090. }
  1091. Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code) {
  1092. Vector<uint8_t> buf;
  1093. Map<StringName, int> identifier_map;
  1094. HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
  1095. Map<uint32_t, int> line_map;
  1096. Vector<uint32_t> token_array;
  1097. GDScriptTokenizerText tt;
  1098. tt.set_code(p_code);
  1099. int line = -1;
  1100. while (true) {
  1101. if (tt.get_token_line() != line) {
  1102. line = tt.get_token_line();
  1103. line_map[line] = token_array.size();
  1104. }
  1105. uint32_t token = tt.get_token();
  1106. switch (tt.get_token()) {
  1107. case TK_IDENTIFIER: {
  1108. StringName id = tt.get_token_identifier();
  1109. if (!identifier_map.has(id)) {
  1110. int idx = identifier_map.size();
  1111. identifier_map[id] = idx;
  1112. }
  1113. token |= identifier_map[id] << TOKEN_BITS;
  1114. } break;
  1115. case TK_CONSTANT: {
  1116. const Variant &c = tt.get_token_constant();
  1117. if (!constant_map.has(c)) {
  1118. int idx = constant_map.size();
  1119. constant_map[c] = idx;
  1120. }
  1121. token |= constant_map[c] << TOKEN_BITS;
  1122. } break;
  1123. case TK_BUILT_IN_TYPE: {
  1124. token |= tt.get_token_type() << TOKEN_BITS;
  1125. } break;
  1126. case TK_BUILT_IN_FUNC: {
  1127. token |= tt.get_token_built_in_func() << TOKEN_BITS;
  1128. } break;
  1129. case TK_NEWLINE: {
  1130. token |= tt.get_token_line_indent() << TOKEN_BITS;
  1131. } break;
  1132. case TK_ERROR: {
  1133. ERR_FAIL_V(Vector<uint8_t>());
  1134. } break;
  1135. default: {
  1136. }
  1137. };
  1138. token_array.push_back(token);
  1139. if (tt.get_token() == TK_EOF)
  1140. break;
  1141. tt.advance();
  1142. }
  1143. //reverse maps
  1144. Map<int, StringName> rev_identifier_map;
  1145. for (Map<StringName, int>::Element *E = identifier_map.front(); E; E = E->next()) {
  1146. rev_identifier_map[E->get()] = E->key();
  1147. }
  1148. Map<int, Variant> rev_constant_map;
  1149. const Variant *K = NULL;
  1150. while ((K = constant_map.next(K))) {
  1151. rev_constant_map[constant_map[*K]] = *K;
  1152. }
  1153. Map<int, uint32_t> rev_line_map;
  1154. for (Map<uint32_t, int>::Element *E = line_map.front(); E; E = E->next()) {
  1155. rev_line_map[E->get()] = E->key();
  1156. }
  1157. //save header
  1158. buf.resize(24);
  1159. buf.write[0] = 'G';
  1160. buf.write[1] = 'D';
  1161. buf.write[2] = 'S';
  1162. buf.write[3] = 'C';
  1163. encode_uint32(BYTECODE_VERSION, &buf.write[4]);
  1164. encode_uint32(identifier_map.size(), &buf.write[8]);
  1165. encode_uint32(constant_map.size(), &buf.write[12]);
  1166. encode_uint32(line_map.size(), &buf.write[16]);
  1167. encode_uint32(token_array.size(), &buf.write[20]);
  1168. //save identifiers
  1169. for (Map<int, StringName>::Element *E = rev_identifier_map.front(); E; E = E->next()) {
  1170. CharString cs = String(E->get()).utf8();
  1171. int len = cs.length() + 1;
  1172. int extra = 4 - (len % 4);
  1173. if (extra == 4)
  1174. extra = 0;
  1175. uint8_t ibuf[4];
  1176. encode_uint32(len + extra, ibuf);
  1177. for (int i = 0; i < 4; i++) {
  1178. buf.push_back(ibuf[i]);
  1179. }
  1180. for (int i = 0; i < len; i++) {
  1181. buf.push_back(cs[i] ^ 0xb6);
  1182. }
  1183. for (int i = 0; i < extra; i++) {
  1184. buf.push_back(0 ^ 0xb6);
  1185. }
  1186. }
  1187. for (Map<int, Variant>::Element *E = rev_constant_map.front(); E; E = E->next()) {
  1188. int len;
  1189. // Objects cannot be constant, never encode objects
  1190. Error err = encode_variant(E->get(), NULL, len, false);
  1191. ERR_FAIL_COND_V_MSG(err != OK, Vector<uint8_t>(), "Error when trying to encode Variant.");
  1192. int pos = buf.size();
  1193. buf.resize(pos + len);
  1194. encode_variant(E->get(), &buf.write[pos], len, false);
  1195. }
  1196. for (Map<int, uint32_t>::Element *E = rev_line_map.front(); E; E = E->next()) {
  1197. uint8_t ibuf[8];
  1198. encode_uint32(E->key(), &ibuf[0]);
  1199. encode_uint32(E->get(), &ibuf[4]);
  1200. for (int i = 0; i < 8; i++)
  1201. buf.push_back(ibuf[i]);
  1202. }
  1203. for (int i = 0; i < token_array.size(); i++) {
  1204. uint32_t token = token_array[i];
  1205. if (token & ~TOKEN_MASK) {
  1206. uint8_t buf4[4];
  1207. encode_uint32(token_array[i] | TOKEN_BYTE_MASK, &buf4[0]);
  1208. for (int j = 0; j < 4; j++) {
  1209. buf.push_back(buf4[j]);
  1210. }
  1211. } else {
  1212. buf.push_back(token);
  1213. }
  1214. }
  1215. return buf;
  1216. }
  1217. GDScriptTokenizerBuffer::Token GDScriptTokenizerBuffer::get_token(int p_offset) const {
  1218. int offset = token + p_offset;
  1219. if (offset < 0 || offset >= tokens.size())
  1220. return TK_EOF;
  1221. return GDScriptTokenizerBuffer::Token(tokens[offset] & TOKEN_MASK);
  1222. }
  1223. StringName GDScriptTokenizerBuffer::get_token_identifier(int p_offset) const {
  1224. int offset = token + p_offset;
  1225. ERR_FAIL_INDEX_V(offset, tokens.size(), StringName());
  1226. uint32_t identifier = tokens[offset] >> TOKEN_BITS;
  1227. ERR_FAIL_UNSIGNED_INDEX_V(identifier, (uint32_t)identifiers.size(), StringName());
  1228. return identifiers[identifier];
  1229. }
  1230. GDScriptFunctions::Function GDScriptTokenizerBuffer::get_token_built_in_func(int p_offset) const {
  1231. int offset = token + p_offset;
  1232. ERR_FAIL_INDEX_V(offset, tokens.size(), GDScriptFunctions::FUNC_MAX);
  1233. return GDScriptFunctions::Function(tokens[offset] >> TOKEN_BITS);
  1234. }
  1235. Variant::Type GDScriptTokenizerBuffer::get_token_type(int p_offset) const {
  1236. int offset = token + p_offset;
  1237. ERR_FAIL_INDEX_V(offset, tokens.size(), Variant::NIL);
  1238. return Variant::Type(tokens[offset] >> TOKEN_BITS);
  1239. }
  1240. int GDScriptTokenizerBuffer::get_token_line(int p_offset) const {
  1241. int offset = token + p_offset;
  1242. int pos = lines.find_nearest(offset);
  1243. if (pos < 0)
  1244. return -1;
  1245. if (pos >= lines.size())
  1246. pos = lines.size() - 1;
  1247. uint32_t l = lines.getv(pos);
  1248. return l & TOKEN_LINE_MASK;
  1249. }
  1250. int GDScriptTokenizerBuffer::get_token_column(int p_offset) const {
  1251. int offset = token + p_offset;
  1252. int pos = lines.find_nearest(offset);
  1253. if (pos < 0)
  1254. return -1;
  1255. if (pos >= lines.size())
  1256. pos = lines.size() - 1;
  1257. uint32_t l = lines.getv(pos);
  1258. return l >> TOKEN_LINE_BITS;
  1259. }
  1260. int GDScriptTokenizerBuffer::get_token_line_indent(int p_offset) const {
  1261. int offset = token + p_offset;
  1262. ERR_FAIL_INDEX_V(offset, tokens.size(), 0);
  1263. return tokens[offset] >> TOKEN_BITS;
  1264. }
  1265. const Variant &GDScriptTokenizerBuffer::get_token_constant(int p_offset) const {
  1266. int offset = token + p_offset;
  1267. ERR_FAIL_INDEX_V(offset, tokens.size(), nil);
  1268. uint32_t constant = tokens[offset] >> TOKEN_BITS;
  1269. ERR_FAIL_UNSIGNED_INDEX_V(constant, (uint32_t)constants.size(), nil);
  1270. return constants[constant];
  1271. }
  1272. String GDScriptTokenizerBuffer::get_token_error(int p_offset) const {
  1273. ERR_FAIL_V(String());
  1274. }
  1275. void GDScriptTokenizerBuffer::advance(int p_amount) {
  1276. ERR_FAIL_INDEX(p_amount + token, tokens.size());
  1277. token += p_amount;
  1278. }
  1279. GDScriptTokenizerBuffer::GDScriptTokenizerBuffer() {
  1280. token = 0;
  1281. }