2
0

gdscript_tokenizer.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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/error_macros.h"
  32. #ifdef TOOLS_ENABLED
  33. #include "editor/editor_settings.h"
  34. #endif
  35. static const char *token_names[] = {
  36. "Empty", // EMPTY,
  37. // Basic
  38. "Annotation", // ANNOTATION
  39. "Identifier", // IDENTIFIER,
  40. "Literal", // LITERAL,
  41. // Comparison
  42. "<", // LESS,
  43. "<=", // LESS_EQUAL,
  44. ">", // GREATER,
  45. ">=", // GREATER_EQUAL,
  46. "==", // EQUAL_EQUAL,
  47. "!=", // BANG_EQUAL,
  48. // Logical
  49. "and", // AND,
  50. "or", // OR,
  51. "not", // NOT,
  52. "&&", // AMPERSAND_AMPERSAND,
  53. "||", // PIPE_PIPE,
  54. "!", // BANG,
  55. // Bitwise
  56. "&", // AMPERSAND,
  57. "|", // PIPE,
  58. "~", // TILDE,
  59. "^", // CARET,
  60. "<<", // LESS_LESS,
  61. ">>", // GREATER_GREATER,
  62. // Math
  63. "+", // PLUS,
  64. "-", // MINUS,
  65. "*", // STAR,
  66. "/", // SLASH,
  67. "%", // PERCENT,
  68. // Assignment
  69. "=", // EQUAL,
  70. "+=", // PLUS_EQUAL,
  71. "-=", // MINUS_EQUAL,
  72. "*=", // STAR_EQUAL,
  73. "/=", // SLASH_EQUAL,
  74. "%=", // PERCENT_EQUAL,
  75. "<<=", // LESS_LESS_EQUAL,
  76. ">>=", // GREATER_GREATER_EQUAL,
  77. "&=", // AMPERSAND_EQUAL,
  78. "|=", // PIPE_EQUAL,
  79. "^=", // CARET_EQUAL,
  80. // Control flow
  81. "if", // IF,
  82. "elif", // ELIF,
  83. "else", // ELSE,
  84. "for", // FOR,
  85. "while", // WHILE,
  86. "break", // BREAK,
  87. "continue", // CONTINUE,
  88. "pass", // PASS,
  89. "return", // RETURN,
  90. "match", // MATCH,
  91. // Keywords
  92. "as", // AS,
  93. "assert", // ASSERT,
  94. "await", // AWAIT,
  95. "breakpoint", // BREAKPOINT,
  96. "class", // CLASS,
  97. "class_name", // CLASS_NAME,
  98. "const", // CONST,
  99. "enum", // ENUM,
  100. "extends", // EXTENDS,
  101. "func", // FUNC,
  102. "in", // IN,
  103. "is", // IS,
  104. "namespace", // NAMESPACE
  105. "preload", // PRELOAD,
  106. "self", // SELF,
  107. "signal", // SIGNAL,
  108. "static", // STATIC,
  109. "super", // SUPER,
  110. "trait", // TRAIT,
  111. "var", // VAR,
  112. "void", // VOID,
  113. "yield", // YIELD,
  114. // Punctuation
  115. "[", // BRACKET_OPEN,
  116. "]", // BRACKET_CLOSE,
  117. "{", // BRACE_OPEN,
  118. "}", // BRACE_CLOSE,
  119. "(", // PARENTHESIS_OPEN,
  120. ")", // PARENTHESIS_CLOSE,
  121. ",", // COMMA,
  122. ";", // SEMICOLON,
  123. ".", // PERIOD,
  124. "..", // PERIOD_PERIOD,
  125. ":", // COLON,
  126. "$", // DOLLAR,
  127. "->", // FORWARD_ARROW,
  128. "_", // UNDERSCORE,
  129. // Whitespace
  130. "Newline", // NEWLINE,
  131. "Indent", // INDENT,
  132. "Dedent", // DEDENT,
  133. // Constants
  134. "PI", // CONST_PI,
  135. "TAU", // CONST_TAU,
  136. "INF", // CONST_INF,
  137. "NaN", // CONST_NAN,
  138. // Error message improvement
  139. "VCS conflict marker", // VCS_CONFLICT_MARKER,
  140. "`", // BACKTICK,
  141. "?", // QUESTION_MARK,
  142. // Special
  143. "Error", // ERROR,
  144. "End of file", // EOF,
  145. };
  146. // Avoid desync.
  147. static_assert(sizeof(token_names) / sizeof(token_names[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of token names don't match the amount of token types.");
  148. const char *GDScriptTokenizer::Token::get_name() const {
  149. ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");
  150. return token_names[type];
  151. }
  152. bool GDScriptTokenizer::Token::is_identifier() const {
  153. // Note: Most keywords should not be recognized as identifiers.
  154. // These are only exceptions for stuff that already is on the engine's API.
  155. switch (type) {
  156. case IDENTIFIER:
  157. case MATCH: // Used in String.match().
  158. return true;
  159. default:
  160. return false;
  161. }
  162. }
  163. bool GDScriptTokenizer::Token::is_node_name() const {
  164. // This is meant to allow keywords with the $ notation, but not as general identifiers.
  165. switch (type) {
  166. case IDENTIFIER:
  167. case AND:
  168. case AS:
  169. case ASSERT:
  170. case AWAIT:
  171. case BREAK:
  172. case BREAKPOINT:
  173. case CLASS_NAME:
  174. case CLASS:
  175. case CONST:
  176. case CONTINUE:
  177. case ELIF:
  178. case ELSE:
  179. case ENUM:
  180. case EXTENDS:
  181. case FOR:
  182. case FUNC:
  183. case IF:
  184. case IN:
  185. case IS:
  186. case MATCH:
  187. case NAMESPACE:
  188. case NOT:
  189. case OR:
  190. case PASS:
  191. case PRELOAD:
  192. case RETURN:
  193. case SELF:
  194. case SIGNAL:
  195. case STATIC:
  196. case SUPER:
  197. case TRAIT:
  198. case UNDERSCORE:
  199. case VAR:
  200. case VOID:
  201. case WHILE:
  202. case YIELD:
  203. return true;
  204. default:
  205. return false;
  206. }
  207. }
  208. String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {
  209. ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");
  210. return token_names[p_token_type];
  211. }
  212. void GDScriptTokenizer::set_source_code(const String &p_source_code) {
  213. source = p_source_code;
  214. if (source.empty()) {
  215. _source = L"";
  216. } else {
  217. _source = source.ptr();
  218. }
  219. _current = _source;
  220. line = 1;
  221. column = 1;
  222. length = p_source_code.length();
  223. position = 0;
  224. }
  225. void GDScriptTokenizer::set_cursor_position(int p_line, int p_column) {
  226. cursor_line = p_line;
  227. cursor_column = p_column;
  228. }
  229. void GDScriptTokenizer::set_multiline_mode(bool p_state) {
  230. multiline_mode = p_state;
  231. }
  232. int GDScriptTokenizer::get_cursor_line() const {
  233. return cursor_line;
  234. }
  235. int GDScriptTokenizer::get_cursor_column() const {
  236. return cursor_column;
  237. }
  238. bool GDScriptTokenizer::is_past_cursor() const {
  239. if (line < cursor_line) {
  240. return false;
  241. }
  242. if (line > cursor_line) {
  243. return true;
  244. }
  245. if (column < cursor_column) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. CharType GDScriptTokenizer::_advance() {
  251. if (unlikely(_is_at_end())) {
  252. return '\0';
  253. }
  254. _current++;
  255. column++;
  256. position++;
  257. if (column > rightmost_column) {
  258. rightmost_column = column;
  259. }
  260. if (unlikely(_is_at_end())) {
  261. // Add extra newline even if it's not there, to satisfy the parser.
  262. newline(true);
  263. // Also add needed unindent.
  264. check_indent();
  265. }
  266. return _peek(-1);
  267. }
  268. void GDScriptTokenizer::push_paren(CharType p_char) {
  269. paren_stack.push_back(p_char);
  270. }
  271. bool GDScriptTokenizer::pop_paren(CharType p_expected) {
  272. if (paren_stack.empty()) {
  273. return false;
  274. }
  275. CharType actual = paren_stack.back()->get();
  276. paren_stack.pop_back();
  277. return actual == p_expected;
  278. }
  279. GDScriptTokenizer::Token GDScriptTokenizer::pop_error() {
  280. Token error = error_stack.back()->get();
  281. error_stack.pop_back();
  282. return error;
  283. }
  284. static bool _is_alphanumeric(CharType c) {
  285. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
  286. }
  287. static bool _is_digit(CharType c) {
  288. return (c >= '0' && c <= '9');
  289. }
  290. static bool _is_hex_digit(CharType c) {
  291. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  292. }
  293. static bool _is_binary_digit(CharType c) {
  294. return (c == '0' || c == '1');
  295. }
  296. GDScriptTokenizer::Token GDScriptTokenizer::make_token(Token::Type p_type) {
  297. Token token(p_type);
  298. token.start_line = start_line;
  299. token.end_line = line;
  300. token.start_column = start_column;
  301. token.end_column = column;
  302. token.leftmost_column = leftmost_column;
  303. token.rightmost_column = rightmost_column;
  304. token.source = String(_start, _current - _start);
  305. if (p_type != Token::ERROR && cursor_line > -1) {
  306. // Also count whitespace after token.
  307. int offset = 0;
  308. while (_peek(offset) == ' ' || _peek(offset) == '\t') {
  309. offset++;
  310. }
  311. int last_column = column + offset;
  312. // Check cursor position in token.
  313. if (start_line == line) {
  314. // Single line token.
  315. if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {
  316. token.cursor_position = cursor_column - start_column;
  317. if (cursor_column == start_column) {
  318. token.cursor_place = CURSOR_BEGINNING;
  319. } else if (cursor_column < column) {
  320. token.cursor_place = CURSOR_MIDDLE;
  321. } else {
  322. token.cursor_place = CURSOR_END;
  323. }
  324. }
  325. } else {
  326. // Multi line token.
  327. if (cursor_line == start_line && cursor_column >= start_column) {
  328. // Is in first line.
  329. token.cursor_position = cursor_column - start_column;
  330. if (cursor_column == start_column) {
  331. token.cursor_place = CURSOR_BEGINNING;
  332. } else {
  333. token.cursor_place = CURSOR_MIDDLE;
  334. }
  335. } else if (cursor_line == line && cursor_column <= last_column) {
  336. // Is in last line.
  337. token.cursor_position = cursor_column - start_column;
  338. if (cursor_column < column) {
  339. token.cursor_place = CURSOR_MIDDLE;
  340. } else {
  341. token.cursor_place = CURSOR_END;
  342. }
  343. } else if (cursor_line > start_line && cursor_line < line) {
  344. // Is in middle line.
  345. token.cursor_position = CURSOR_MIDDLE;
  346. }
  347. }
  348. }
  349. return token;
  350. }
  351. GDScriptTokenizer::Token GDScriptTokenizer::make_literal(const Variant &p_literal) {
  352. Token token = make_token(Token::LITERAL);
  353. token.literal = p_literal;
  354. return token;
  355. }
  356. GDScriptTokenizer::Token GDScriptTokenizer::make_identifier(const StringName &p_identifier) {
  357. Token identifier = make_token(Token::IDENTIFIER);
  358. identifier.literal = p_identifier;
  359. return identifier;
  360. }
  361. GDScriptTokenizer::Token GDScriptTokenizer::make_error(const String &p_message) {
  362. Token error = make_token(Token::ERROR);
  363. error.literal = p_message;
  364. return error;
  365. }
  366. void GDScriptTokenizer::push_error(const String &p_message) {
  367. Token error = make_error(p_message);
  368. error_stack.push_back(error);
  369. }
  370. void GDScriptTokenizer::push_error(const Token &p_error) {
  371. error_stack.push_back(p_error);
  372. }
  373. GDScriptTokenizer::Token GDScriptTokenizer::make_paren_error(CharType p_paren) {
  374. if (paren_stack.empty()) {
  375. return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));
  376. }
  377. Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));
  378. paren_stack.pop_back(); // Remove opening one anyway.
  379. return error;
  380. }
  381. GDScriptTokenizer::Token GDScriptTokenizer::check_vcs_marker(CharType p_test, Token::Type p_double_type) {
  382. const CharType *next = _current + 1;
  383. int chars = 2; // Two already matched.
  384. // Test before consuming characters, since we don't want to consume more than needed.
  385. while (*next == p_test) {
  386. chars++;
  387. next++;
  388. }
  389. if (chars >= 7) {
  390. // It is a VCS conflict marker.
  391. while (chars > 1) {
  392. // Consume all characters (first was already consumed by scan()).
  393. _advance();
  394. chars--;
  395. }
  396. return make_token(Token::VCS_CONFLICT_MARKER);
  397. } else {
  398. // It is only a regular double character token, so we consume the second character.
  399. _advance();
  400. return make_token(p_double_type);
  401. }
  402. }
  403. GDScriptTokenizer::Token GDScriptTokenizer::annotation() {
  404. if (!_is_alphanumeric(_peek())) {
  405. push_error("Expected annotation identifier after \"@\".");
  406. }
  407. while (_is_alphanumeric(_peek())) {
  408. // Consume all identifier characters.
  409. _advance();
  410. }
  411. Token annotation = make_token(Token::ANNOTATION);
  412. annotation.literal = StringName(annotation.source);
  413. return annotation;
  414. }
  415. GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() {
  416. #define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
  417. KEYWORD_GROUP('a') \
  418. KEYWORD("as", Token::AS) \
  419. KEYWORD("and", Token::AND) \
  420. KEYWORD("assert", Token::ASSERT) \
  421. KEYWORD("await", Token::AWAIT) \
  422. KEYWORD_GROUP('b') \
  423. KEYWORD("break", Token::BREAK) \
  424. KEYWORD("breakpoint", Token::BREAKPOINT) \
  425. KEYWORD_GROUP('c') \
  426. KEYWORD("class", Token::CLASS) \
  427. KEYWORD("class_name", Token::CLASS_NAME) \
  428. KEYWORD("const", Token::CONST) \
  429. KEYWORD("continue", Token::CONTINUE) \
  430. KEYWORD_GROUP('e') \
  431. KEYWORD("elif", Token::ELIF) \
  432. KEYWORD("else", Token::ELSE) \
  433. KEYWORD("enum", Token::ENUM) \
  434. KEYWORD("extends", Token::EXTENDS) \
  435. KEYWORD_GROUP('f') \
  436. KEYWORD("for", Token::FOR) \
  437. KEYWORD("func", Token::FUNC) \
  438. KEYWORD_GROUP('i') \
  439. KEYWORD("if", Token::IF) \
  440. KEYWORD("in", Token::IN) \
  441. KEYWORD("is", Token::IS) \
  442. KEYWORD_GROUP('m') \
  443. KEYWORD("match", Token::MATCH) \
  444. KEYWORD_GROUP('n') \
  445. KEYWORD("namespace", Token::NAMESPACE) \
  446. KEYWORD("not", Token::NOT) \
  447. KEYWORD_GROUP('o') \
  448. KEYWORD("or", Token::OR) \
  449. KEYWORD_GROUP('p') \
  450. KEYWORD("pass", Token::PASS) \
  451. KEYWORD("preload", Token::PRELOAD) \
  452. KEYWORD_GROUP('r') \
  453. KEYWORD("return", Token::RETURN) \
  454. KEYWORD_GROUP('s') \
  455. KEYWORD("self", Token::SELF) \
  456. KEYWORD("signal", Token::SIGNAL) \
  457. KEYWORD("static", Token::STATIC) \
  458. KEYWORD("super", Token::SUPER) \
  459. KEYWORD_GROUP('t') \
  460. KEYWORD("trait", Token::TRAIT) \
  461. KEYWORD_GROUP('v') \
  462. KEYWORD("var", Token::VAR) \
  463. KEYWORD("void", Token::VOID) \
  464. KEYWORD_GROUP('w') \
  465. KEYWORD("while", Token::WHILE) \
  466. KEYWORD_GROUP('y') \
  467. KEYWORD("yield", Token::YIELD) \
  468. KEYWORD_GROUP('I') \
  469. KEYWORD("INF", Token::CONST_INF) \
  470. KEYWORD_GROUP('N') \
  471. KEYWORD("NAN", Token::CONST_NAN) \
  472. KEYWORD_GROUP('P') \
  473. KEYWORD("PI", Token::CONST_PI) \
  474. KEYWORD_GROUP('T') \
  475. KEYWORD("TAU", Token::CONST_TAU)
  476. #define MIN_KEYWORD_LENGTH 2
  477. #define MAX_KEYWORD_LENGTH 10
  478. // Consume all alphanumeric characters.
  479. while (_is_alphanumeric(_peek())) {
  480. _advance();
  481. }
  482. int length = _current - _start;
  483. if (length == 1 && _peek(-1) == '_') {
  484. // Lone underscore.
  485. return make_token(Token::UNDERSCORE);
  486. }
  487. String name(_start, length);
  488. if (length < MIN_KEYWORD_LENGTH || length > MAX_KEYWORD_LENGTH) {
  489. // Cannot be a keyword, as the length doesn't match any.
  490. return make_identifier(name);
  491. }
  492. // Define some helper macros for the switch case.
  493. #define KEYWORD_GROUP_CASE(char) \
  494. break; \
  495. case char:
  496. #define KEYWORD(keyword, token_type) \
  497. { \
  498. const int keyword_length = sizeof(keyword) - 1; \
  499. static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
  500. static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
  501. if (keyword_length == length && name == keyword) { \
  502. return make_token(token_type); \
  503. } \
  504. }
  505. // Find if it's a keyword.
  506. switch (_start[0]) {
  507. default:
  508. KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
  509. break;
  510. }
  511. // Check if it's a special literal
  512. if (length == 4) {
  513. if (name == "true") {
  514. return make_literal(true);
  515. } else if (name == "null") {
  516. return make_literal(Variant());
  517. }
  518. } else if (length == 5) {
  519. if (name == "false") {
  520. return make_literal(false);
  521. }
  522. }
  523. // Not a keyword, so must be an identifier.
  524. return make_identifier(name);
  525. #undef KEYWORDS
  526. #undef MIN_KEYWORD_LENGTH
  527. #undef MAX_KEYWORD_LENGTH
  528. #undef KEYWORD_GROUP_CASE
  529. #undef KEYWORD
  530. }
  531. void GDScriptTokenizer::newline(bool p_make_token) {
  532. // Don't overwrite previous newline, nor create if we want a line contination.
  533. if (p_make_token && !pending_newline && !line_continuation) {
  534. Token newline(Token::NEWLINE);
  535. newline.start_line = line;
  536. newline.end_line = line;
  537. newline.start_column = column - 1;
  538. newline.end_column = column;
  539. newline.leftmost_column = newline.start_column;
  540. newline.rightmost_column = newline.end_column;
  541. pending_newline = true;
  542. last_newline = newline;
  543. }
  544. // Increment line/column counters.
  545. line++;
  546. column = 1;
  547. leftmost_column = 1;
  548. }
  549. GDScriptTokenizer::Token GDScriptTokenizer::number() {
  550. int base = 10;
  551. bool has_decimal = false;
  552. bool has_exponent = false;
  553. bool has_error = false;
  554. bool (*digit_check_func)(CharType) = _is_digit;
  555. if (_peek(-1) == '.') {
  556. has_decimal = true;
  557. } else if (_peek(-1) == '0') {
  558. if (_peek() == 'x') {
  559. // Hexadecimal.
  560. base = 16;
  561. digit_check_func = _is_hex_digit;
  562. _advance();
  563. } else if (_peek() == 'b') {
  564. // Binary.
  565. base = 2;
  566. digit_check_func = _is_binary_digit;
  567. _advance();
  568. }
  569. }
  570. // Allow '_' to be used in a number, for readability.
  571. while (digit_check_func(_peek()) || _peek() == '_') {
  572. _advance();
  573. }
  574. // It might be a ".." token (instead of decimal point) so we check if it's not.
  575. if (_peek() == '.' && _peek(1) != '.') {
  576. if (base == 10 && !has_decimal) {
  577. has_decimal = true;
  578. } else if (base == 10) {
  579. Token error = make_error("Cannot use a decimal point twice in a number.");
  580. error.start_column = column;
  581. error.leftmost_column = column;
  582. error.end_column = column + 1;
  583. error.rightmost_column = column + 1;
  584. push_error(error);
  585. has_error = true;
  586. } else if (base == 16) {
  587. Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
  588. error.start_column = column;
  589. error.leftmost_column = column;
  590. error.end_column = column + 1;
  591. error.rightmost_column = column + 1;
  592. push_error(error);
  593. has_error = true;
  594. } else {
  595. Token error = make_error("Cannot use a decimal point in a binary number.");
  596. error.start_column = column;
  597. error.leftmost_column = column;
  598. error.end_column = column + 1;
  599. error.rightmost_column = column + 1;
  600. push_error(error);
  601. has_error = true;
  602. }
  603. if (!has_error) {
  604. _advance();
  605. // Consume decimal digits.
  606. while (_is_digit(_peek()) || _peek() == '_') {
  607. _advance();
  608. }
  609. }
  610. }
  611. if (base == 10) {
  612. if (_peek() == 'e' || _peek() == 'E') {
  613. has_exponent = true;
  614. _advance();
  615. if (_peek() == '+' || _peek() == '-') {
  616. // Exponent sign.
  617. _advance();
  618. }
  619. // Consume exponent digits.
  620. while (_is_digit(_peek()) || _peek() == '_') {
  621. _advance();
  622. }
  623. }
  624. }
  625. // Detect extra decimal point.
  626. if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
  627. Token error = make_error("Cannot use a decimal point twice in a number.");
  628. error.start_column = column;
  629. error.leftmost_column = column;
  630. error.end_column = column + 1;
  631. error.rightmost_column = column + 1;
  632. push_error(error);
  633. has_error = true;
  634. } else if (_is_alphanumeric(_peek())) {
  635. // Letter at the end of the number.
  636. push_error("Invalid numeric notation.");
  637. }
  638. // Create a string with the whole number.
  639. int length = _current - _start;
  640. String number = String(_start, length).replace("_", "");
  641. // Convert to the appropriate literal type.
  642. if (base == 16) {
  643. int64_t value = number.hex_to_int();
  644. return make_literal(value);
  645. } else if (base == 2) {
  646. int64_t value = number.bin_to_int();
  647. return make_literal(value);
  648. } else if (has_decimal || has_exponent) {
  649. double value = number.to_float();
  650. return make_literal(value);
  651. } else {
  652. int64_t value = number.to_int();
  653. return make_literal(value);
  654. }
  655. }
  656. GDScriptTokenizer::Token GDScriptTokenizer::string() {
  657. enum StringType {
  658. STRING_REGULAR,
  659. STRING_NAME,
  660. STRING_NODEPATH,
  661. };
  662. bool is_multiline = false;
  663. StringType type = STRING_REGULAR;
  664. if (_peek(-1) == '&') {
  665. type = STRING_NAME;
  666. _advance();
  667. } else if (_peek(-1) == '^') {
  668. type = STRING_NODEPATH;
  669. _advance();
  670. }
  671. CharType quote_char = _peek(-1);
  672. if (_peek() == quote_char && _peek(1) == quote_char) {
  673. is_multiline = true;
  674. // Consume all quotes.
  675. _advance();
  676. _advance();
  677. }
  678. String result;
  679. for (;;) {
  680. // Consume actual string.
  681. if (_is_at_end()) {
  682. return make_error("Unterminated string.");
  683. }
  684. CharType ch = _peek();
  685. if (ch == '\\') {
  686. // Escape pattern.
  687. _advance();
  688. if (_is_at_end()) {
  689. return make_error("Unterminated string.");
  690. }
  691. // Grab escape character.
  692. CharType code = _peek();
  693. _advance();
  694. if (_is_at_end()) {
  695. return make_error("Unterminated string.");
  696. }
  697. CharType escaped = 0;
  698. bool valid_escape = true;
  699. switch (code) {
  700. case 'a':
  701. escaped = '\a';
  702. break;
  703. case 'b':
  704. escaped = '\b';
  705. break;
  706. case 'f':
  707. escaped = '\f';
  708. break;
  709. case 'n':
  710. escaped = '\n';
  711. break;
  712. case 'r':
  713. escaped = '\r';
  714. break;
  715. case 't':
  716. escaped = '\t';
  717. break;
  718. case 'v':
  719. escaped = '\v';
  720. break;
  721. case '\'':
  722. escaped = '\'';
  723. break;
  724. case '\"':
  725. escaped = '\"';
  726. break;
  727. case '\\':
  728. escaped = '\\';
  729. break;
  730. case 'u':
  731. // Hexadecimal sequence.
  732. for (int i = 0; i < 4; i++) {
  733. if (_is_at_end()) {
  734. return make_error("Unterminated string.");
  735. }
  736. CharType digit = _peek();
  737. CharType value = 0;
  738. if (digit >= '0' && digit <= '9') {
  739. value = digit - '0';
  740. } else if (digit >= 'a' && digit <= 'f') {
  741. value = digit - 'a';
  742. value += 10;
  743. } else if (digit >= 'A' && digit <= 'F') {
  744. value = digit - 'A';
  745. value += 10;
  746. } else {
  747. // Make error, but keep parsing the string.
  748. Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
  749. error.start_column = column;
  750. error.leftmost_column = error.start_column;
  751. error.end_column = column + 1;
  752. error.rightmost_column = error.end_column;
  753. push_error(error);
  754. valid_escape = false;
  755. break;
  756. }
  757. escaped <<= 4;
  758. escaped |= value;
  759. _advance();
  760. }
  761. break;
  762. case '\r':
  763. if (_peek() != '\n') {
  764. // Carriage return without newline in string. (???)
  765. // Just add it to the string and keep going.
  766. result += ch;
  767. _advance();
  768. break;
  769. }
  770. [[fallthrough]];
  771. case '\n':
  772. // Escaping newline.
  773. newline(false);
  774. valid_escape = false; // Don't add to the string.
  775. break;
  776. default:
  777. Token error = make_error("Invalid escape in string.");
  778. error.start_column = column - 2;
  779. error.leftmost_column = error.start_column;
  780. push_error(error);
  781. valid_escape = false;
  782. break;
  783. }
  784. if (valid_escape) {
  785. result += escaped;
  786. }
  787. } else if (ch == quote_char) {
  788. _advance();
  789. if (is_multiline) {
  790. if (_peek() == quote_char && _peek(1) == quote_char) {
  791. // Ended the multiline string. Consume all quotes.
  792. _advance();
  793. _advance();
  794. break;
  795. }
  796. } else {
  797. // Ended single-line string.
  798. break;
  799. }
  800. } else {
  801. result += ch;
  802. _advance();
  803. if (ch == '\n') {
  804. newline(false);
  805. }
  806. }
  807. }
  808. // Make the literal.
  809. Variant string;
  810. switch (type) {
  811. case STRING_NAME:
  812. string = StringName(result);
  813. break;
  814. case STRING_NODEPATH:
  815. string = NodePath(result);
  816. break;
  817. case STRING_REGULAR:
  818. string = result;
  819. break;
  820. }
  821. return make_literal(string);
  822. }
  823. void GDScriptTokenizer::check_indent() {
  824. ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
  825. if (_is_at_end()) {
  826. // Send dedents for every indent level.
  827. pending_indents -= indent_level();
  828. indent_stack.clear();
  829. return;
  830. }
  831. for (;;) {
  832. CharType current_indent_char = _peek();
  833. int indent_count = 0;
  834. if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
  835. // First character of the line is not whitespace, so we clear all indentation levels.
  836. // Unless we are in a continuation or in multiline mode (inside expression).
  837. if (line_continuation || multiline_mode) {
  838. return;
  839. }
  840. pending_indents -= indent_level();
  841. indent_stack.clear();
  842. return;
  843. }
  844. if (_peek() == '\r') {
  845. _advance();
  846. if (_peek() != '\n') {
  847. push_error("Stray carriage return character in source code.");
  848. }
  849. }
  850. if (_peek() == '\n') {
  851. // Empty line, keep going.
  852. _advance();
  853. newline(false);
  854. continue;
  855. }
  856. // Check indent level.
  857. bool mixed = false;
  858. while (!_is_at_end()) {
  859. CharType space = _peek();
  860. if (space == '\t') {
  861. // Consider individual tab columns.
  862. column += tab_size - 1;
  863. indent_count += tab_size;
  864. } else if (space == ' ') {
  865. indent_count += 1;
  866. } else {
  867. break;
  868. }
  869. mixed = mixed || space != current_indent_char;
  870. _advance();
  871. }
  872. if (mixed) {
  873. Token error = make_error("Mixed use of tabs and spaces for indentation.");
  874. error.start_line = line;
  875. error.start_column = 1;
  876. error.leftmost_column = 1;
  877. error.rightmost_column = column;
  878. push_error(error);
  879. }
  880. if (_is_at_end()) {
  881. // Reached the end with an empty line, so just dedent as much as needed.
  882. pending_indents -= indent_level();
  883. indent_stack.clear();
  884. return;
  885. }
  886. if (_peek() == '\r') {
  887. _advance();
  888. if (_peek() != '\n') {
  889. push_error("Stray carriage return character in source code.");
  890. }
  891. }
  892. if (_peek() == '\n') {
  893. // Empty line, keep going.
  894. _advance();
  895. newline(false);
  896. continue;
  897. }
  898. if (_peek() == '#') {
  899. // Comment. Advance to the next line.
  900. while (_peek() != '\n' && !_is_at_end()) {
  901. _advance();
  902. }
  903. if (_is_at_end()) {
  904. // Reached the end with an empty line, so just dedent as much as needed.
  905. pending_indents -= indent_level();
  906. indent_stack.clear();
  907. return;
  908. }
  909. _advance(); // Consume '\n'.
  910. newline(false);
  911. continue;
  912. }
  913. if (line_continuation || multiline_mode) {
  914. // We cleared up all the whitespace at the beginning of the line.
  915. // But if this is a continuation or multiline mode and we don't want any indentation change.
  916. return;
  917. }
  918. // Check if indentation character is consistent.
  919. if (indent_char == '\0') {
  920. // First time indenting, choose character now.
  921. indent_char = current_indent_char;
  922. } else if (current_indent_char != indent_char) {
  923. Token error = make_error(vformat("Used \"%c\" for indentation instead \"%c\" as used before in the file.", String(&current_indent_char, 1).c_escape(), String(&indent_char, 1).c_escape()));
  924. error.start_line = line;
  925. error.start_column = 1;
  926. error.leftmost_column = 1;
  927. error.rightmost_column = column;
  928. push_error(error);
  929. }
  930. // Now we can do actual indentation changes.
  931. // Check if indent or dedent.
  932. int previous_indent = 0;
  933. if (indent_level() > 0) {
  934. previous_indent = indent_stack.back()->get();
  935. }
  936. if (indent_count == previous_indent) {
  937. // No change in indentation.
  938. return;
  939. }
  940. if (indent_count > previous_indent) {
  941. // Indentation increased.
  942. indent_stack.push_back(indent_count);
  943. pending_indents++;
  944. } else {
  945. // Indentation decreased (dedent).
  946. if (indent_level() == 0) {
  947. push_error("Tokenizer bug: trying to dedent without previous indent.");
  948. return;
  949. }
  950. while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
  951. indent_stack.pop_back();
  952. pending_indents--;
  953. }
  954. if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
  955. // Mismatched indentation alignment.
  956. Token error = make_error("Unindent doesn't match the previous indentation level.");
  957. error.start_line = line;
  958. error.start_column = 1;
  959. error.leftmost_column = 1;
  960. error.end_column = column + 1;
  961. error.rightmost_column = column + 1;
  962. push_error(error);
  963. // Still, we'll be lenient and keep going, so keep this level in the stack.
  964. indent_stack.push_back(indent_count);
  965. }
  966. }
  967. break; // Get out of the loop in any case.
  968. }
  969. }
  970. void GDScriptTokenizer::_skip_whitespace() {
  971. if (pending_indents != 0) {
  972. // Still have some indent/dedent tokens to give.
  973. return;
  974. }
  975. bool is_bol = column == 1; // Beginning of line.
  976. if (is_bol) {
  977. check_indent();
  978. return;
  979. }
  980. for (;;) {
  981. CharType c = _peek();
  982. switch (c) {
  983. case ' ':
  984. _advance();
  985. break;
  986. case '\t':
  987. _advance();
  988. // Consider individual tab columns.
  989. column += tab_size - 1;
  990. break;
  991. case '\r':
  992. _advance(); // Consume either way.
  993. if (_peek() != '\n') {
  994. push_error("Stray carriage return character in source code.");
  995. return;
  996. }
  997. break;
  998. case '\n':
  999. _advance();
  1000. newline(!is_bol); // Don't create new line token if line is empty.
  1001. check_indent();
  1002. break;
  1003. case '#':
  1004. // Comment.
  1005. while (_peek() != '\n' && !_is_at_end()) {
  1006. _advance();
  1007. }
  1008. if (_is_at_end()) {
  1009. return;
  1010. }
  1011. _advance(); // Consume '\n'
  1012. newline(!is_bol);
  1013. check_indent();
  1014. break;
  1015. default:
  1016. return;
  1017. }
  1018. }
  1019. }
  1020. GDScriptTokenizer::Token GDScriptTokenizer::scan() {
  1021. if (has_error()) {
  1022. return pop_error();
  1023. }
  1024. _skip_whitespace();
  1025. if (pending_newline) {
  1026. pending_newline = false;
  1027. if (!multiline_mode) {
  1028. // Don't return newline tokens on multine mode.
  1029. return last_newline;
  1030. }
  1031. }
  1032. // Check for potential errors after skipping whitespace().
  1033. if (has_error()) {
  1034. return pop_error();
  1035. }
  1036. _start = _current;
  1037. start_line = line;
  1038. start_column = column;
  1039. leftmost_column = column;
  1040. rightmost_column = column;
  1041. if (pending_indents != 0) {
  1042. // Adjust position for indent.
  1043. _start -= start_column - 1;
  1044. start_column = 1;
  1045. leftmost_column = 1;
  1046. if (pending_indents > 0) {
  1047. // Indents.
  1048. pending_indents--;
  1049. return make_token(Token::INDENT);
  1050. } else {
  1051. // Dedents.
  1052. pending_indents++;
  1053. Token dedent = make_token(Token::DEDENT);
  1054. dedent.end_column += 1;
  1055. dedent.rightmost_column += 1;
  1056. return dedent;
  1057. }
  1058. }
  1059. if (_is_at_end()) {
  1060. return make_token(Token::TK_EOF);
  1061. }
  1062. const CharType c = _advance();
  1063. if (c == '\\') {
  1064. // Line continuation with backslash.
  1065. if (_peek() == '\r') {
  1066. if (_peek(1) != '\n') {
  1067. return make_error("Unexpected carriage return character.");
  1068. }
  1069. _advance();
  1070. }
  1071. if (_peek() != '\n') {
  1072. return make_error("Expected new line after \"\\\".");
  1073. }
  1074. _advance();
  1075. newline(false);
  1076. line_continuation = true;
  1077. return scan(); // Recurse to get next token.
  1078. }
  1079. line_continuation = false;
  1080. if (_is_digit(c)) {
  1081. return number();
  1082. } else if (_is_alphanumeric(c)) {
  1083. return potential_identifier();
  1084. }
  1085. switch (c) {
  1086. // String literals.
  1087. case '"':
  1088. case '\'':
  1089. return string();
  1090. // Annotation.
  1091. case '@':
  1092. return annotation();
  1093. // Single characters.
  1094. case '~':
  1095. return make_token(Token::TILDE);
  1096. case ',':
  1097. return make_token(Token::COMMA);
  1098. case ':':
  1099. return make_token(Token::COLON);
  1100. case ';':
  1101. return make_token(Token::SEMICOLON);
  1102. case '$':
  1103. return make_token(Token::DOLLAR);
  1104. case '?':
  1105. return make_token(Token::QUESTION_MARK);
  1106. case '`':
  1107. return make_token(Token::BACKTICK);
  1108. // Parens.
  1109. case '(':
  1110. push_paren('(');
  1111. return make_token(Token::PARENTHESIS_OPEN);
  1112. case '[':
  1113. push_paren('[');
  1114. return make_token(Token::BRACKET_OPEN);
  1115. case '{':
  1116. push_paren('{');
  1117. return make_token(Token::BRACE_OPEN);
  1118. case ')':
  1119. if (!pop_paren('(')) {
  1120. return make_paren_error(c);
  1121. }
  1122. return make_token(Token::PARENTHESIS_CLOSE);
  1123. case ']':
  1124. if (!pop_paren('[')) {
  1125. return make_paren_error(c);
  1126. }
  1127. return make_token(Token::BRACKET_CLOSE);
  1128. case '}':
  1129. if (!pop_paren('{')) {
  1130. return make_paren_error(c);
  1131. }
  1132. return make_token(Token::BRACE_CLOSE);
  1133. // Double characters.
  1134. case '!':
  1135. if (_peek() == '=') {
  1136. _advance();
  1137. return make_token(Token::BANG_EQUAL);
  1138. } else {
  1139. return make_token(Token::BANG);
  1140. }
  1141. case '.':
  1142. if (_peek() == '.') {
  1143. _advance();
  1144. return make_token(Token::PERIOD_PERIOD);
  1145. } else if (_is_digit(_peek())) {
  1146. // Number starting with '.'.
  1147. return number();
  1148. } else {
  1149. return make_token(Token::PERIOD);
  1150. }
  1151. case '+':
  1152. if (_peek() == '=') {
  1153. _advance();
  1154. return make_token(Token::PLUS_EQUAL);
  1155. } else {
  1156. return make_token(Token::PLUS);
  1157. }
  1158. case '-':
  1159. if (_peek() == '=') {
  1160. _advance();
  1161. return make_token(Token::MINUS_EQUAL);
  1162. } else if (_peek() == '>') {
  1163. _advance();
  1164. return make_token(Token::FORWARD_ARROW);
  1165. } else {
  1166. return make_token(Token::MINUS);
  1167. }
  1168. case '*':
  1169. if (_peek() == '=') {
  1170. _advance();
  1171. return make_token(Token::STAR_EQUAL);
  1172. } else {
  1173. return make_token(Token::STAR);
  1174. }
  1175. case '/':
  1176. if (_peek() == '=') {
  1177. _advance();
  1178. return make_token(Token::SLASH_EQUAL);
  1179. } else {
  1180. return make_token(Token::SLASH);
  1181. }
  1182. case '%':
  1183. if (_peek() == '=') {
  1184. _advance();
  1185. return make_token(Token::PERCENT_EQUAL);
  1186. } else {
  1187. return make_token(Token::PERCENT);
  1188. }
  1189. case '^':
  1190. if (_peek() == '=') {
  1191. _advance();
  1192. return make_token(Token::CARET_EQUAL);
  1193. } else if (_peek() == '"' || _peek() == '\'') {
  1194. // Node path
  1195. return string();
  1196. } else {
  1197. return make_token(Token::CARET);
  1198. }
  1199. case '&':
  1200. if (_peek() == '&') {
  1201. _advance();
  1202. return make_token(Token::AMPERSAND_AMPERSAND);
  1203. } else if (_peek() == '=') {
  1204. _advance();
  1205. return make_token(Token::AMPERSAND_EQUAL);
  1206. } else if (_peek() == '"' || _peek() == '\'') {
  1207. // String Name
  1208. return string();
  1209. } else {
  1210. return make_token(Token::AMPERSAND);
  1211. }
  1212. case '|':
  1213. if (_peek() == '|') {
  1214. _advance();
  1215. return make_token(Token::PIPE_PIPE);
  1216. } else if (_peek() == '=') {
  1217. _advance();
  1218. return make_token(Token::PIPE_EQUAL);
  1219. } else {
  1220. return make_token(Token::PIPE);
  1221. }
  1222. // Potential VCS conflict markers.
  1223. case '=':
  1224. if (_peek() == '=') {
  1225. return check_vcs_marker('=', Token::EQUAL_EQUAL);
  1226. } else {
  1227. return make_token(Token::EQUAL);
  1228. }
  1229. case '<':
  1230. if (_peek() == '=') {
  1231. _advance();
  1232. return make_token(Token::LESS_EQUAL);
  1233. } else if (_peek() == '<') {
  1234. if (_peek(1) == '=') {
  1235. _advance();
  1236. _advance(); // Advance both '<' and '='
  1237. return make_token(Token::LESS_LESS_EQUAL);
  1238. } else {
  1239. return check_vcs_marker('<', Token::LESS_LESS);
  1240. }
  1241. } else {
  1242. return make_token(Token::LESS);
  1243. }
  1244. case '>':
  1245. if (_peek() == '=') {
  1246. _advance();
  1247. return make_token(Token::GREATER_EQUAL);
  1248. } else if (_peek() == '>') {
  1249. if (_peek(1) == '=') {
  1250. _advance();
  1251. _advance(); // Advance both '>' and '='
  1252. return make_token(Token::GREATER_GREATER_EQUAL);
  1253. } else {
  1254. return check_vcs_marker('>', Token::GREATER_GREATER);
  1255. }
  1256. } else {
  1257. return make_token(Token::GREATER);
  1258. }
  1259. default:
  1260. return make_error(vformat(R"(Unknown character "%s".")", String(&c, 1)));
  1261. }
  1262. }
  1263. GDScriptTokenizer::GDScriptTokenizer() {
  1264. #ifdef TOOLS_ENABLED
  1265. if (EditorSettings::get_singleton()) {
  1266. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
  1267. }
  1268. #endif // TOOLS_ENABLED
  1269. }