gdscript_tokenizer.cpp 45 KB

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