gdscript_tokenizer.cpp 46 KB

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