gdscript_tokenizer.cpp 33 KB

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