gdscript_tokenizer.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. /**************************************************************************/
  2. /* gdscript_tokenizer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdscript_tokenizer.h"
  31. #include "core/error/error_macros.h"
  32. #include "core/string/char_utils.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "servers/text_server.h"
  35. #endif
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. static const char *token_names[] = {
  40. "Empty", // EMPTY,
  41. // Basic
  42. "Annotation", // ANNOTATION
  43. "Identifier", // IDENTIFIER,
  44. "Literal", // LITERAL,
  45. // Comparison
  46. "<", // LESS,
  47. "<=", // LESS_EQUAL,
  48. ">", // GREATER,
  49. ">=", // GREATER_EQUAL,
  50. "==", // EQUAL_EQUAL,
  51. "!=", // BANG_EQUAL,
  52. // Logical
  53. "and", // AND,
  54. "or", // OR,
  55. "not", // NOT,
  56. "&&", // AMPERSAND_AMPERSAND,
  57. "||", // PIPE_PIPE,
  58. "!", // BANG,
  59. // Bitwise
  60. "&", // AMPERSAND,
  61. "|", // PIPE,
  62. "~", // TILDE,
  63. "^", // CARET,
  64. "<<", // LESS_LESS,
  65. ">>", // GREATER_GREATER,
  66. // Math
  67. "+", // PLUS,
  68. "-", // MINUS,
  69. "*", // STAR,
  70. "**", // STAR_STAR,
  71. "/", // SLASH,
  72. "%", // PERCENT,
  73. // Assignment
  74. "=", // EQUAL,
  75. "+=", // PLUS_EQUAL,
  76. "-=", // MINUS_EQUAL,
  77. "*=", // STAR_EQUAL,
  78. "**=", // STAR_STAR_EQUAL,
  79. "/=", // SLASH_EQUAL,
  80. "%=", // PERCENT_EQUAL,
  81. "<<=", // LESS_LESS_EQUAL,
  82. ">>=", // GREATER_GREATER_EQUAL,
  83. "&=", // AMPERSAND_EQUAL,
  84. "|=", // PIPE_EQUAL,
  85. "^=", // CARET_EQUAL,
  86. // Control flow
  87. "if", // IF,
  88. "elif", // ELIF,
  89. "else", // ELSE,
  90. "for", // FOR,
  91. "while", // WHILE,
  92. "break", // BREAK,
  93. "continue", // CONTINUE,
  94. "pass", // PASS,
  95. "return", // RETURN,
  96. "match", // MATCH,
  97. "when", // WHEN,
  98. // Keywords
  99. "as", // AS,
  100. "assert", // ASSERT,
  101. "await", // AWAIT,
  102. "breakpoint", // BREAKPOINT,
  103. "class", // CLASS,
  104. "class_name", // CLASS_NAME,
  105. "const", // TK_CONST,
  106. "enum", // ENUM,
  107. "extends", // EXTENDS,
  108. "func", // FUNC,
  109. "in", // TK_IN,
  110. "is", // IS,
  111. "namespace", // NAMESPACE
  112. "preload", // PRELOAD,
  113. "self", // SELF,
  114. "signal", // SIGNAL,
  115. "static", // STATIC,
  116. "super", // SUPER,
  117. "trait", // TRAIT,
  118. "var", // VAR,
  119. "void", // TK_VOID,
  120. "yield", // YIELD,
  121. // Punctuation
  122. "[", // BRACKET_OPEN,
  123. "]", // BRACKET_CLOSE,
  124. "{", // BRACE_OPEN,
  125. "}", // BRACE_CLOSE,
  126. "(", // PARENTHESIS_OPEN,
  127. ")", // PARENTHESIS_CLOSE,
  128. ",", // COMMA,
  129. ";", // SEMICOLON,
  130. ".", // PERIOD,
  131. "..", // PERIOD_PERIOD,
  132. "...", // PERIOD_PERIOD_PERIOD,
  133. ":", // COLON,
  134. "$", // DOLLAR,
  135. "->", // FORWARD_ARROW,
  136. "_", // UNDERSCORE,
  137. // Whitespace
  138. "Newline", // NEWLINE,
  139. "Indent", // INDENT,
  140. "Dedent", // DEDENT,
  141. // Constants
  142. "PI", // CONST_PI,
  143. "TAU", // CONST_TAU,
  144. "INF", // CONST_INF,
  145. "NaN", // CONST_NAN,
  146. // Error message improvement
  147. "VCS conflict marker", // VCS_CONFLICT_MARKER,
  148. "`", // BACKTICK,
  149. "?", // QUESTION_MARK,
  150. // Special
  151. "Error", // ERROR,
  152. "End of file", // EOF,
  153. };
  154. // Avoid desync.
  155. static_assert(std::size(token_names) == GDScriptTokenizer::Token::TK_MAX, "Amount of token names don't match the amount of token types.");
  156. const char *GDScriptTokenizer::Token::get_name() const {
  157. ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");
  158. return token_names[type];
  159. }
  160. String GDScriptTokenizer::Token::get_debug_name() const {
  161. switch (type) {
  162. case IDENTIFIER:
  163. return vformat(R"(identifier "%s")", source);
  164. default:
  165. return vformat(R"("%s")", get_name());
  166. }
  167. }
  168. bool GDScriptTokenizer::Token::can_precede_bin_op() const {
  169. switch (type) {
  170. case IDENTIFIER:
  171. case LITERAL:
  172. case SELF:
  173. case BRACKET_CLOSE:
  174. case BRACE_CLOSE:
  175. case PARENTHESIS_CLOSE:
  176. case CONST_PI:
  177. case CONST_TAU:
  178. case CONST_INF:
  179. case CONST_NAN:
  180. return true;
  181. default:
  182. return false;
  183. }
  184. }
  185. bool GDScriptTokenizer::Token::is_identifier() const {
  186. // Note: Most keywords should not be recognized as identifiers.
  187. // These are only exceptions for stuff that already is on the engine's API.
  188. switch (type) {
  189. case IDENTIFIER:
  190. case MATCH: // Used in String.match().
  191. case WHEN: // New keyword, avoid breaking existing code.
  192. // Allow constants to be treated as regular identifiers.
  193. case CONST_PI:
  194. case CONST_INF:
  195. case CONST_NAN:
  196. case CONST_TAU:
  197. return true;
  198. default:
  199. return false;
  200. }
  201. }
  202. bool GDScriptTokenizer::Token::is_node_name() const {
  203. // This is meant to allow keywords with the $ notation, but not as general identifiers.
  204. switch (type) {
  205. case IDENTIFIER:
  206. case AND:
  207. case AS:
  208. case ASSERT:
  209. case AWAIT:
  210. case BREAK:
  211. case BREAKPOINT:
  212. case CLASS_NAME:
  213. case CLASS:
  214. case TK_CONST:
  215. case CONST_PI:
  216. case CONST_INF:
  217. case CONST_NAN:
  218. case CONST_TAU:
  219. case CONTINUE:
  220. case ELIF:
  221. case ELSE:
  222. case ENUM:
  223. case EXTENDS:
  224. case FOR:
  225. case FUNC:
  226. case IF:
  227. case TK_IN:
  228. case IS:
  229. case MATCH:
  230. case NAMESPACE:
  231. case NOT:
  232. case OR:
  233. case PASS:
  234. case PRELOAD:
  235. case RETURN:
  236. case SELF:
  237. case SIGNAL:
  238. case STATIC:
  239. case SUPER:
  240. case TRAIT:
  241. case UNDERSCORE:
  242. case VAR:
  243. case TK_VOID:
  244. case WHILE:
  245. case WHEN:
  246. case YIELD:
  247. return true;
  248. default:
  249. return false;
  250. }
  251. }
  252. String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {
  253. ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");
  254. return token_names[p_token_type];
  255. }
  256. void GDScriptTokenizerText::set_source_code(const String &p_source_code) {
  257. source = p_source_code;
  258. _source = source.get_data();
  259. _current = _source;
  260. _start = _source;
  261. line = 1;
  262. column = 1;
  263. length = p_source_code.length();
  264. position = 0;
  265. }
  266. void GDScriptTokenizerText::set_cursor_position(int p_line, int p_column) {
  267. cursor_line = p_line;
  268. cursor_column = p_column;
  269. }
  270. void GDScriptTokenizerText::set_multiline_mode(bool p_state) {
  271. multiline_mode = p_state;
  272. }
  273. void GDScriptTokenizerText::push_expression_indented_block() {
  274. indent_stack_stack.push_back(indent_stack);
  275. }
  276. void GDScriptTokenizerText::pop_expression_indented_block() {
  277. ERR_FAIL_COND(indent_stack_stack.is_empty());
  278. indent_stack = indent_stack_stack.back()->get();
  279. indent_stack_stack.pop_back();
  280. }
  281. int GDScriptTokenizerText::get_cursor_line() const {
  282. return cursor_line;
  283. }
  284. int GDScriptTokenizerText::get_cursor_column() const {
  285. return cursor_column;
  286. }
  287. bool GDScriptTokenizerText::is_past_cursor() const {
  288. if (line < cursor_line) {
  289. return false;
  290. }
  291. if (line > cursor_line) {
  292. return true;
  293. }
  294. if (column < cursor_column) {
  295. return false;
  296. }
  297. return true;
  298. }
  299. char32_t GDScriptTokenizerText::_advance() {
  300. if (unlikely(_is_at_end())) {
  301. return '\0';
  302. }
  303. _current++;
  304. column++;
  305. position++;
  306. if (unlikely(_is_at_end())) {
  307. // Add extra newline even if it's not there, to satisfy the parser.
  308. newline(true);
  309. // Also add needed unindent.
  310. check_indent();
  311. }
  312. return _peek(-1);
  313. }
  314. void GDScriptTokenizerText::push_paren(char32_t p_char) {
  315. paren_stack.push_back(p_char);
  316. }
  317. bool GDScriptTokenizerText::pop_paren(char32_t p_expected) {
  318. if (paren_stack.is_empty()) {
  319. return false;
  320. }
  321. char32_t actual = paren_stack.back()->get();
  322. paren_stack.pop_back();
  323. return actual == p_expected;
  324. }
  325. GDScriptTokenizer::Token GDScriptTokenizerText::pop_error() {
  326. Token error = error_stack.back()->get();
  327. error_stack.pop_back();
  328. return error;
  329. }
  330. GDScriptTokenizer::Token GDScriptTokenizerText::make_token(Token::Type p_type) {
  331. Token token(p_type);
  332. token.start_line = start_line;
  333. token.end_line = line;
  334. token.start_column = start_column;
  335. token.end_column = column;
  336. token.source = String::utf32(Span(_start, _current - _start));
  337. if (p_type != Token::ERROR && cursor_line > -1) {
  338. // Also count whitespace after token.
  339. int offset = 0;
  340. while (_peek(offset) == ' ' || _peek(offset) == '\t') {
  341. offset++;
  342. }
  343. int last_column = column + offset;
  344. // Check cursor position in token.
  345. if (start_line == line) {
  346. // Single line token.
  347. if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {
  348. token.cursor_position = cursor_column - start_column;
  349. if (cursor_column == start_column) {
  350. token.cursor_place = CURSOR_BEGINNING;
  351. } else if (cursor_column < column) {
  352. token.cursor_place = CURSOR_MIDDLE;
  353. } else {
  354. token.cursor_place = CURSOR_END;
  355. }
  356. }
  357. } else {
  358. // Multi line token.
  359. if (cursor_line == start_line && cursor_column >= start_column) {
  360. // Is in first line.
  361. token.cursor_position = cursor_column - start_column;
  362. if (cursor_column == start_column) {
  363. token.cursor_place = CURSOR_BEGINNING;
  364. } else {
  365. token.cursor_place = CURSOR_MIDDLE;
  366. }
  367. } else if (cursor_line == line && cursor_column <= last_column) {
  368. // Is in last line.
  369. token.cursor_position = cursor_column - start_column;
  370. if (cursor_column < column) {
  371. token.cursor_place = CURSOR_MIDDLE;
  372. } else {
  373. token.cursor_place = CURSOR_END;
  374. }
  375. } else if (cursor_line > start_line && cursor_line < line) {
  376. // Is in middle line.
  377. token.cursor_position = CURSOR_MIDDLE;
  378. }
  379. }
  380. }
  381. last_token = token;
  382. return token;
  383. }
  384. GDScriptTokenizer::Token GDScriptTokenizerText::make_literal(const Variant &p_literal) {
  385. Token token = make_token(Token::LITERAL);
  386. token.literal = p_literal;
  387. return token;
  388. }
  389. GDScriptTokenizer::Token GDScriptTokenizerText::make_identifier(const StringName &p_identifier) {
  390. Token identifier = make_token(Token::IDENTIFIER);
  391. identifier.literal = p_identifier;
  392. return identifier;
  393. }
  394. GDScriptTokenizer::Token GDScriptTokenizerText::make_error(const String &p_message) {
  395. Token error = make_token(Token::ERROR);
  396. error.literal = p_message;
  397. return error;
  398. }
  399. void GDScriptTokenizerText::push_error(const String &p_message) {
  400. Token error = make_error(p_message);
  401. error_stack.push_back(error);
  402. }
  403. void GDScriptTokenizerText::push_error(const Token &p_error) {
  404. error_stack.push_back(p_error);
  405. }
  406. GDScriptTokenizer::Token GDScriptTokenizerText::make_paren_error(char32_t p_paren) {
  407. if (paren_stack.is_empty()) {
  408. return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));
  409. }
  410. Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));
  411. paren_stack.pop_back(); // Remove opening one anyway.
  412. return error;
  413. }
  414. GDScriptTokenizer::Token GDScriptTokenizerText::check_vcs_marker(char32_t p_test, Token::Type p_double_type) {
  415. const char32_t *next = _current + 1;
  416. int chars = 2; // Two already matched.
  417. // Test before consuming characters, since we don't want to consume more than needed.
  418. while (*next == p_test) {
  419. chars++;
  420. next++;
  421. }
  422. if (chars >= 7) {
  423. // It is a VCS conflict marker.
  424. while (chars > 1) {
  425. // Consume all characters (first was already consumed by scan()).
  426. _advance();
  427. chars--;
  428. }
  429. return make_token(Token::VCS_CONFLICT_MARKER);
  430. } else {
  431. // It is only a regular double character token, so we consume the second character.
  432. _advance();
  433. return make_token(p_double_type);
  434. }
  435. }
  436. GDScriptTokenizer::Token GDScriptTokenizerText::annotation() {
  437. if (is_unicode_identifier_start(_peek())) {
  438. _advance(); // Consume start character.
  439. } else {
  440. push_error("Expected annotation identifier after \"@\".");
  441. }
  442. while (is_unicode_identifier_continue(_peek())) {
  443. // Consume all identifier characters.
  444. _advance();
  445. }
  446. Token annotation = make_token(Token::ANNOTATION);
  447. annotation.literal = StringName(annotation.source);
  448. return annotation;
  449. }
  450. #define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
  451. KEYWORD_GROUP('a') \
  452. KEYWORD("as", Token::AS) \
  453. KEYWORD("and", Token::AND) \
  454. KEYWORD("assert", Token::ASSERT) \
  455. KEYWORD("await", Token::AWAIT) \
  456. KEYWORD_GROUP('b') \
  457. KEYWORD("break", Token::BREAK) \
  458. KEYWORD("breakpoint", Token::BREAKPOINT) \
  459. KEYWORD_GROUP('c') \
  460. KEYWORD("class", Token::CLASS) \
  461. KEYWORD("class_name", Token::CLASS_NAME) \
  462. KEYWORD("const", Token::TK_CONST) \
  463. KEYWORD("continue", Token::CONTINUE) \
  464. KEYWORD_GROUP('e') \
  465. KEYWORD("elif", Token::ELIF) \
  466. KEYWORD("else", Token::ELSE) \
  467. KEYWORD("enum", Token::ENUM) \
  468. KEYWORD("extends", Token::EXTENDS) \
  469. KEYWORD_GROUP('f') \
  470. KEYWORD("for", Token::FOR) \
  471. KEYWORD("func", Token::FUNC) \
  472. KEYWORD_GROUP('i') \
  473. KEYWORD("if", Token::IF) \
  474. KEYWORD("in", Token::TK_IN) \
  475. KEYWORD("is", Token::IS) \
  476. KEYWORD_GROUP('m') \
  477. KEYWORD("match", Token::MATCH) \
  478. KEYWORD_GROUP('n') \
  479. KEYWORD("namespace", Token::NAMESPACE) \
  480. KEYWORD("not", Token::NOT) \
  481. KEYWORD_GROUP('o') \
  482. KEYWORD("or", Token::OR) \
  483. KEYWORD_GROUP('p') \
  484. KEYWORD("pass", Token::PASS) \
  485. KEYWORD("preload", Token::PRELOAD) \
  486. KEYWORD_GROUP('r') \
  487. KEYWORD("return", Token::RETURN) \
  488. KEYWORD_GROUP('s') \
  489. KEYWORD("self", Token::SELF) \
  490. KEYWORD("signal", Token::SIGNAL) \
  491. KEYWORD("static", Token::STATIC) \
  492. KEYWORD("super", Token::SUPER) \
  493. KEYWORD_GROUP('t') \
  494. KEYWORD("trait", Token::TRAIT) \
  495. KEYWORD_GROUP('v') \
  496. KEYWORD("var", Token::VAR) \
  497. KEYWORD("void", Token::TK_VOID) \
  498. KEYWORD_GROUP('w') \
  499. KEYWORD("while", Token::WHILE) \
  500. KEYWORD("when", Token::WHEN) \
  501. KEYWORD_GROUP('y') \
  502. KEYWORD("yield", Token::YIELD) \
  503. KEYWORD_GROUP('I') \
  504. KEYWORD("INF", Token::CONST_INF) \
  505. KEYWORD_GROUP('N') \
  506. KEYWORD("NAN", Token::CONST_NAN) \
  507. KEYWORD_GROUP('P') \
  508. KEYWORD("PI", Token::CONST_PI) \
  509. KEYWORD_GROUP('T') \
  510. KEYWORD("TAU", Token::CONST_TAU)
  511. #define MIN_KEYWORD_LENGTH 2
  512. #define MAX_KEYWORD_LENGTH 10
  513. #ifdef DEBUG_ENABLED
  514. void GDScriptTokenizerText::make_keyword_list() {
  515. #define KEYWORD_LINE(keyword, token_type) keyword,
  516. #define KEYWORD_GROUP_IGNORE(group)
  517. keyword_list = {
  518. KEYWORDS(KEYWORD_GROUP_IGNORE, KEYWORD_LINE)
  519. };
  520. #undef KEYWORD_LINE
  521. #undef KEYWORD_GROUP_IGNORE
  522. }
  523. #endif // DEBUG_ENABLED
  524. GDScriptTokenizer::Token GDScriptTokenizerText::potential_identifier() {
  525. bool only_ascii = _peek(-1) < 128;
  526. // Consume all identifier characters.
  527. while (is_unicode_identifier_continue(_peek())) {
  528. char32_t c = _advance();
  529. only_ascii = only_ascii && c < 128;
  530. }
  531. int len = _current - _start;
  532. if (len == 1 && _peek(-1) == '_') {
  533. // Lone underscore.
  534. Token token = make_token(Token::UNDERSCORE);
  535. token.literal = "_";
  536. return token;
  537. }
  538. String name = String::utf32(Span(_start, len));
  539. if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) {
  540. // Cannot be a keyword, as the length doesn't match any.
  541. return make_identifier(name);
  542. }
  543. if (!only_ascii) {
  544. // Kept here in case the order with push_error matters.
  545. Token id = make_identifier(name);
  546. #ifdef DEBUG_ENABLED
  547. // Additional checks for identifiers but only in debug and if it's available in TextServer.
  548. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY)) {
  549. int64_t confusable = TS->is_confusable(name, keyword_list);
  550. if (confusable >= 0) {
  551. push_error(vformat(R"(Identifier "%s" is visually similar to the GDScript keyword "%s" and thus not allowed.)", name, keyword_list[confusable]));
  552. }
  553. }
  554. #endif // DEBUG_ENABLED
  555. // Cannot be a keyword, as keywords are ASCII only.
  556. return id;
  557. }
  558. // Define some helper macros for the switch case.
  559. #define KEYWORD_GROUP_CASE(char) \
  560. break; \
  561. case char:
  562. #define KEYWORD(keyword, token_type) \
  563. { \
  564. const int keyword_length = sizeof(keyword) - 1; \
  565. static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
  566. static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
  567. if (keyword_length == len && name == keyword) { \
  568. Token kw = make_token(token_type); \
  569. kw.literal = name; \
  570. return kw; \
  571. } \
  572. }
  573. // Find if it's a keyword.
  574. switch (_start[0]) {
  575. default:
  576. KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
  577. break;
  578. }
  579. // Check if it's a special literal
  580. if (len == 4) {
  581. if (name == "true") {
  582. return make_literal(true);
  583. } else if (name == "null") {
  584. return make_literal(Variant());
  585. }
  586. } else if (len == 5) {
  587. if (name == "false") {
  588. return make_literal(false);
  589. }
  590. }
  591. // Not a keyword, so must be an identifier.
  592. return make_identifier(name);
  593. #undef KEYWORD_GROUP_CASE
  594. #undef KEYWORD
  595. }
  596. #undef MAX_KEYWORD_LENGTH
  597. #undef MIN_KEYWORD_LENGTH
  598. #undef KEYWORDS
  599. void GDScriptTokenizerText::newline(bool p_make_token) {
  600. // Don't overwrite previous newline, nor create if we want a line continuation.
  601. if (p_make_token && !pending_newline && !line_continuation) {
  602. Token newline(Token::NEWLINE);
  603. newline.start_line = line;
  604. newline.end_line = line;
  605. newline.start_column = column - 1;
  606. newline.end_column = column;
  607. pending_newline = true;
  608. last_token = newline;
  609. last_newline = newline;
  610. }
  611. // Increment line/column counters.
  612. line++;
  613. column = 1;
  614. }
  615. GDScriptTokenizer::Token GDScriptTokenizerText::number() {
  616. int base = 10;
  617. bool has_decimal = false;
  618. bool has_exponent = false;
  619. bool has_error = false;
  620. bool need_digits = false;
  621. bool (*digit_check_func)(char32_t) = is_digit;
  622. // Sign before hexadecimal or binary.
  623. if ((_peek(-1) == '+' || _peek(-1) == '-') && _peek() == '0') {
  624. _advance();
  625. }
  626. if (_peek(-1) == '.') {
  627. has_decimal = true;
  628. } else if (_peek(-1) == '0') {
  629. if (_peek() == 'x' || _peek() == 'X') {
  630. // Hexadecimal.
  631. base = 16;
  632. digit_check_func = is_hex_digit;
  633. need_digits = true;
  634. _advance();
  635. } else if (_peek() == 'b' || _peek() == 'B') {
  636. // Binary.
  637. base = 2;
  638. digit_check_func = is_binary_digit;
  639. need_digits = true;
  640. _advance();
  641. }
  642. }
  643. if (base != 10 && is_underscore(_peek())) { // Disallow `0x_` and `0b_`.
  644. Token error = make_error(vformat(R"(Unexpected underscore after "0%c".)", _peek(-1)));
  645. error.start_column = column;
  646. error.end_column = column + 1;
  647. push_error(error);
  648. has_error = true;
  649. }
  650. bool previous_was_underscore = false; // Allow `_` to be used in a number, for readability.
  651. while (digit_check_func(_peek()) || is_underscore(_peek())) {
  652. if (is_underscore(_peek())) {
  653. if (previous_was_underscore) {
  654. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  655. error.start_column = column;
  656. error.end_column = column + 1;
  657. push_error(error);
  658. }
  659. previous_was_underscore = true;
  660. } else {
  661. need_digits = false;
  662. previous_was_underscore = false;
  663. }
  664. _advance();
  665. }
  666. // It might be a ".." token (instead of decimal point) so we check if it's not.
  667. if (_peek() == '.' && _peek(1) != '.') {
  668. if (base == 10 && !has_decimal) {
  669. has_decimal = true;
  670. } else if (base == 10) {
  671. Token error = make_error("Cannot use a decimal point twice in a number.");
  672. error.start_column = column;
  673. error.end_column = column + 1;
  674. push_error(error);
  675. has_error = true;
  676. } else if (base == 16) {
  677. Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
  678. error.start_column = column;
  679. error.end_column = column + 1;
  680. push_error(error);
  681. has_error = true;
  682. } else {
  683. Token error = make_error("Cannot use a decimal point in a binary number.");
  684. error.start_column = column;
  685. error.end_column = column + 1;
  686. push_error(error);
  687. has_error = true;
  688. }
  689. if (!has_error) {
  690. _advance();
  691. // Consume decimal digits.
  692. if (is_underscore(_peek())) { // Disallow `10._`, but allow `10.`.
  693. Token error = make_error(R"(Unexpected underscore after decimal point.)");
  694. error.start_column = column;
  695. error.end_column = column + 1;
  696. push_error(error);
  697. has_error = true;
  698. }
  699. previous_was_underscore = false;
  700. while (is_digit(_peek()) || is_underscore(_peek())) {
  701. if (is_underscore(_peek())) {
  702. if (previous_was_underscore) {
  703. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  704. error.start_column = column;
  705. error.end_column = column + 1;
  706. push_error(error);
  707. }
  708. previous_was_underscore = true;
  709. } else {
  710. previous_was_underscore = false;
  711. }
  712. _advance();
  713. }
  714. }
  715. }
  716. if (base == 10) {
  717. if (_peek() == 'e' || _peek() == 'E') {
  718. has_exponent = true;
  719. _advance();
  720. if (_peek() == '+' || _peek() == '-') {
  721. // Exponent sign.
  722. _advance();
  723. }
  724. // Consume exponent digits.
  725. if (!is_digit(_peek())) {
  726. Token error = make_error(R"(Expected exponent value after "e".)");
  727. error.start_column = column;
  728. error.end_column = column + 1;
  729. push_error(error);
  730. }
  731. previous_was_underscore = false;
  732. while (is_digit(_peek()) || is_underscore(_peek())) {
  733. if (is_underscore(_peek())) {
  734. if (previous_was_underscore) {
  735. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  736. error.start_column = column;
  737. error.end_column = column + 1;
  738. push_error(error);
  739. }
  740. previous_was_underscore = true;
  741. } else {
  742. previous_was_underscore = false;
  743. }
  744. _advance();
  745. }
  746. }
  747. }
  748. if (need_digits) {
  749. // No digits in hex or bin literal.
  750. Token error = make_error(vformat(R"(Expected %s digit after "0%c".)", (base == 16 ? "hexadecimal" : "binary"), (base == 16 ? 'x' : 'b')));
  751. error.start_column = column;
  752. error.end_column = column + 1;
  753. return error;
  754. }
  755. // Detect extra decimal point.
  756. if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
  757. Token error = make_error("Cannot use a decimal point twice in a number.");
  758. error.start_column = column;
  759. error.end_column = column + 1;
  760. push_error(error);
  761. has_error = true;
  762. } else if (is_unicode_identifier_start(_peek()) || is_unicode_identifier_continue(_peek())) {
  763. // Letter at the end of the number.
  764. push_error("Invalid numeric notation.");
  765. }
  766. // Create a string with the whole number.
  767. int len = _current - _start;
  768. String number = String::utf32(Span(_start, len)).remove_char('_');
  769. // Convert to the appropriate literal type.
  770. if (base == 16) {
  771. int64_t value = number.hex_to_int();
  772. return make_literal(value);
  773. } else if (base == 2) {
  774. int64_t value = number.bin_to_int();
  775. return make_literal(value);
  776. } else if (has_decimal || has_exponent) {
  777. double value = number.to_float();
  778. return make_literal(value);
  779. } else {
  780. int64_t value = number.to_int();
  781. return make_literal(value);
  782. }
  783. }
  784. GDScriptTokenizer::Token GDScriptTokenizerText::string() {
  785. enum StringType {
  786. STRING_REGULAR,
  787. STRING_NAME,
  788. STRING_NODEPATH,
  789. };
  790. bool is_raw = false;
  791. bool is_multiline = false;
  792. StringType type = STRING_REGULAR;
  793. if (_peek(-1) == 'r') {
  794. is_raw = true;
  795. _advance();
  796. } else if (_peek(-1) == '&') {
  797. type = STRING_NAME;
  798. _advance();
  799. } else if (_peek(-1) == '^') {
  800. type = STRING_NODEPATH;
  801. _advance();
  802. }
  803. char32_t quote_char = _peek(-1);
  804. if (_peek() == quote_char && _peek(1) == quote_char) {
  805. is_multiline = true;
  806. // Consume all quotes.
  807. _advance();
  808. _advance();
  809. }
  810. String result;
  811. char32_t prev = 0;
  812. int prev_pos = 0;
  813. for (;;) {
  814. // Consume actual string.
  815. if (_is_at_end()) {
  816. return make_error("Unterminated string.");
  817. }
  818. char32_t ch = _peek();
  819. if (ch == 0x200E || ch == 0x200F || (ch >= 0x202A && ch <= 0x202E) || (ch >= 0x2066 && ch <= 0x2069)) {
  820. Token error;
  821. if (is_raw) {
  822. error = make_error("Invisible text direction control character present in the string, use regular string literal instead of r-string.");
  823. } else {
  824. error = make_error("Invisible text direction control character present in the string, escape it (\"\\u" + String::num_int64(ch, 16) + "\") to avoid confusion.");
  825. }
  826. error.start_column = column;
  827. error.end_column = column + 1;
  828. push_error(error);
  829. }
  830. if (ch == '\\') {
  831. // Escape pattern.
  832. _advance();
  833. if (_is_at_end()) {
  834. return make_error("Unterminated string.");
  835. }
  836. if (is_raw) {
  837. if (_peek() == quote_char) {
  838. _advance();
  839. if (_is_at_end()) {
  840. return make_error("Unterminated string.");
  841. }
  842. result += '\\';
  843. result += quote_char;
  844. } else if (_peek() == '\\') { // For `\\\"`.
  845. _advance();
  846. if (_is_at_end()) {
  847. return make_error("Unterminated string.");
  848. }
  849. result += '\\';
  850. result += '\\';
  851. } else {
  852. result += '\\';
  853. }
  854. } else {
  855. // Grab escape character.
  856. char32_t code = _peek();
  857. _advance();
  858. if (_is_at_end()) {
  859. return make_error("Unterminated string.");
  860. }
  861. char32_t escaped = 0;
  862. bool valid_escape = true;
  863. switch (code) {
  864. case 'a':
  865. escaped = '\a';
  866. break;
  867. case 'b':
  868. escaped = '\b';
  869. break;
  870. case 'f':
  871. escaped = '\f';
  872. break;
  873. case 'n':
  874. escaped = '\n';
  875. break;
  876. case 'r':
  877. escaped = '\r';
  878. break;
  879. case 't':
  880. escaped = '\t';
  881. break;
  882. case 'v':
  883. escaped = '\v';
  884. break;
  885. case '\'':
  886. escaped = '\'';
  887. break;
  888. case '\"':
  889. escaped = '\"';
  890. break;
  891. case '\\':
  892. escaped = '\\';
  893. break;
  894. case 'U':
  895. case 'u': {
  896. // Hexadecimal sequence.
  897. int hex_len = (code == 'U') ? 6 : 4;
  898. for (int j = 0; j < hex_len; j++) {
  899. if (_is_at_end()) {
  900. return make_error("Unterminated string.");
  901. }
  902. char32_t digit = _peek();
  903. char32_t value = 0;
  904. if (is_digit(digit)) {
  905. value = digit - '0';
  906. } else if (digit >= 'a' && digit <= 'f') {
  907. value = digit - 'a';
  908. value += 10;
  909. } else if (digit >= 'A' && digit <= 'F') {
  910. value = digit - 'A';
  911. value += 10;
  912. } else {
  913. // Make error, but keep parsing the string.
  914. Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
  915. error.start_column = column;
  916. error.end_column = column + 1;
  917. push_error(error);
  918. valid_escape = false;
  919. break;
  920. }
  921. escaped <<= 4;
  922. escaped |= value;
  923. _advance();
  924. }
  925. } break;
  926. case '\r':
  927. if (_peek() != '\n') {
  928. // Carriage return without newline in string. (???)
  929. // Just add it to the string and keep going.
  930. result += ch;
  931. _advance();
  932. break;
  933. }
  934. [[fallthrough]];
  935. case '\n':
  936. // Escaping newline.
  937. newline(false);
  938. valid_escape = false; // Don't add to the string.
  939. break;
  940. default:
  941. Token error = make_error("Invalid escape in string.");
  942. error.start_column = column - 2;
  943. push_error(error);
  944. valid_escape = false;
  945. break;
  946. }
  947. // Parse UTF-16 pair.
  948. if (valid_escape) {
  949. if ((escaped & 0xfffffc00) == 0xd800) {
  950. if (prev == 0) {
  951. prev = escaped;
  952. prev_pos = column - 2;
  953. continue;
  954. } else {
  955. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");
  956. error.start_column = column - 2;
  957. push_error(error);
  958. valid_escape = false;
  959. prev = 0;
  960. }
  961. } else if ((escaped & 0xfffffc00) == 0xdc00) {
  962. if (prev == 0) {
  963. Token error = make_error("Invalid UTF-16 sequence in string, unpaired trail surrogate.");
  964. error.start_column = column - 2;
  965. push_error(error);
  966. valid_escape = false;
  967. } else {
  968. escaped = (prev << 10UL) + escaped - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  969. prev = 0;
  970. }
  971. }
  972. if (prev != 0) {
  973. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");
  974. error.start_column = prev_pos;
  975. push_error(error);
  976. prev = 0;
  977. }
  978. }
  979. if (valid_escape) {
  980. result += escaped;
  981. }
  982. }
  983. } else if (ch == quote_char) {
  984. if (prev != 0) {
  985. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  986. error.start_column = prev_pos;
  987. push_error(error);
  988. prev = 0;
  989. }
  990. _advance();
  991. if (is_multiline) {
  992. if (_peek() == quote_char && _peek(1) == quote_char) {
  993. // Ended the multiline string. Consume all quotes.
  994. _advance();
  995. _advance();
  996. break;
  997. } else {
  998. // Not a multiline string termination, add consumed quote.
  999. result += quote_char;
  1000. }
  1001. } else {
  1002. // Ended single-line string.
  1003. break;
  1004. }
  1005. } else {
  1006. if (prev != 0) {
  1007. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  1008. error.start_column = prev_pos;
  1009. push_error(error);
  1010. prev = 0;
  1011. }
  1012. result += ch;
  1013. _advance();
  1014. if (ch == '\n') {
  1015. newline(false);
  1016. }
  1017. }
  1018. }
  1019. if (prev != 0) {
  1020. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  1021. error.start_column = prev_pos;
  1022. push_error(error);
  1023. prev = 0;
  1024. }
  1025. // Make the literal.
  1026. Variant string;
  1027. switch (type) {
  1028. case STRING_NAME:
  1029. string = StringName(result);
  1030. break;
  1031. case STRING_NODEPATH:
  1032. string = NodePath(result);
  1033. break;
  1034. case STRING_REGULAR:
  1035. string = result;
  1036. break;
  1037. }
  1038. return make_literal(string);
  1039. }
  1040. void GDScriptTokenizerText::check_indent() {
  1041. ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
  1042. if (_is_at_end()) {
  1043. // Send dedents for every indent level.
  1044. pending_indents -= indent_level();
  1045. indent_stack.clear();
  1046. return;
  1047. }
  1048. for (;;) {
  1049. char32_t current_indent_char = _peek();
  1050. int indent_count = 0;
  1051. if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
  1052. // First character of the line is not whitespace, so we clear all indentation levels.
  1053. // Unless we are in a continuation or in multiline mode (inside expression).
  1054. if (line_continuation || multiline_mode) {
  1055. return;
  1056. }
  1057. pending_indents -= indent_level();
  1058. indent_stack.clear();
  1059. return;
  1060. }
  1061. if (_peek() == '\r') {
  1062. _advance();
  1063. if (_peek() != '\n') {
  1064. push_error("Stray carriage return character in source code.");
  1065. }
  1066. }
  1067. if (_peek() == '\n') {
  1068. // Empty line, keep going.
  1069. _advance();
  1070. newline(false);
  1071. continue;
  1072. }
  1073. // Check indent level.
  1074. bool mixed = false;
  1075. while (!_is_at_end()) {
  1076. char32_t space = _peek();
  1077. if (space == '\t') {
  1078. // Consider individual tab columns.
  1079. column += tab_size - 1;
  1080. indent_count += tab_size;
  1081. } else if (space == ' ') {
  1082. indent_count += 1;
  1083. } else {
  1084. break;
  1085. }
  1086. mixed = mixed || space != current_indent_char;
  1087. _advance();
  1088. }
  1089. if (_is_at_end()) {
  1090. // Reached the end with an empty line, so just dedent as much as needed.
  1091. pending_indents -= indent_level();
  1092. indent_stack.clear();
  1093. return;
  1094. }
  1095. if (_peek() == '\r') {
  1096. _advance();
  1097. if (_peek() != '\n') {
  1098. push_error("Stray carriage return character in source code.");
  1099. }
  1100. }
  1101. if (_peek() == '\n') {
  1102. // Empty line, keep going.
  1103. _advance();
  1104. newline(false);
  1105. continue;
  1106. }
  1107. if (_peek() == '#') {
  1108. // Comment. Advance to the next line.
  1109. #ifdef TOOLS_ENABLED
  1110. String comment;
  1111. while (_peek() != '\n' && !_is_at_end()) {
  1112. comment += _advance();
  1113. }
  1114. comments[line] = CommentData(comment, true);
  1115. #else
  1116. while (_peek() != '\n' && !_is_at_end()) {
  1117. _advance();
  1118. }
  1119. #endif // TOOLS_ENABLED
  1120. if (_is_at_end()) {
  1121. // Reached the end with an empty line, so just dedent as much as needed.
  1122. pending_indents -= indent_level();
  1123. indent_stack.clear();
  1124. return;
  1125. }
  1126. _advance(); // Consume '\n'.
  1127. newline(false);
  1128. continue;
  1129. }
  1130. if (mixed && !line_continuation && !multiline_mode) {
  1131. Token error = make_error("Mixed use of tabs and spaces for indentation.");
  1132. error.start_line = line;
  1133. error.start_column = 1;
  1134. push_error(error);
  1135. }
  1136. if (line_continuation || multiline_mode) {
  1137. // We cleared up all the whitespace at the beginning of the line.
  1138. // If this is a line continuation or we're in multiline mode then we don't want any indentation changes.
  1139. return;
  1140. }
  1141. // Check if indentation character is consistent.
  1142. if (indent_char == '\0') {
  1143. // First time indenting, choose character now.
  1144. indent_char = current_indent_char;
  1145. } else if (current_indent_char != indent_char) {
  1146. Token error = make_error(vformat("Used %s character for indentation instead of %s as used before in the file.",
  1147. _get_indent_char_name(current_indent_char), _get_indent_char_name(indent_char)));
  1148. error.start_line = line;
  1149. error.start_column = 1;
  1150. push_error(error);
  1151. }
  1152. // Now we can do actual indentation changes.
  1153. // Check if indent or dedent.
  1154. int previous_indent = 0;
  1155. if (indent_level() > 0) {
  1156. previous_indent = indent_stack.back()->get();
  1157. }
  1158. if (indent_count == previous_indent) {
  1159. // No change in indentation.
  1160. return;
  1161. }
  1162. if (indent_count > previous_indent) {
  1163. // Indentation increased.
  1164. indent_stack.push_back(indent_count);
  1165. pending_indents++;
  1166. } else {
  1167. // Indentation decreased (dedent).
  1168. if (indent_level() == 0) {
  1169. push_error("Tokenizer bug: trying to dedent without previous indent.");
  1170. return;
  1171. }
  1172. while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
  1173. indent_stack.pop_back();
  1174. pending_indents--;
  1175. }
  1176. if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
  1177. // Mismatched indentation alignment.
  1178. Token error = make_error("Unindent doesn't match the previous indentation level.");
  1179. error.start_line = line;
  1180. error.start_column = 1;
  1181. error.end_column = column + 1;
  1182. push_error(error);
  1183. // Still, we'll be lenient and keep going, so keep this level in the stack.
  1184. indent_stack.push_back(indent_count);
  1185. }
  1186. }
  1187. break; // Get out of the loop in any case.
  1188. }
  1189. }
  1190. String GDScriptTokenizerText::_get_indent_char_name(char32_t ch) {
  1191. ERR_FAIL_COND_V(ch != ' ' && ch != '\t', String::chr(ch).c_escape());
  1192. return ch == ' ' ? "space" : "tab";
  1193. }
  1194. void GDScriptTokenizerText::_skip_whitespace() {
  1195. if (pending_indents != 0) {
  1196. // Still have some indent/dedent tokens to give.
  1197. return;
  1198. }
  1199. bool is_bol = column == 1; // Beginning of line.
  1200. if (is_bol) {
  1201. check_indent();
  1202. return;
  1203. }
  1204. for (;;) {
  1205. char32_t c = _peek();
  1206. switch (c) {
  1207. case ' ':
  1208. _advance();
  1209. break;
  1210. case '\t':
  1211. _advance();
  1212. // Consider individual tab columns.
  1213. column += tab_size - 1;
  1214. break;
  1215. case '\r':
  1216. _advance(); // Consume either way.
  1217. if (_peek() != '\n') {
  1218. push_error("Stray carriage return character in source code.");
  1219. return;
  1220. }
  1221. break;
  1222. case '\n':
  1223. _advance();
  1224. newline(!is_bol); // Don't create new line token if line is empty.
  1225. check_indent();
  1226. break;
  1227. case '#': {
  1228. // Comment.
  1229. #ifdef TOOLS_ENABLED
  1230. String comment;
  1231. while (_peek() != '\n' && !_is_at_end()) {
  1232. comment += _advance();
  1233. }
  1234. comments[line] = CommentData(comment, is_bol);
  1235. #else
  1236. while (_peek() != '\n' && !_is_at_end()) {
  1237. _advance();
  1238. }
  1239. #endif // TOOLS_ENABLED
  1240. if (_is_at_end()) {
  1241. return;
  1242. }
  1243. _advance(); // Consume '\n'
  1244. newline(!is_bol);
  1245. check_indent();
  1246. } break;
  1247. default:
  1248. return;
  1249. }
  1250. }
  1251. }
  1252. GDScriptTokenizer::Token GDScriptTokenizerText::scan() {
  1253. if (has_error()) {
  1254. return pop_error();
  1255. }
  1256. _skip_whitespace();
  1257. if (pending_newline) {
  1258. pending_newline = false;
  1259. if (!multiline_mode) {
  1260. // Don't return newline tokens on multiline mode.
  1261. return last_newline;
  1262. }
  1263. }
  1264. // Check for potential errors after skipping whitespace().
  1265. if (has_error()) {
  1266. return pop_error();
  1267. }
  1268. _start = _current;
  1269. start_line = line;
  1270. start_column = column;
  1271. if (pending_indents != 0) {
  1272. // Adjust position for indent.
  1273. _start -= start_column - 1;
  1274. start_column = 1;
  1275. if (pending_indents > 0) {
  1276. // Indents.
  1277. pending_indents--;
  1278. return make_token(Token::INDENT);
  1279. } else {
  1280. // Dedents.
  1281. pending_indents++;
  1282. Token dedent = make_token(Token::DEDENT);
  1283. dedent.end_column += 1;
  1284. return dedent;
  1285. }
  1286. }
  1287. if (_is_at_end()) {
  1288. return make_token(Token::TK_EOF);
  1289. }
  1290. const char32_t c = _advance();
  1291. if (c == '\\') {
  1292. // Line continuation with backslash.
  1293. if (_peek() == '\r') {
  1294. if (_peek(1) != '\n') {
  1295. return make_error("Unexpected carriage return character.");
  1296. }
  1297. _advance();
  1298. }
  1299. if (_peek() != '\n') {
  1300. return make_error("Expected new line after \"\\\".");
  1301. }
  1302. _advance();
  1303. newline(false);
  1304. line_continuation = true;
  1305. _skip_whitespace(); // Skip whitespace/comment lines after `\`. See GH-89403.
  1306. continuation_lines.push_back(line);
  1307. return scan(); // Recurse to get next token.
  1308. }
  1309. line_continuation = false;
  1310. if (is_digit(c)) {
  1311. return number();
  1312. } else if (c == 'r' && (_peek() == '"' || _peek() == '\'')) {
  1313. // Raw string literals.
  1314. return string();
  1315. } else if (is_unicode_identifier_start(c)) {
  1316. return potential_identifier();
  1317. }
  1318. switch (c) {
  1319. // String literals.
  1320. case '"':
  1321. case '\'':
  1322. return string();
  1323. // Annotation.
  1324. case '@':
  1325. return annotation();
  1326. // Single characters.
  1327. case '~':
  1328. return make_token(Token::TILDE);
  1329. case ',':
  1330. return make_token(Token::COMMA);
  1331. case ':':
  1332. return make_token(Token::COLON);
  1333. case ';':
  1334. return make_token(Token::SEMICOLON);
  1335. case '$':
  1336. return make_token(Token::DOLLAR);
  1337. case '?':
  1338. return make_token(Token::QUESTION_MARK);
  1339. case '`':
  1340. return make_token(Token::BACKTICK);
  1341. // Parens.
  1342. case '(':
  1343. push_paren('(');
  1344. return make_token(Token::PARENTHESIS_OPEN);
  1345. case '[':
  1346. push_paren('[');
  1347. return make_token(Token::BRACKET_OPEN);
  1348. case '{':
  1349. push_paren('{');
  1350. return make_token(Token::BRACE_OPEN);
  1351. case ')':
  1352. if (!pop_paren('(')) {
  1353. return make_paren_error(c);
  1354. }
  1355. return make_token(Token::PARENTHESIS_CLOSE);
  1356. case ']':
  1357. if (!pop_paren('[')) {
  1358. return make_paren_error(c);
  1359. }
  1360. return make_token(Token::BRACKET_CLOSE);
  1361. case '}':
  1362. if (!pop_paren('{')) {
  1363. return make_paren_error(c);
  1364. }
  1365. return make_token(Token::BRACE_CLOSE);
  1366. // Double characters.
  1367. case '!':
  1368. if (_peek() == '=') {
  1369. _advance();
  1370. return make_token(Token::BANG_EQUAL);
  1371. } else {
  1372. return make_token(Token::BANG);
  1373. }
  1374. case '.':
  1375. if (_peek() == '.') {
  1376. _advance();
  1377. if (_peek() == '.') {
  1378. _advance();
  1379. return make_token(Token::PERIOD_PERIOD_PERIOD);
  1380. }
  1381. return make_token(Token::PERIOD_PERIOD);
  1382. } else if (is_digit(_peek())) {
  1383. // Number starting with '.'.
  1384. return number();
  1385. } else {
  1386. return make_token(Token::PERIOD);
  1387. }
  1388. case '+':
  1389. if (_peek() == '=') {
  1390. _advance();
  1391. return make_token(Token::PLUS_EQUAL);
  1392. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1393. // Number starting with '+'.
  1394. return number();
  1395. } else {
  1396. return make_token(Token::PLUS);
  1397. }
  1398. case '-':
  1399. if (_peek() == '=') {
  1400. _advance();
  1401. return make_token(Token::MINUS_EQUAL);
  1402. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1403. // Number starting with '-'.
  1404. return number();
  1405. } else if (_peek() == '>') {
  1406. _advance();
  1407. return make_token(Token::FORWARD_ARROW);
  1408. } else {
  1409. return make_token(Token::MINUS);
  1410. }
  1411. case '*':
  1412. if (_peek() == '=') {
  1413. _advance();
  1414. return make_token(Token::STAR_EQUAL);
  1415. } else if (_peek() == '*') {
  1416. if (_peek(1) == '=') {
  1417. _advance();
  1418. _advance(); // Advance both '*' and '='
  1419. return make_token(Token::STAR_STAR_EQUAL);
  1420. }
  1421. _advance();
  1422. return make_token(Token::STAR_STAR);
  1423. } else {
  1424. return make_token(Token::STAR);
  1425. }
  1426. case '/':
  1427. if (_peek() == '=') {
  1428. _advance();
  1429. return make_token(Token::SLASH_EQUAL);
  1430. } else {
  1431. return make_token(Token::SLASH);
  1432. }
  1433. case '%':
  1434. if (_peek() == '=') {
  1435. _advance();
  1436. return make_token(Token::PERCENT_EQUAL);
  1437. } else {
  1438. return make_token(Token::PERCENT);
  1439. }
  1440. case '^':
  1441. if (_peek() == '=') {
  1442. _advance();
  1443. return make_token(Token::CARET_EQUAL);
  1444. } else if (_peek() == '"' || _peek() == '\'') {
  1445. // Node path
  1446. return string();
  1447. } else {
  1448. return make_token(Token::CARET);
  1449. }
  1450. case '&':
  1451. if (_peek() == '&') {
  1452. _advance();
  1453. return make_token(Token::AMPERSAND_AMPERSAND);
  1454. } else if (_peek() == '=') {
  1455. _advance();
  1456. return make_token(Token::AMPERSAND_EQUAL);
  1457. } else if (_peek() == '"' || _peek() == '\'') {
  1458. // String Name
  1459. return string();
  1460. } else {
  1461. return make_token(Token::AMPERSAND);
  1462. }
  1463. case '|':
  1464. if (_peek() == '|') {
  1465. _advance();
  1466. return make_token(Token::PIPE_PIPE);
  1467. } else if (_peek() == '=') {
  1468. _advance();
  1469. return make_token(Token::PIPE_EQUAL);
  1470. } else {
  1471. return make_token(Token::PIPE);
  1472. }
  1473. // Potential VCS conflict markers.
  1474. case '=':
  1475. if (_peek() == '=') {
  1476. return check_vcs_marker('=', Token::EQUAL_EQUAL);
  1477. } else {
  1478. return make_token(Token::EQUAL);
  1479. }
  1480. case '<':
  1481. if (_peek() == '=') {
  1482. _advance();
  1483. return make_token(Token::LESS_EQUAL);
  1484. } else if (_peek() == '<') {
  1485. if (_peek(1) == '=') {
  1486. _advance();
  1487. _advance(); // Advance both '<' and '='
  1488. return make_token(Token::LESS_LESS_EQUAL);
  1489. } else {
  1490. return check_vcs_marker('<', Token::LESS_LESS);
  1491. }
  1492. } else {
  1493. return make_token(Token::LESS);
  1494. }
  1495. case '>':
  1496. if (_peek() == '=') {
  1497. _advance();
  1498. return make_token(Token::GREATER_EQUAL);
  1499. } else if (_peek() == '>') {
  1500. if (_peek(1) == '=') {
  1501. _advance();
  1502. _advance(); // Advance both '>' and '='
  1503. return make_token(Token::GREATER_GREATER_EQUAL);
  1504. } else {
  1505. return check_vcs_marker('>', Token::GREATER_GREATER);
  1506. }
  1507. } else {
  1508. return make_token(Token::GREATER);
  1509. }
  1510. default:
  1511. if (is_whitespace(c)) {
  1512. return make_error(vformat(R"(Invalid white space character U+%04X.)", static_cast<int32_t>(c)));
  1513. } else {
  1514. return make_error(vformat(R"(Invalid character "%c" (U+%04X).)", c, static_cast<int32_t>(c)));
  1515. }
  1516. }
  1517. }
  1518. GDScriptTokenizerText::GDScriptTokenizerText() {
  1519. #ifdef TOOLS_ENABLED
  1520. if (EditorSettings::get_singleton()) {
  1521. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  1522. }
  1523. #endif // TOOLS_ENABLED
  1524. #ifdef DEBUG_ENABLED
  1525. make_keyword_list();
  1526. #endif // DEBUG_ENABLED
  1527. }