gdscript_tokenizer.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. if (!only_ascii) {
  537. // Kept here in case the order with push_error matters.
  538. Token id = make_identifier(name);
  539. #ifdef DEBUG_ENABLED
  540. // Additional checks for identifiers but only in debug and if it's available in TextServer.
  541. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY)) {
  542. int64_t confusable = TS->is_confusable(name, keyword_list);
  543. if (confusable >= 0) {
  544. push_error(vformat(R"(Identifier "%s" is visually similar to the GDScript keyword "%s" and thus not allowed.)", name, keyword_list[confusable]));
  545. }
  546. }
  547. #endif // DEBUG_ENABLED
  548. // Cannot be a keyword, as keywords are ASCII only.
  549. return id;
  550. }
  551. // Define some helper macros for the switch case.
  552. #define KEYWORD_GROUP_CASE(char) \
  553. break; \
  554. case char:
  555. #define KEYWORD(keyword, token_type) \
  556. { \
  557. const int keyword_length = sizeof(keyword) - 1; \
  558. static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
  559. static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
  560. if (keyword_length == len && name == keyword) { \
  561. return make_token(token_type); \
  562. } \
  563. }
  564. // Find if it's a keyword.
  565. switch (_start[0]) {
  566. default:
  567. KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
  568. break;
  569. }
  570. // Check if it's a special literal
  571. if (len == 4) {
  572. if (name == "true") {
  573. return make_literal(true);
  574. } else if (name == "null") {
  575. return make_literal(Variant());
  576. }
  577. } else if (len == 5) {
  578. if (name == "false") {
  579. return make_literal(false);
  580. }
  581. }
  582. // Not a keyword, so must be an identifier.
  583. return make_identifier(name);
  584. #undef KEYWORD_GROUP_CASE
  585. #undef KEYWORD
  586. }
  587. #undef MAX_KEYWORD_LENGTH
  588. #undef MIN_KEYWORD_LENGTH
  589. #undef KEYWORDS
  590. void GDScriptTokenizer::newline(bool p_make_token) {
  591. // Don't overwrite previous newline, nor create if we want a line continuation.
  592. if (p_make_token && !pending_newline && !line_continuation) {
  593. Token newline(Token::NEWLINE);
  594. newline.start_line = line;
  595. newline.end_line = line;
  596. newline.start_column = column - 1;
  597. newline.end_column = column;
  598. newline.leftmost_column = newline.start_column;
  599. newline.rightmost_column = newline.end_column;
  600. pending_newline = true;
  601. last_token = newline;
  602. last_newline = newline;
  603. }
  604. // Increment line/column counters.
  605. line++;
  606. column = 1;
  607. leftmost_column = 1;
  608. }
  609. GDScriptTokenizer::Token GDScriptTokenizer::number() {
  610. int base = 10;
  611. bool has_decimal = false;
  612. bool has_exponent = false;
  613. bool has_error = false;
  614. bool (*digit_check_func)(char32_t) = is_digit;
  615. // Sign before hexadecimal or binary.
  616. if ((_peek(-1) == '+' || _peek(-1) == '-') && _peek() == '0') {
  617. _advance();
  618. }
  619. if (_peek(-1) == '.') {
  620. has_decimal = true;
  621. } else if (_peek(-1) == '0') {
  622. if (_peek() == 'x') {
  623. // Hexadecimal.
  624. base = 16;
  625. digit_check_func = is_hex_digit;
  626. _advance();
  627. } else if (_peek() == 'b') {
  628. // Binary.
  629. base = 2;
  630. digit_check_func = is_binary_digit;
  631. _advance();
  632. }
  633. }
  634. if (base != 10 && is_underscore(_peek())) { // Disallow `0x_` and `0b_`.
  635. Token error = make_error(vformat(R"(Unexpected underscore after "0%c".)", _peek(-1)));
  636. error.start_column = column;
  637. error.leftmost_column = column;
  638. error.end_column = column + 1;
  639. error.rightmost_column = column + 1;
  640. push_error(error);
  641. has_error = true;
  642. }
  643. bool previous_was_underscore = false; // Allow `_` to be used in a number, for readability.
  644. while (digit_check_func(_peek()) || is_underscore(_peek())) {
  645. if (is_underscore(_peek())) {
  646. if (previous_was_underscore) {
  647. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  648. error.start_column = column;
  649. error.leftmost_column = column;
  650. error.end_column = column + 1;
  651. error.rightmost_column = column + 1;
  652. push_error(error);
  653. }
  654. previous_was_underscore = true;
  655. } else {
  656. previous_was_underscore = false;
  657. }
  658. _advance();
  659. }
  660. // It might be a ".." token (instead of decimal point) so we check if it's not.
  661. if (_peek() == '.' && _peek(1) != '.') {
  662. if (base == 10 && !has_decimal) {
  663. has_decimal = true;
  664. } else if (base == 10) {
  665. Token error = make_error("Cannot use a decimal point twice in a number.");
  666. error.start_column = column;
  667. error.leftmost_column = column;
  668. error.end_column = column + 1;
  669. error.rightmost_column = column + 1;
  670. push_error(error);
  671. has_error = true;
  672. } else if (base == 16) {
  673. Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
  674. error.start_column = column;
  675. error.leftmost_column = column;
  676. error.end_column = column + 1;
  677. error.rightmost_column = column + 1;
  678. push_error(error);
  679. has_error = true;
  680. } else {
  681. Token error = make_error("Cannot use a decimal point in a binary number.");
  682. error.start_column = column;
  683. error.leftmost_column = column;
  684. error.end_column = column + 1;
  685. error.rightmost_column = column + 1;
  686. push_error(error);
  687. has_error = true;
  688. }
  689. if (!has_error) {
  690. _advance();
  691. // Consume decimal digits.
  692. if (is_underscore(_peek())) { // Disallow `10._`, but allow `10.`.
  693. Token error = make_error(R"(Unexpected underscore after decimal point.)");
  694. error.start_column = column;
  695. error.leftmost_column = column;
  696. error.end_column = column + 1;
  697. error.rightmost_column = column + 1;
  698. push_error(error);
  699. has_error = true;
  700. }
  701. previous_was_underscore = false;
  702. while (is_digit(_peek()) || is_underscore(_peek())) {
  703. if (is_underscore(_peek())) {
  704. if (previous_was_underscore) {
  705. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  706. error.start_column = column;
  707. error.leftmost_column = column;
  708. error.end_column = column + 1;
  709. error.rightmost_column = column + 1;
  710. push_error(error);
  711. }
  712. previous_was_underscore = true;
  713. } else {
  714. previous_was_underscore = false;
  715. }
  716. _advance();
  717. }
  718. }
  719. }
  720. if (base == 10) {
  721. if (_peek() == 'e' || _peek() == 'E') {
  722. has_exponent = true;
  723. _advance();
  724. if (_peek() == '+' || _peek() == '-') {
  725. // Exponent sign.
  726. _advance();
  727. }
  728. // Consume exponent digits.
  729. if (!is_digit(_peek())) {
  730. Token error = make_error(R"(Expected exponent value after "e".)");
  731. error.start_column = column;
  732. error.leftmost_column = column;
  733. error.end_column = column + 1;
  734. error.rightmost_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.leftmost_column = column;
  744. error.end_column = column + 1;
  745. error.rightmost_column = column + 1;
  746. push_error(error);
  747. }
  748. previous_was_underscore = true;
  749. } else {
  750. previous_was_underscore = false;
  751. }
  752. _advance();
  753. }
  754. }
  755. }
  756. // Detect extra decimal point.
  757. if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
  758. Token error = make_error("Cannot use a decimal point twice in a number.");
  759. error.start_column = column;
  760. error.leftmost_column = column;
  761. error.end_column = column + 1;
  762. error.rightmost_column = column + 1;
  763. push_error(error);
  764. has_error = true;
  765. } else if (is_unicode_identifier_start(_peek()) || is_unicode_identifier_continue(_peek())) {
  766. // Letter at the end of the number.
  767. push_error("Invalid numeric notation.");
  768. }
  769. // Create a string with the whole number.
  770. int len = _current - _start;
  771. String number = String(_start, len).replace("_", "");
  772. // Convert to the appropriate literal type.
  773. if (base == 16) {
  774. int64_t value = number.hex_to_int();
  775. return make_literal(value);
  776. } else if (base == 2) {
  777. int64_t value = number.bin_to_int();
  778. return make_literal(value);
  779. } else if (has_decimal || has_exponent) {
  780. double value = number.to_float();
  781. return make_literal(value);
  782. } else {
  783. int64_t value = number.to_int();
  784. return make_literal(value);
  785. }
  786. }
  787. GDScriptTokenizer::Token GDScriptTokenizer::string() {
  788. enum StringType {
  789. STRING_REGULAR,
  790. STRING_NAME,
  791. STRING_NODEPATH,
  792. };
  793. bool is_multiline = false;
  794. StringType type = STRING_REGULAR;
  795. if (_peek(-1) == '&') {
  796. type = STRING_NAME;
  797. _advance();
  798. } else if (_peek(-1) == '^') {
  799. type = STRING_NODEPATH;
  800. _advance();
  801. }
  802. char32_t quote_char = _peek(-1);
  803. if (_peek() == quote_char && _peek(1) == quote_char) {
  804. is_multiline = true;
  805. // Consume all quotes.
  806. _advance();
  807. _advance();
  808. }
  809. String result;
  810. char32_t prev = 0;
  811. int prev_pos = 0;
  812. for (;;) {
  813. // Consume actual string.
  814. if (_is_at_end()) {
  815. return make_error("Unterminated string.");
  816. }
  817. char32_t ch = _peek();
  818. if (ch == 0x200E || ch == 0x200F || (ch >= 0x202A && ch <= 0x202E) || (ch >= 0x2066 && ch <= 0x2069)) {
  819. Token error = make_error("Invisible text direction control character present in the string, escape it (\"\\u" + String::num_int64(ch, 16) + "\") to avoid confusion.");
  820. error.start_column = column;
  821. error.leftmost_column = error.start_column;
  822. error.end_column = column + 1;
  823. error.rightmost_column = error.end_column;
  824. push_error(error);
  825. }
  826. if (ch == '\\') {
  827. // Escape pattern.
  828. _advance();
  829. if (_is_at_end()) {
  830. return make_error("Unterminated string.");
  831. }
  832. // Grab escape character.
  833. char32_t code = _peek();
  834. _advance();
  835. if (_is_at_end()) {
  836. return make_error("Unterminated string.");
  837. }
  838. char32_t escaped = 0;
  839. bool valid_escape = true;
  840. switch (code) {
  841. case 'a':
  842. escaped = '\a';
  843. break;
  844. case 'b':
  845. escaped = '\b';
  846. break;
  847. case 'f':
  848. escaped = '\f';
  849. break;
  850. case 'n':
  851. escaped = '\n';
  852. break;
  853. case 'r':
  854. escaped = '\r';
  855. break;
  856. case 't':
  857. escaped = '\t';
  858. break;
  859. case 'v':
  860. escaped = '\v';
  861. break;
  862. case '\'':
  863. escaped = '\'';
  864. break;
  865. case '\"':
  866. escaped = '\"';
  867. break;
  868. case '\\':
  869. escaped = '\\';
  870. break;
  871. case 'U':
  872. case 'u': {
  873. // Hexadecimal sequence.
  874. int hex_len = (code == 'U') ? 6 : 4;
  875. for (int j = 0; j < hex_len; j++) {
  876. if (_is_at_end()) {
  877. return make_error("Unterminated string.");
  878. }
  879. char32_t digit = _peek();
  880. char32_t value = 0;
  881. if (is_digit(digit)) {
  882. value = digit - '0';
  883. } else if (digit >= 'a' && digit <= 'f') {
  884. value = digit - 'a';
  885. value += 10;
  886. } else if (digit >= 'A' && digit <= 'F') {
  887. value = digit - 'A';
  888. value += 10;
  889. } else {
  890. // Make error, but keep parsing the string.
  891. Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
  892. error.start_column = column;
  893. error.leftmost_column = error.start_column;
  894. error.end_column = column + 1;
  895. error.rightmost_column = error.end_column;
  896. push_error(error);
  897. valid_escape = false;
  898. break;
  899. }
  900. escaped <<= 4;
  901. escaped |= value;
  902. _advance();
  903. }
  904. } break;
  905. case '\r':
  906. if (_peek() != '\n') {
  907. // Carriage return without newline in string. (???)
  908. // Just add it to the string and keep going.
  909. result += ch;
  910. _advance();
  911. break;
  912. }
  913. [[fallthrough]];
  914. case '\n':
  915. // Escaping newline.
  916. newline(false);
  917. valid_escape = false; // Don't add to the string.
  918. break;
  919. default:
  920. Token error = make_error("Invalid escape in string.");
  921. error.start_column = column - 2;
  922. error.leftmost_column = error.start_column;
  923. push_error(error);
  924. valid_escape = false;
  925. break;
  926. }
  927. // Parse UTF-16 pair.
  928. if (valid_escape) {
  929. if ((escaped & 0xfffffc00) == 0xd800) {
  930. if (prev == 0) {
  931. prev = escaped;
  932. prev_pos = column - 2;
  933. continue;
  934. } else {
  935. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  936. error.start_column = column - 2;
  937. error.leftmost_column = error.start_column;
  938. push_error(error);
  939. valid_escape = false;
  940. prev = 0;
  941. }
  942. } else if ((escaped & 0xfffffc00) == 0xdc00) {
  943. if (prev == 0) {
  944. Token error = make_error("Invalid UTF-16 sequence in string, unpaired trail surrogate");
  945. error.start_column = column - 2;
  946. error.leftmost_column = error.start_column;
  947. push_error(error);
  948. valid_escape = false;
  949. } else {
  950. escaped = (prev << 10UL) + escaped - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  951. prev = 0;
  952. }
  953. }
  954. if (prev != 0) {
  955. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  956. error.start_column = prev_pos;
  957. error.leftmost_column = error.start_column;
  958. push_error(error);
  959. prev = 0;
  960. }
  961. }
  962. if (valid_escape) {
  963. result += escaped;
  964. }
  965. } else if (ch == quote_char) {
  966. if (prev != 0) {
  967. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  968. error.start_column = prev_pos;
  969. error.leftmost_column = error.start_column;
  970. push_error(error);
  971. prev = 0;
  972. }
  973. _advance();
  974. if (is_multiline) {
  975. if (_peek() == quote_char && _peek(1) == quote_char) {
  976. // Ended the multiline string. Consume all quotes.
  977. _advance();
  978. _advance();
  979. break;
  980. } else {
  981. // Not a multiline string termination, add consumed quote.
  982. result += quote_char;
  983. }
  984. } else {
  985. // Ended single-line string.
  986. break;
  987. }
  988. } else {
  989. if (prev != 0) {
  990. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  991. error.start_column = prev_pos;
  992. error.leftmost_column = error.start_column;
  993. push_error(error);
  994. prev = 0;
  995. }
  996. result += ch;
  997. _advance();
  998. if (ch == '\n') {
  999. newline(false);
  1000. }
  1001. }
  1002. }
  1003. if (prev != 0) {
  1004. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  1005. error.start_column = prev_pos;
  1006. error.leftmost_column = error.start_column;
  1007. push_error(error);
  1008. prev = 0;
  1009. }
  1010. // Make the literal.
  1011. Variant string;
  1012. switch (type) {
  1013. case STRING_NAME:
  1014. string = StringName(result);
  1015. break;
  1016. case STRING_NODEPATH:
  1017. string = NodePath(result);
  1018. break;
  1019. case STRING_REGULAR:
  1020. string = result;
  1021. break;
  1022. }
  1023. return make_literal(string);
  1024. }
  1025. void GDScriptTokenizer::check_indent() {
  1026. ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
  1027. if (_is_at_end()) {
  1028. // Send dedents for every indent level.
  1029. pending_indents -= indent_level();
  1030. indent_stack.clear();
  1031. return;
  1032. }
  1033. for (;;) {
  1034. char32_t current_indent_char = _peek();
  1035. int indent_count = 0;
  1036. if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
  1037. // First character of the line is not whitespace, so we clear all indentation levels.
  1038. // Unless we are in a continuation or in multiline mode (inside expression).
  1039. if (line_continuation || multiline_mode) {
  1040. return;
  1041. }
  1042. pending_indents -= indent_level();
  1043. indent_stack.clear();
  1044. return;
  1045. }
  1046. if (_peek() == '\r') {
  1047. _advance();
  1048. if (_peek() != '\n') {
  1049. push_error("Stray carriage return character in source code.");
  1050. }
  1051. }
  1052. if (_peek() == '\n') {
  1053. // Empty line, keep going.
  1054. _advance();
  1055. newline(false);
  1056. continue;
  1057. }
  1058. // Check indent level.
  1059. bool mixed = false;
  1060. while (!_is_at_end()) {
  1061. char32_t space = _peek();
  1062. if (space == '\t') {
  1063. // Consider individual tab columns.
  1064. column += tab_size - 1;
  1065. indent_count += tab_size;
  1066. } else if (space == ' ') {
  1067. indent_count += 1;
  1068. } else {
  1069. break;
  1070. }
  1071. mixed = mixed || space != current_indent_char;
  1072. _advance();
  1073. }
  1074. if (_is_at_end()) {
  1075. // Reached the end with an empty line, so just dedent as much as needed.
  1076. pending_indents -= indent_level();
  1077. indent_stack.clear();
  1078. return;
  1079. }
  1080. if (_peek() == '\r') {
  1081. _advance();
  1082. if (_peek() != '\n') {
  1083. push_error("Stray carriage return character in source code.");
  1084. }
  1085. }
  1086. if (_peek() == '\n') {
  1087. // Empty line, keep going.
  1088. _advance();
  1089. newline(false);
  1090. continue;
  1091. }
  1092. if (_peek() == '#') {
  1093. // Comment. Advance to the next line.
  1094. #ifdef TOOLS_ENABLED
  1095. String comment;
  1096. while (_peek() != '\n' && !_is_at_end()) {
  1097. comment += _advance();
  1098. }
  1099. comments[line] = CommentData(comment, true);
  1100. #else
  1101. while (_peek() != '\n' && !_is_at_end()) {
  1102. _advance();
  1103. }
  1104. #endif // TOOLS_ENABLED
  1105. if (_is_at_end()) {
  1106. // Reached the end with an empty line, so just dedent as much as needed.
  1107. pending_indents -= indent_level();
  1108. indent_stack.clear();
  1109. return;
  1110. }
  1111. _advance(); // Consume '\n'.
  1112. newline(false);
  1113. continue;
  1114. }
  1115. if (mixed && !line_continuation && !multiline_mode) {
  1116. Token error = make_error("Mixed use of tabs and spaces for indentation.");
  1117. error.start_line = line;
  1118. error.start_column = 1;
  1119. error.leftmost_column = 1;
  1120. error.rightmost_column = column;
  1121. push_error(error);
  1122. }
  1123. if (line_continuation || multiline_mode) {
  1124. // We cleared up all the whitespace at the beginning of the line.
  1125. // If this is a line continuation or we're in multiline mode then we don't want any indentation changes.
  1126. return;
  1127. }
  1128. // Check if indentation character is consistent.
  1129. if (indent_char == '\0') {
  1130. // First time indenting, choose character now.
  1131. indent_char = current_indent_char;
  1132. } else if (current_indent_char != indent_char) {
  1133. Token error = make_error(vformat("Used %s character for indentation instead of %s as used before in the file.",
  1134. _get_indent_char_name(current_indent_char), _get_indent_char_name(indent_char)));
  1135. error.start_line = line;
  1136. error.start_column = 1;
  1137. error.leftmost_column = 1;
  1138. error.rightmost_column = column;
  1139. push_error(error);
  1140. }
  1141. // Now we can do actual indentation changes.
  1142. // Check if indent or dedent.
  1143. int previous_indent = 0;
  1144. if (indent_level() > 0) {
  1145. previous_indent = indent_stack.back()->get();
  1146. }
  1147. if (indent_count == previous_indent) {
  1148. // No change in indentation.
  1149. return;
  1150. }
  1151. if (indent_count > previous_indent) {
  1152. // Indentation increased.
  1153. indent_stack.push_back(indent_count);
  1154. pending_indents++;
  1155. } else {
  1156. // Indentation decreased (dedent).
  1157. if (indent_level() == 0) {
  1158. push_error("Tokenizer bug: trying to dedent without previous indent.");
  1159. return;
  1160. }
  1161. while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
  1162. indent_stack.pop_back();
  1163. pending_indents--;
  1164. }
  1165. if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
  1166. // Mismatched indentation alignment.
  1167. Token error = make_error("Unindent doesn't match the previous indentation level.");
  1168. error.start_line = line;
  1169. error.start_column = 1;
  1170. error.leftmost_column = 1;
  1171. error.end_column = column + 1;
  1172. error.rightmost_column = column + 1;
  1173. push_error(error);
  1174. // Still, we'll be lenient and keep going, so keep this level in the stack.
  1175. indent_stack.push_back(indent_count);
  1176. }
  1177. }
  1178. break; // Get out of the loop in any case.
  1179. }
  1180. }
  1181. String GDScriptTokenizer::_get_indent_char_name(char32_t ch) {
  1182. ERR_FAIL_COND_V(ch != ' ' && ch != '\t', String(&ch, 1).c_escape());
  1183. return ch == ' ' ? "space" : "tab";
  1184. }
  1185. void GDScriptTokenizer::_skip_whitespace() {
  1186. if (pending_indents != 0) {
  1187. // Still have some indent/dedent tokens to give.
  1188. return;
  1189. }
  1190. bool is_bol = column == 1; // Beginning of line.
  1191. if (is_bol) {
  1192. check_indent();
  1193. return;
  1194. }
  1195. for (;;) {
  1196. char32_t c = _peek();
  1197. switch (c) {
  1198. case ' ':
  1199. _advance();
  1200. break;
  1201. case '\t':
  1202. _advance();
  1203. // Consider individual tab columns.
  1204. column += tab_size - 1;
  1205. break;
  1206. case '\r':
  1207. _advance(); // Consume either way.
  1208. if (_peek() != '\n') {
  1209. push_error("Stray carriage return character in source code.");
  1210. return;
  1211. }
  1212. break;
  1213. case '\n':
  1214. _advance();
  1215. newline(!is_bol); // Don't create new line token if line is empty.
  1216. check_indent();
  1217. break;
  1218. case '#': {
  1219. // Comment.
  1220. #ifdef TOOLS_ENABLED
  1221. String comment;
  1222. while (_peek() != '\n' && !_is_at_end()) {
  1223. comment += _advance();
  1224. }
  1225. comments[line] = CommentData(comment, is_bol);
  1226. #else
  1227. while (_peek() != '\n' && !_is_at_end()) {
  1228. _advance();
  1229. }
  1230. #endif // TOOLS_ENABLED
  1231. if (_is_at_end()) {
  1232. return;
  1233. }
  1234. _advance(); // Consume '\n'
  1235. newline(!is_bol);
  1236. check_indent();
  1237. } break;
  1238. default:
  1239. return;
  1240. }
  1241. }
  1242. }
  1243. GDScriptTokenizer::Token GDScriptTokenizer::scan() {
  1244. if (has_error()) {
  1245. return pop_error();
  1246. }
  1247. _skip_whitespace();
  1248. if (pending_newline) {
  1249. pending_newline = false;
  1250. if (!multiline_mode) {
  1251. // Don't return newline tokens on multiline mode.
  1252. return last_newline;
  1253. }
  1254. }
  1255. // Check for potential errors after skipping whitespace().
  1256. if (has_error()) {
  1257. return pop_error();
  1258. }
  1259. _start = _current;
  1260. start_line = line;
  1261. start_column = column;
  1262. leftmost_column = column;
  1263. rightmost_column = column;
  1264. if (pending_indents != 0) {
  1265. // Adjust position for indent.
  1266. _start -= start_column - 1;
  1267. start_column = 1;
  1268. leftmost_column = 1;
  1269. if (pending_indents > 0) {
  1270. // Indents.
  1271. pending_indents--;
  1272. return make_token(Token::INDENT);
  1273. } else {
  1274. // Dedents.
  1275. pending_indents++;
  1276. Token dedent = make_token(Token::DEDENT);
  1277. dedent.end_column += 1;
  1278. dedent.rightmost_column += 1;
  1279. return dedent;
  1280. }
  1281. }
  1282. if (_is_at_end()) {
  1283. return make_token(Token::TK_EOF);
  1284. }
  1285. const char32_t c = _advance();
  1286. if (c == '\\') {
  1287. // Line continuation with backslash.
  1288. if (_peek() == '\r') {
  1289. if (_peek(1) != '\n') {
  1290. return make_error("Unexpected carriage return character.");
  1291. }
  1292. _advance();
  1293. }
  1294. if (_peek() != '\n') {
  1295. return make_error("Expected new line after \"\\\".");
  1296. }
  1297. _advance();
  1298. newline(false);
  1299. line_continuation = true;
  1300. return scan(); // Recurse to get next token.
  1301. }
  1302. line_continuation = false;
  1303. if (is_digit(c)) {
  1304. return number();
  1305. } else if (is_unicode_identifier_start(c)) {
  1306. return potential_identifier();
  1307. }
  1308. switch (c) {
  1309. // String literals.
  1310. case '"':
  1311. case '\'':
  1312. return string();
  1313. // Annotation.
  1314. case '@':
  1315. return annotation();
  1316. // Single characters.
  1317. case '~':
  1318. return make_token(Token::TILDE);
  1319. case ',':
  1320. return make_token(Token::COMMA);
  1321. case ':':
  1322. return make_token(Token::COLON);
  1323. case ';':
  1324. return make_token(Token::SEMICOLON);
  1325. case '$':
  1326. return make_token(Token::DOLLAR);
  1327. case '?':
  1328. return make_token(Token::QUESTION_MARK);
  1329. case '`':
  1330. return make_token(Token::BACKTICK);
  1331. // Parens.
  1332. case '(':
  1333. push_paren('(');
  1334. return make_token(Token::PARENTHESIS_OPEN);
  1335. case '[':
  1336. push_paren('[');
  1337. return make_token(Token::BRACKET_OPEN);
  1338. case '{':
  1339. push_paren('{');
  1340. return make_token(Token::BRACE_OPEN);
  1341. case ')':
  1342. if (!pop_paren('(')) {
  1343. return make_paren_error(c);
  1344. }
  1345. return make_token(Token::PARENTHESIS_CLOSE);
  1346. case ']':
  1347. if (!pop_paren('[')) {
  1348. return make_paren_error(c);
  1349. }
  1350. return make_token(Token::BRACKET_CLOSE);
  1351. case '}':
  1352. if (!pop_paren('{')) {
  1353. return make_paren_error(c);
  1354. }
  1355. return make_token(Token::BRACE_CLOSE);
  1356. // Double characters.
  1357. case '!':
  1358. if (_peek() == '=') {
  1359. _advance();
  1360. return make_token(Token::BANG_EQUAL);
  1361. } else {
  1362. return make_token(Token::BANG);
  1363. }
  1364. case '.':
  1365. if (_peek() == '.') {
  1366. _advance();
  1367. return make_token(Token::PERIOD_PERIOD);
  1368. } else if (is_digit(_peek())) {
  1369. // Number starting with '.'.
  1370. return number();
  1371. } else {
  1372. return make_token(Token::PERIOD);
  1373. }
  1374. case '+':
  1375. if (_peek() == '=') {
  1376. _advance();
  1377. return make_token(Token::PLUS_EQUAL);
  1378. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1379. // Number starting with '+'.
  1380. return number();
  1381. } else {
  1382. return make_token(Token::PLUS);
  1383. }
  1384. case '-':
  1385. if (_peek() == '=') {
  1386. _advance();
  1387. return make_token(Token::MINUS_EQUAL);
  1388. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1389. // Number starting with '-'.
  1390. return number();
  1391. } else if (_peek() == '>') {
  1392. _advance();
  1393. return make_token(Token::FORWARD_ARROW);
  1394. } else {
  1395. return make_token(Token::MINUS);
  1396. }
  1397. case '*':
  1398. if (_peek() == '=') {
  1399. _advance();
  1400. return make_token(Token::STAR_EQUAL);
  1401. } else if (_peek() == '*') {
  1402. if (_peek(1) == '=') {
  1403. _advance();
  1404. _advance(); // Advance both '*' and '='
  1405. return make_token(Token::STAR_STAR_EQUAL);
  1406. }
  1407. _advance();
  1408. return make_token(Token::STAR_STAR);
  1409. } else {
  1410. return make_token(Token::STAR);
  1411. }
  1412. case '/':
  1413. if (_peek() == '=') {
  1414. _advance();
  1415. return make_token(Token::SLASH_EQUAL);
  1416. } else {
  1417. return make_token(Token::SLASH);
  1418. }
  1419. case '%':
  1420. if (_peek() == '=') {
  1421. _advance();
  1422. return make_token(Token::PERCENT_EQUAL);
  1423. } else {
  1424. return make_token(Token::PERCENT);
  1425. }
  1426. case '^':
  1427. if (_peek() == '=') {
  1428. _advance();
  1429. return make_token(Token::CARET_EQUAL);
  1430. } else if (_peek() == '"' || _peek() == '\'') {
  1431. // Node path
  1432. return string();
  1433. } else {
  1434. return make_token(Token::CARET);
  1435. }
  1436. case '&':
  1437. if (_peek() == '&') {
  1438. _advance();
  1439. return make_token(Token::AMPERSAND_AMPERSAND);
  1440. } else if (_peek() == '=') {
  1441. _advance();
  1442. return make_token(Token::AMPERSAND_EQUAL);
  1443. } else if (_peek() == '"' || _peek() == '\'') {
  1444. // String Name
  1445. return string();
  1446. } else {
  1447. return make_token(Token::AMPERSAND);
  1448. }
  1449. case '|':
  1450. if (_peek() == '|') {
  1451. _advance();
  1452. return make_token(Token::PIPE_PIPE);
  1453. } else if (_peek() == '=') {
  1454. _advance();
  1455. return make_token(Token::PIPE_EQUAL);
  1456. } else {
  1457. return make_token(Token::PIPE);
  1458. }
  1459. // Potential VCS conflict markers.
  1460. case '=':
  1461. if (_peek() == '=') {
  1462. return check_vcs_marker('=', Token::EQUAL_EQUAL);
  1463. } else {
  1464. return make_token(Token::EQUAL);
  1465. }
  1466. case '<':
  1467. if (_peek() == '=') {
  1468. _advance();
  1469. return make_token(Token::LESS_EQUAL);
  1470. } else if (_peek() == '<') {
  1471. if (_peek(1) == '=') {
  1472. _advance();
  1473. _advance(); // Advance both '<' and '='
  1474. return make_token(Token::LESS_LESS_EQUAL);
  1475. } else {
  1476. return check_vcs_marker('<', Token::LESS_LESS);
  1477. }
  1478. } else {
  1479. return make_token(Token::LESS);
  1480. }
  1481. case '>':
  1482. if (_peek() == '=') {
  1483. _advance();
  1484. return make_token(Token::GREATER_EQUAL);
  1485. } else if (_peek() == '>') {
  1486. if (_peek(1) == '=') {
  1487. _advance();
  1488. _advance(); // Advance both '>' and '='
  1489. return make_token(Token::GREATER_GREATER_EQUAL);
  1490. } else {
  1491. return check_vcs_marker('>', Token::GREATER_GREATER);
  1492. }
  1493. } else {
  1494. return make_token(Token::GREATER);
  1495. }
  1496. default:
  1497. if (is_whitespace(c)) {
  1498. return make_error(vformat(R"(Invalid white space character U+%04X.)", static_cast<int32_t>(c)));
  1499. } else {
  1500. return make_error(vformat(R"(Invalid character "%c" (U+%04X).)", c, static_cast<int32_t>(c)));
  1501. }
  1502. }
  1503. }
  1504. GDScriptTokenizer::GDScriptTokenizer() {
  1505. #ifdef TOOLS_ENABLED
  1506. if (EditorSettings::get_singleton()) {
  1507. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  1508. }
  1509. #endif // TOOLS_ENABLED
  1510. #ifdef DEBUG_ENABLED
  1511. make_keyword_list();
  1512. #endif // DEBUG_ENABLED
  1513. }