gdscript_tokenizer.cpp 44 KB

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