gdscript_tokenizer.cpp 43 KB

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