gdscript_tokenizer.cpp 46 KB

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