2
0

gdscript_tokenizer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. /*************************************************************************/
  2. /* gdscript_tokenizer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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_macros.h"
  32. #ifdef TOOLS_ENABLED
  33. #include "editor/editor_settings.h"
  34. #endif
  35. static const char *token_names[] = {
  36. "Empty", // EMPTY,
  37. // Basic
  38. "Annotation", // ANNOTATION
  39. "Identifier", // IDENTIFIER,
  40. "Literal", // LITERAL,
  41. // Comparison
  42. "<", // LESS,
  43. "<=", // LESS_EQUAL,
  44. ">", // GREATER,
  45. ">=", // GREATER_EQUAL,
  46. "==", // EQUAL_EQUAL,
  47. "!=", // BANG_EQUAL,
  48. // Logical
  49. "and", // AND,
  50. "or", // OR,
  51. "not", // NOT,
  52. "&&", // AMPERSAND_AMPERSAND,
  53. "||", // PIPE_PIPE,
  54. "!", // BANG,
  55. // Bitwise
  56. "&", // AMPERSAND,
  57. "|", // PIPE,
  58. "~", // TILDE,
  59. "^", // CARET,
  60. "<<", // LESS_LESS,
  61. ">>", // GREATER_GREATER,
  62. // Math
  63. "+", // PLUS,
  64. "-", // MINUS,
  65. "*", // STAR,
  66. "/", // SLASH,
  67. "%", // PERCENT,
  68. // Assignment
  69. "=", // EQUAL,
  70. "+=", // PLUS_EQUAL,
  71. "-=", // MINUS_EQUAL,
  72. "*=", // STAR_EQUAL,
  73. "/=", // SLASH_EQUAL,
  74. "%=", // PERCENT_EQUAL,
  75. "<<=", // LESS_LESS_EQUAL,
  76. ">>=", // GREATER_GREATER_EQUAL,
  77. "&=", // AMPERSAND_EQUAL,
  78. "|=", // PIPE_EQUAL,
  79. "^=", // CARET_EQUAL,
  80. // Control flow
  81. "if", // IF,
  82. "elif", // ELIF,
  83. "else", // ELSE,
  84. "for", // FOR,
  85. "while", // WHILE,
  86. "break", // BREAK,
  87. "continue", // CONTINUE,
  88. "pass", // PASS,
  89. "return", // RETURN,
  90. "match", // MATCH,
  91. // Keywords
  92. "as", // AS,
  93. "assert", // ASSERT,
  94. "await", // AWAIT,
  95. "breakpoint", // BREAKPOINT,
  96. "class", // CLASS,
  97. "class_name", // CLASS_NAME,
  98. "const", // CONST,
  99. "enum", // ENUM,
  100. "extends", // EXTENDS,
  101. "func", // FUNC,
  102. "in", // IN,
  103. "is", // IS,
  104. "namespace", // NAMESPACE
  105. "preload", // PRELOAD,
  106. "self", // SELF,
  107. "signal", // SIGNAL,
  108. "static", // STATIC,
  109. "super", // SUPER,
  110. "var", // VAR,
  111. "void", // VOID,
  112. "yield", // YIELD,
  113. // Punctuation
  114. "[", // BRACKET_OPEN,
  115. "]", // BRACKET_CLOSE,
  116. "{", // BRACE_OPEN,
  117. "}", // BRACE_CLOSE,
  118. "(", // PARENTHESIS_OPEN,
  119. ")", // PARENTHESIS_CLOSE,
  120. ",", // COMMA,
  121. ";", // SEMICOLON,
  122. ".", // PERIOD,
  123. "..", // PERIOD_PERIOD,
  124. ":", // COLON,
  125. "$", // DOLLAR,
  126. "->", // FORWARD_ARROW,
  127. "_", // UNDERSCORE,
  128. // Whitespace
  129. "Newline", // NEWLINE,
  130. "Indent", // INDENT,
  131. "Dedent", // DEDENT,
  132. // Constants
  133. "PI", // CONST_PI,
  134. "TAU", // CONST_TAU,
  135. "INF", // CONST_INF,
  136. "NaN", // CONST_NAN,
  137. // Error message improvement
  138. "VCS conflict marker", // VCS_CONFLICT_MARKER,
  139. "`", // BACKTICK,
  140. "?", // QUESTION_MARK,
  141. // Special
  142. "Error", // ERROR,
  143. "End of file", // EOF,
  144. };
  145. // Avoid desync.
  146. 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.");
  147. const char *GDScriptTokenizer::Token::get_name() const {
  148. ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");
  149. return token_names[type];
  150. }
  151. String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {
  152. ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");
  153. return token_names[p_token_type];
  154. }
  155. void GDScriptTokenizer::set_source_code(const String &p_source_code) {
  156. source = p_source_code;
  157. if (source.empty()) {
  158. _source = L"";
  159. } else {
  160. _source = source.ptr();
  161. }
  162. _current = _source;
  163. line = 1;
  164. column = 1;
  165. length = p_source_code.length();
  166. position = 0;
  167. }
  168. void GDScriptTokenizer::set_cursor_position(int p_line, int p_column) {
  169. cursor_line = p_line;
  170. cursor_column = p_column;
  171. }
  172. void GDScriptTokenizer::set_multiline_mode(bool p_state) {
  173. multiline_mode = p_state;
  174. }
  175. int GDScriptTokenizer::get_cursor_line() const {
  176. return cursor_line;
  177. }
  178. int GDScriptTokenizer::get_cursor_column() const {
  179. return cursor_column;
  180. }
  181. bool GDScriptTokenizer::is_past_cursor() const {
  182. if (line < cursor_line) {
  183. return false;
  184. }
  185. if (line > cursor_line) {
  186. return true;
  187. }
  188. if (column < cursor_column) {
  189. return false;
  190. }
  191. return true;
  192. }
  193. CharType GDScriptTokenizer::_advance() {
  194. if (unlikely(_is_at_end())) {
  195. return '\0';
  196. }
  197. _current++;
  198. column++;
  199. position++;
  200. if (column > rightmost_column) {
  201. rightmost_column = column;
  202. }
  203. if (unlikely(_is_at_end())) {
  204. // Add extra newline even if it's not there, to satisfy the parser.
  205. newline(true);
  206. // Also add needed unindent.
  207. check_indent();
  208. }
  209. return _peek(-1);
  210. }
  211. void GDScriptTokenizer::push_paren(CharType p_char) {
  212. paren_stack.push_back(p_char);
  213. }
  214. bool GDScriptTokenizer::pop_paren(CharType p_expected) {
  215. if (paren_stack.empty()) {
  216. return false;
  217. }
  218. CharType actual = paren_stack.back()->get();
  219. paren_stack.pop_back();
  220. return actual == p_expected;
  221. }
  222. GDScriptTokenizer::Token GDScriptTokenizer::pop_error() {
  223. Token error = error_stack.back()->get();
  224. error_stack.pop_back();
  225. return error;
  226. }
  227. static bool _is_alphanumeric(CharType c) {
  228. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
  229. }
  230. static bool _is_digit(CharType c) {
  231. return (c >= '0' && c <= '9');
  232. }
  233. static bool _is_hex_digit(CharType c) {
  234. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  235. }
  236. static bool _is_binary_digit(CharType c) {
  237. return (c == '0' || c == '1');
  238. }
  239. GDScriptTokenizer::Token GDScriptTokenizer::make_token(Token::Type p_type) {
  240. Token token(p_type);
  241. token.start_line = start_line;
  242. token.end_line = line;
  243. token.start_column = start_column;
  244. token.end_column = column;
  245. token.leftmost_column = leftmost_column;
  246. token.rightmost_column = rightmost_column;
  247. token.source = String(_start, _current - _start);
  248. if (p_type != Token::ERROR && cursor_line > -1) {
  249. // Also count whitespace after token.
  250. int offset = 0;
  251. while (_peek(offset) == ' ' || _peek(offset) == '\t') {
  252. offset++;
  253. }
  254. int last_column = column + offset;
  255. // Check cursor position in token.
  256. if (start_line == line) {
  257. // Single line token.
  258. if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {
  259. token.cursor_position = cursor_column - start_column;
  260. if (cursor_column == start_column) {
  261. token.cursor_place = CURSOR_BEGINNING;
  262. } else if (cursor_column < column) {
  263. token.cursor_place = CURSOR_MIDDLE;
  264. } else {
  265. token.cursor_place = CURSOR_END;
  266. }
  267. }
  268. } else {
  269. // Multi line token.
  270. if (cursor_line == start_line && cursor_column >= start_column) {
  271. // Is in first line.
  272. token.cursor_position = cursor_column - start_column;
  273. if (cursor_column == start_column) {
  274. token.cursor_place = CURSOR_BEGINNING;
  275. } else {
  276. token.cursor_place = CURSOR_MIDDLE;
  277. }
  278. } else if (cursor_line == line && cursor_column <= last_column) {
  279. // Is in last line.
  280. token.cursor_position = cursor_column - start_column;
  281. if (cursor_column < column) {
  282. token.cursor_place = CURSOR_MIDDLE;
  283. } else {
  284. token.cursor_place = CURSOR_END;
  285. }
  286. } else if (cursor_line > start_line && cursor_line < line) {
  287. // Is in middle line.
  288. token.cursor_position = CURSOR_MIDDLE;
  289. }
  290. }
  291. }
  292. return token;
  293. }
  294. GDScriptTokenizer::Token GDScriptTokenizer::make_literal(const Variant &p_literal) {
  295. Token token = make_token(Token::LITERAL);
  296. token.literal = p_literal;
  297. return token;
  298. }
  299. GDScriptTokenizer::Token GDScriptTokenizer::make_identifier(const StringName &p_identifier) {
  300. Token identifier = make_token(Token::IDENTIFIER);
  301. identifier.literal = p_identifier;
  302. return identifier;
  303. }
  304. GDScriptTokenizer::Token GDScriptTokenizer::make_error(const String &p_message) {
  305. Token error = make_token(Token::ERROR);
  306. error.literal = p_message;
  307. return error;
  308. }
  309. void GDScriptTokenizer::push_error(const String &p_message) {
  310. Token error = make_error(p_message);
  311. error_stack.push_back(error);
  312. }
  313. void GDScriptTokenizer::push_error(const Token &p_error) {
  314. error_stack.push_back(p_error);
  315. }
  316. GDScriptTokenizer::Token GDScriptTokenizer::make_paren_error(CharType p_paren) {
  317. if (paren_stack.empty()) {
  318. return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));
  319. }
  320. Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));
  321. paren_stack.pop_back(); // Remove opening one anyway.
  322. return error;
  323. }
  324. GDScriptTokenizer::Token GDScriptTokenizer::check_vcs_marker(CharType p_test, Token::Type p_double_type) {
  325. const CharType *next = _current + 1;
  326. int chars = 2; // Two already matched.
  327. // Test before consuming characters, since we don't want to consume more than needed.
  328. while (*next == p_test) {
  329. chars++;
  330. next++;
  331. }
  332. if (chars >= 7) {
  333. // It is a VCS conflict marker.
  334. while (chars > 1) {
  335. // Consume all characters (first was already consumed by scan()).
  336. _advance();
  337. chars--;
  338. }
  339. return make_token(Token::VCS_CONFLICT_MARKER);
  340. } else {
  341. // It is only a regular double character token, so we consume the second character.
  342. _advance();
  343. return make_token(p_double_type);
  344. }
  345. }
  346. GDScriptTokenizer::Token GDScriptTokenizer::annotation() {
  347. if (!_is_alphanumeric(_peek())) {
  348. push_error("Expected annotation identifier after \"@\".");
  349. }
  350. while (_is_alphanumeric(_peek())) {
  351. // Consume all identifier characters.
  352. _advance();
  353. }
  354. Token annotation = make_token(Token::ANNOTATION);
  355. annotation.literal = StringName(annotation.source);
  356. return annotation;
  357. }
  358. GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() {
  359. #define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
  360. KEYWORD_GROUP('a') \
  361. KEYWORD("as", Token::AS) \
  362. KEYWORD("and", Token::AND) \
  363. KEYWORD("assert", Token::ASSERT) \
  364. KEYWORD("await", Token::AWAIT) \
  365. KEYWORD_GROUP('b') \
  366. KEYWORD("break", Token::BREAK) \
  367. KEYWORD("breakpoint", Token::BREAKPOINT) \
  368. KEYWORD_GROUP('c') \
  369. KEYWORD("class", Token::CLASS) \
  370. KEYWORD("class_name", Token::CLASS_NAME) \
  371. KEYWORD("const", Token::CONST) \
  372. KEYWORD("continue", Token::CONTINUE) \
  373. KEYWORD_GROUP('e') \
  374. KEYWORD("elif", Token::ELIF) \
  375. KEYWORD("else", Token::ELSE) \
  376. KEYWORD("enum", Token::ENUM) \
  377. KEYWORD("extends", Token::EXTENDS) \
  378. KEYWORD_GROUP('f') \
  379. KEYWORD("for", Token::FOR) \
  380. KEYWORD("func", Token::FUNC) \
  381. KEYWORD_GROUP('i') \
  382. KEYWORD("if", Token::IF) \
  383. KEYWORD("in", Token::IN) \
  384. KEYWORD("is", Token::IS) \
  385. KEYWORD_GROUP('m') \
  386. KEYWORD("match", Token::MATCH) \
  387. KEYWORD_GROUP('n') \
  388. KEYWORD("namespace", Token::NAMESPACE) \
  389. KEYWORD("not", Token::NOT) \
  390. KEYWORD_GROUP('o') \
  391. KEYWORD("or", Token::OR) \
  392. KEYWORD_GROUP('p') \
  393. KEYWORD("pass", Token::PASS) \
  394. KEYWORD("preload", Token::PRELOAD) \
  395. KEYWORD_GROUP('r') \
  396. KEYWORD("return", Token::RETURN) \
  397. KEYWORD_GROUP('s') \
  398. KEYWORD("self", Token::SELF) \
  399. KEYWORD("signal", Token::SIGNAL) \
  400. KEYWORD("static", Token::STATIC) \
  401. KEYWORD("super", Token::SUPER) \
  402. KEYWORD_GROUP('v') \
  403. KEYWORD("var", Token::VAR) \
  404. KEYWORD("void", Token::VOID) \
  405. KEYWORD_GROUP('w') \
  406. KEYWORD("while", Token::WHILE) \
  407. KEYWORD_GROUP('y') \
  408. KEYWORD("yield", Token::YIELD) \
  409. KEYWORD_GROUP('I') \
  410. KEYWORD("INF", Token::CONST_INF) \
  411. KEYWORD_GROUP('N') \
  412. KEYWORD("NAN", Token::CONST_NAN) \
  413. KEYWORD_GROUP('P') \
  414. KEYWORD("PI", Token::CONST_PI) \
  415. KEYWORD_GROUP('T') \
  416. KEYWORD("TAU", Token::CONST_TAU)
  417. #define MIN_KEYWORD_LENGTH 2
  418. #define MAX_KEYWORD_LENGTH 10
  419. // Consume all alphanumeric characters.
  420. while (_is_alphanumeric(_peek())) {
  421. _advance();
  422. }
  423. int length = _current - _start;
  424. if (length == 1 && _peek(-1) == '_') {
  425. // Lone underscore.
  426. return make_token(Token::UNDERSCORE);
  427. }
  428. String name(_start, length);
  429. if (length < MIN_KEYWORD_LENGTH || length > MAX_KEYWORD_LENGTH) {
  430. // Cannot be a keyword, as the length doesn't match any.
  431. return make_identifier(name);
  432. }
  433. // Define some helper macros for the switch case.
  434. #define KEYWORD_GROUP_CASE(char) \
  435. break; \
  436. case char:
  437. #define KEYWORD(keyword, token_type) \
  438. { \
  439. const int keyword_length = sizeof(keyword) - 1; \
  440. static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
  441. static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
  442. if (keyword_length == length && name == keyword) { \
  443. return make_token(token_type); \
  444. } \
  445. }
  446. // Find if it's a keyword.
  447. switch (_start[0]) {
  448. default:
  449. KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
  450. break;
  451. }
  452. // Check if it's a special literal
  453. if (length == 4) {
  454. if (name == "true") {
  455. return make_literal(true);
  456. } else if (name == "null") {
  457. return make_literal(Variant());
  458. }
  459. } else if (length == 5) {
  460. if (name == "false") {
  461. return make_literal(false);
  462. }
  463. }
  464. // Not a keyword, so must be an identifier.
  465. return make_identifier(name);
  466. #undef KEYWORDS
  467. #undef MIN_KEYWORD_LENGTH
  468. #undef MAX_KEYWORD_LENGTH
  469. #undef KEYWORD_GROUP_CASE
  470. #undef KEYWORD
  471. }
  472. void GDScriptTokenizer::newline(bool p_make_token) {
  473. // Don't overwrite previous newline, nor create if we want a line contination.
  474. if (p_make_token && !pending_newline && !line_continuation) {
  475. Token newline(Token::NEWLINE);
  476. newline.start_line = line;
  477. newline.end_line = line;
  478. newline.start_column = column - 1;
  479. newline.end_column = column;
  480. newline.leftmost_column = newline.start_column;
  481. newline.rightmost_column = newline.end_column;
  482. pending_newline = true;
  483. last_newline = newline;
  484. }
  485. // Increment line/column counters.
  486. line++;
  487. column = 1;
  488. leftmost_column = 1;
  489. }
  490. GDScriptTokenizer::Token GDScriptTokenizer::number() {
  491. int base = 10;
  492. bool has_decimal = false;
  493. bool has_exponent = false;
  494. bool has_error = false;
  495. bool (*digit_check_func)(CharType) = _is_digit;
  496. if (_peek(-1) == '.') {
  497. has_decimal = true;
  498. } else if (_peek(-1) == '0') {
  499. if (_peek() == 'x') {
  500. // Hexadecimal.
  501. base = 16;
  502. digit_check_func = _is_hex_digit;
  503. _advance();
  504. } else if (_peek() == 'b') {
  505. // Binary.
  506. base = 2;
  507. digit_check_func = _is_binary_digit;
  508. _advance();
  509. }
  510. }
  511. // Allow '_' to be used in a number, for readability.
  512. while (digit_check_func(_peek()) || _peek() == '_') {
  513. _advance();
  514. }
  515. // It might be a ".." token (instead of decimal point) so we check if it's not.
  516. if (_peek() == '.' && _peek(1) != '.') {
  517. if (base == 10 && !has_decimal) {
  518. has_decimal = true;
  519. } else if (base == 10) {
  520. Token error = make_error("Cannot use a decimal point twice in a number.");
  521. error.start_column = column;
  522. error.leftmost_column = column;
  523. error.end_column = column + 1;
  524. error.rightmost_column = column + 1;
  525. push_error(error);
  526. has_error = true;
  527. } else if (base == 16) {
  528. Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
  529. error.start_column = column;
  530. error.leftmost_column = column;
  531. error.end_column = column + 1;
  532. error.rightmost_column = column + 1;
  533. push_error(error);
  534. has_error = true;
  535. } else {
  536. Token error = make_error("Cannot use a decimal point in a binary number.");
  537. error.start_column = column;
  538. error.leftmost_column = column;
  539. error.end_column = column + 1;
  540. error.rightmost_column = column + 1;
  541. push_error(error);
  542. has_error = true;
  543. }
  544. if (!has_error) {
  545. _advance();
  546. // Consume decimal digits.
  547. while (_is_digit(_peek()) || _peek() == '_') {
  548. _advance();
  549. }
  550. }
  551. }
  552. if (base == 10) {
  553. if (_peek() == 'e' || _peek() == 'E') {
  554. has_exponent = true;
  555. _advance();
  556. if (_peek() == '+' || _peek() == '-') {
  557. // Exponent sign.
  558. _advance();
  559. }
  560. // Consume exponent digits.
  561. while (_is_digit(_peek()) || _peek() == '_') {
  562. _advance();
  563. }
  564. }
  565. }
  566. // Detect extra decimal point.
  567. if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
  568. Token error = make_error("Cannot use a decimal point twice in a number.");
  569. error.start_column = column;
  570. error.leftmost_column = column;
  571. error.end_column = column + 1;
  572. error.rightmost_column = column + 1;
  573. push_error(error);
  574. has_error = true;
  575. } else if (_is_alphanumeric(_peek())) {
  576. // Letter at the end of the number.
  577. push_error("Invalid numeric notation.");
  578. }
  579. // Create a string with the whole number.
  580. int length = _current - _start;
  581. String number = String(_start, length).replace("_", "");
  582. // Convert to the appropriate literal type.
  583. if (base == 16) {
  584. int64_t value = number.hex_to_int();
  585. return make_literal(value);
  586. } else if (base == 2) {
  587. int64_t value = number.bin_to_int();
  588. return make_literal(value);
  589. } else if (has_decimal || has_exponent) {
  590. double value = number.to_double();
  591. return make_literal(value);
  592. } else {
  593. int64_t value = number.to_int();
  594. return make_literal(value);
  595. }
  596. }
  597. GDScriptTokenizer::Token GDScriptTokenizer::string() {
  598. enum StringType {
  599. STRING_REGULAR,
  600. STRING_NAME,
  601. STRING_NODEPATH,
  602. };
  603. bool is_multiline = false;
  604. StringType type = STRING_REGULAR;
  605. if (_peek(-1) == '&') {
  606. type = STRING_NAME;
  607. _advance();
  608. } else if (_peek(-1) == '^') {
  609. type = STRING_NODEPATH;
  610. _advance();
  611. }
  612. CharType quote_char = _peek(-1);
  613. if (_peek() == quote_char && _peek(1) == quote_char) {
  614. is_multiline = true;
  615. // Consume all quotes.
  616. _advance();
  617. _advance();
  618. }
  619. String result;
  620. for (;;) {
  621. // Consume actual string.
  622. if (_is_at_end()) {
  623. return make_error("Unterminated string.");
  624. }
  625. CharType ch = _peek();
  626. if (ch == '\\') {
  627. // Escape pattern.
  628. _advance();
  629. if (_is_at_end()) {
  630. return make_error("Unterminated string.");
  631. }
  632. // Grab escape character.
  633. CharType code = _peek();
  634. _advance();
  635. if (_is_at_end()) {
  636. return make_error("Unterminated string.");
  637. }
  638. CharType escaped = 0;
  639. bool valid_escape = true;
  640. switch (code) {
  641. case 'a':
  642. escaped = '\a';
  643. break;
  644. case 'b':
  645. escaped = '\b';
  646. break;
  647. case 'f':
  648. escaped = '\f';
  649. break;
  650. case 'n':
  651. escaped = '\n';
  652. break;
  653. case 'r':
  654. escaped = '\r';
  655. break;
  656. case 't':
  657. escaped = '\t';
  658. break;
  659. case 'v':
  660. escaped = '\v';
  661. break;
  662. case '\'':
  663. escaped = '\'';
  664. break;
  665. case '\"':
  666. escaped = '\"';
  667. break;
  668. case '\\':
  669. escaped = '\\';
  670. break;
  671. case 'u':
  672. // Hexadecimal sequence.
  673. for (int i = 0; i < 4; i++) {
  674. if (_is_at_end()) {
  675. return make_error("Unterminated string.");
  676. }
  677. CharType digit = _peek();
  678. CharType value = 0;
  679. if (digit >= '0' && digit <= '9') {
  680. value = digit - '0';
  681. } else if (digit >= 'a' && digit <= 'f') {
  682. value = digit - 'a';
  683. value += 10;
  684. } else if (digit >= 'A' && digit <= 'F') {
  685. value = digit - 'A';
  686. value += 10;
  687. } else {
  688. // Make error, but keep parsing the string.
  689. Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
  690. error.start_column = column;
  691. error.leftmost_column = error.start_column;
  692. error.end_column = column + 1;
  693. error.rightmost_column = error.end_column;
  694. push_error(error);
  695. valid_escape = false;
  696. break;
  697. }
  698. escaped <<= 4;
  699. escaped |= value;
  700. _advance();
  701. }
  702. break;
  703. case '\r':
  704. if (_peek() != '\n') {
  705. // Carriage return without newline in string. (???)
  706. // Just add it to the string and keep going.
  707. result += ch;
  708. _advance();
  709. break;
  710. }
  711. [[fallthrough]];
  712. case '\n':
  713. // Escaping newline.
  714. newline(false);
  715. valid_escape = false; // Don't add to the string.
  716. break;
  717. default:
  718. Token error = make_error("Invalid escape in string.");
  719. error.start_column = column - 2;
  720. error.leftmost_column = error.start_column;
  721. push_error(error);
  722. valid_escape = false;
  723. break;
  724. }
  725. if (valid_escape) {
  726. result += escaped;
  727. }
  728. } else if (ch == quote_char) {
  729. _advance();
  730. if (is_multiline) {
  731. if (_peek() == quote_char && _peek(1) == quote_char) {
  732. // Ended the multiline string. Consume all quotes.
  733. _advance();
  734. _advance();
  735. break;
  736. }
  737. } else {
  738. // Ended single-line string.
  739. break;
  740. }
  741. } else {
  742. result += ch;
  743. _advance();
  744. if (ch == '\n') {
  745. newline(false);
  746. }
  747. }
  748. }
  749. // Make the literal.
  750. Variant string;
  751. switch (type) {
  752. case STRING_NAME:
  753. string = StringName(result);
  754. break;
  755. case STRING_NODEPATH:
  756. string = NodePath(result);
  757. break;
  758. case STRING_REGULAR:
  759. string = result;
  760. break;
  761. }
  762. return make_literal(string);
  763. }
  764. void GDScriptTokenizer::check_indent() {
  765. ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
  766. if (_is_at_end()) {
  767. // Send dedents for every indent level.
  768. pending_indents -= indent_level();
  769. indent_stack.clear();
  770. return;
  771. }
  772. for (;;) {
  773. CharType current_indent_char = _peek();
  774. int indent_count = 0;
  775. if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
  776. // First character of the line is not whitespace, so we clear all indentation levels.
  777. // Unless we are in a continuation or in multiline mode (inside expression).
  778. if (line_continuation || multiline_mode) {
  779. return;
  780. }
  781. pending_indents -= indent_level();
  782. indent_stack.clear();
  783. return;
  784. }
  785. if (_peek() == '\r') {
  786. _advance();
  787. if (_peek() != '\n') {
  788. push_error("Stray carriage return character in source code.");
  789. }
  790. }
  791. if (_peek() == '\n') {
  792. // Empty line, keep going.
  793. _advance();
  794. newline(false);
  795. continue;
  796. }
  797. // Check indent level.
  798. bool mixed = false;
  799. while (!_is_at_end()) {
  800. CharType space = _peek();
  801. if (space == '\t') {
  802. // Consider individual tab columns.
  803. column += tab_size - 1;
  804. indent_count += tab_size;
  805. } else if (space == ' ') {
  806. indent_count += 1;
  807. } else {
  808. break;
  809. }
  810. mixed = mixed || space != current_indent_char;
  811. _advance();
  812. }
  813. if (mixed) {
  814. Token error = make_error("Mixed use of tabs and spaces for indentation.");
  815. error.start_line = line;
  816. error.start_column = 1;
  817. error.leftmost_column = 1;
  818. error.rightmost_column = column;
  819. push_error(error);
  820. }
  821. if (_is_at_end()) {
  822. // Reached the end with an empty line, so just dedent as much as needed.
  823. pending_indents -= indent_level();
  824. indent_stack.clear();
  825. return;
  826. }
  827. if (_peek() == '\r') {
  828. _advance();
  829. if (_peek() != '\n') {
  830. push_error("Stray carriage return character in source code.");
  831. }
  832. }
  833. if (_peek() == '\n') {
  834. // Empty line, keep going.
  835. _advance();
  836. newline(false);
  837. continue;
  838. }
  839. if (_peek() == '#') {
  840. // Comment. Advance to the next line.
  841. while (_peek() != '\n' && !_is_at_end()) {
  842. _advance();
  843. }
  844. if (_is_at_end()) {
  845. // Reached the end with an empty line, so just dedent as much as needed.
  846. pending_indents -= indent_level();
  847. indent_stack.clear();
  848. return;
  849. }
  850. _advance(); // Consume '\n'.
  851. newline(false);
  852. continue;
  853. }
  854. if (line_continuation || multiline_mode) {
  855. // We cleared up all the whitespace at the beginning of the line.
  856. // But if this is a continuation or multiline mode and we don't want any indentation change.
  857. return;
  858. }
  859. // Check if indentation character is consistent.
  860. if (indent_char == '\0') {
  861. // First time indenting, choose character now.
  862. indent_char = current_indent_char;
  863. } else if (current_indent_char != indent_char) {
  864. Token error = make_error(vformat("Used \"%c\" for indentation instead \"%c\" as used before in the file.", String(&current_indent_char, 1).c_escape(), String(&indent_char, 1).c_escape()));
  865. error.start_line = line;
  866. error.start_column = 1;
  867. error.leftmost_column = 1;
  868. error.rightmost_column = column;
  869. push_error(error);
  870. }
  871. // Now we can do actual indentation changes.
  872. // Check if indent or dedent.
  873. int previous_indent = 0;
  874. if (indent_level() > 0) {
  875. previous_indent = indent_stack.back()->get();
  876. }
  877. if (indent_count == previous_indent) {
  878. // No change in indentation.
  879. return;
  880. }
  881. if (indent_count > previous_indent) {
  882. // Indentation increased.
  883. indent_stack.push_back(indent_count);
  884. pending_indents++;
  885. } else {
  886. // Indentation decreased (dedent).
  887. if (indent_level() == 0) {
  888. push_error("Tokenizer bug: trying to dedent without previous indent.");
  889. return;
  890. }
  891. while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
  892. indent_stack.pop_back();
  893. pending_indents--;
  894. }
  895. if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
  896. // Mismatched indentation alignment.
  897. Token error = make_error("Unindent doesn't match the previous indentation level.");
  898. error.start_line = line;
  899. error.start_column = 1;
  900. error.leftmost_column = 1;
  901. error.end_column = column + 1;
  902. error.rightmost_column = column + 1;
  903. push_error(error);
  904. // Still, we'll be lenient and keep going, so keep this level in the stack.
  905. indent_stack.push_back(indent_count);
  906. }
  907. }
  908. break; // Get out of the loop in any case.
  909. }
  910. }
  911. void GDScriptTokenizer::_skip_whitespace() {
  912. if (pending_indents != 0) {
  913. // Still have some indent/dedent tokens to give.
  914. return;
  915. }
  916. bool is_bol = column == 1; // Beginning of line.
  917. if (is_bol) {
  918. check_indent();
  919. return;
  920. }
  921. for (;;) {
  922. CharType c = _peek();
  923. switch (c) {
  924. case ' ':
  925. _advance();
  926. break;
  927. case '\t':
  928. _advance();
  929. // Consider individual tab columns.
  930. column += tab_size - 1;
  931. break;
  932. case '\r':
  933. _advance(); // Consume either way.
  934. if (_peek() != '\n') {
  935. push_error("Stray carriage return character in source code.");
  936. return;
  937. }
  938. break;
  939. case '\n':
  940. _advance();
  941. newline(!is_bol); // Don't create new line token if line is empty.
  942. check_indent();
  943. break;
  944. case '#':
  945. // Comment.
  946. while (_peek() != '\n' && !_is_at_end()) {
  947. _advance();
  948. }
  949. if (_is_at_end()) {
  950. return;
  951. }
  952. _advance(); // Consume '\n'
  953. newline(!is_bol);
  954. check_indent();
  955. break;
  956. default:
  957. return;
  958. }
  959. }
  960. }
  961. GDScriptTokenizer::Token GDScriptTokenizer::scan() {
  962. if (has_error()) {
  963. return pop_error();
  964. }
  965. _skip_whitespace();
  966. if (pending_newline) {
  967. pending_newline = false;
  968. if (!multiline_mode) {
  969. // Don't return newline tokens on multine mode.
  970. return last_newline;
  971. }
  972. }
  973. // Check for potential errors after skipping whitespace().
  974. if (has_error()) {
  975. return pop_error();
  976. }
  977. _start = _current;
  978. start_line = line;
  979. start_column = column;
  980. leftmost_column = column;
  981. rightmost_column = column;
  982. if (pending_indents != 0) {
  983. // Adjust position for indent.
  984. _start -= start_column - 1;
  985. start_column = 1;
  986. leftmost_column = 1;
  987. if (pending_indents > 0) {
  988. // Indents.
  989. pending_indents--;
  990. return make_token(Token::INDENT);
  991. } else {
  992. // Dedents.
  993. pending_indents++;
  994. Token dedent = make_token(Token::DEDENT);
  995. dedent.end_column += 1;
  996. dedent.rightmost_column += 1;
  997. return dedent;
  998. }
  999. }
  1000. if (_is_at_end()) {
  1001. return make_token(Token::TK_EOF);
  1002. }
  1003. const CharType c = _advance();
  1004. if (c == '\\') {
  1005. // Line continuation with backslash.
  1006. if (_peek() == '\r') {
  1007. if (_peek(1) != '\n') {
  1008. return make_error("Unexpected carriage return character.");
  1009. }
  1010. _advance();
  1011. }
  1012. if (_peek() != '\n') {
  1013. return make_error("Expected new line after \"\\\".");
  1014. }
  1015. _advance();
  1016. newline(false);
  1017. line_continuation = true;
  1018. return scan(); // Recurse to get next token.
  1019. }
  1020. line_continuation = false;
  1021. if (_is_digit(c)) {
  1022. return number();
  1023. } else if (_is_alphanumeric(c)) {
  1024. return potential_identifier();
  1025. }
  1026. switch (c) {
  1027. // String literals.
  1028. case '"':
  1029. case '\'':
  1030. return string();
  1031. // Annotation.
  1032. case '@':
  1033. return annotation();
  1034. // Single characters.
  1035. case '~':
  1036. return make_token(Token::TILDE);
  1037. case ',':
  1038. return make_token(Token::COMMA);
  1039. case ':':
  1040. return make_token(Token::COLON);
  1041. case ';':
  1042. return make_token(Token::SEMICOLON);
  1043. case '$':
  1044. return make_token(Token::DOLLAR);
  1045. case '?':
  1046. return make_token(Token::QUESTION_MARK);
  1047. case '`':
  1048. return make_token(Token::BACKTICK);
  1049. // Parens.
  1050. case '(':
  1051. push_paren('(');
  1052. return make_token(Token::PARENTHESIS_OPEN);
  1053. case '[':
  1054. push_paren('[');
  1055. return make_token(Token::BRACKET_OPEN);
  1056. case '{':
  1057. push_paren('{');
  1058. return make_token(Token::BRACE_OPEN);
  1059. case ')':
  1060. if (!pop_paren('(')) {
  1061. return make_paren_error(c);
  1062. }
  1063. return make_token(Token::PARENTHESIS_CLOSE);
  1064. case ']':
  1065. if (!pop_paren('[')) {
  1066. return make_paren_error(c);
  1067. }
  1068. return make_token(Token::BRACKET_CLOSE);
  1069. case '}':
  1070. if (!pop_paren('{')) {
  1071. return make_paren_error(c);
  1072. }
  1073. return make_token(Token::BRACE_CLOSE);
  1074. // Double characters.
  1075. case '!':
  1076. if (_peek() == '=') {
  1077. _advance();
  1078. return make_token(Token::BANG_EQUAL);
  1079. } else {
  1080. return make_token(Token::BANG);
  1081. }
  1082. case '.':
  1083. if (_peek() == '.') {
  1084. _advance();
  1085. return make_token(Token::PERIOD_PERIOD);
  1086. } else if (_is_digit(_peek())) {
  1087. // Number starting with '.'.
  1088. return number();
  1089. } else {
  1090. return make_token(Token::PERIOD);
  1091. }
  1092. case '+':
  1093. if (_peek() == '=') {
  1094. _advance();
  1095. return make_token(Token::PLUS_EQUAL);
  1096. } else {
  1097. return make_token(Token::PLUS);
  1098. }
  1099. case '-':
  1100. if (_peek() == '=') {
  1101. _advance();
  1102. return make_token(Token::MINUS_EQUAL);
  1103. } else if (_peek() == '>') {
  1104. _advance();
  1105. return make_token(Token::FORWARD_ARROW);
  1106. } else {
  1107. return make_token(Token::MINUS);
  1108. }
  1109. case '*':
  1110. if (_peek() == '=') {
  1111. _advance();
  1112. return make_token(Token::STAR_EQUAL);
  1113. } else {
  1114. return make_token(Token::STAR);
  1115. }
  1116. case '/':
  1117. if (_peek() == '=') {
  1118. _advance();
  1119. return make_token(Token::SLASH_EQUAL);
  1120. } else {
  1121. return make_token(Token::SLASH);
  1122. }
  1123. case '%':
  1124. if (_peek() == '=') {
  1125. _advance();
  1126. return make_token(Token::PERCENT_EQUAL);
  1127. } else {
  1128. return make_token(Token::PERCENT);
  1129. }
  1130. case '^':
  1131. if (_peek() == '=') {
  1132. _advance();
  1133. return make_token(Token::CARET_EQUAL);
  1134. } else if (_peek() == '"' || _peek() == '\'') {
  1135. // Node path
  1136. return string();
  1137. } else {
  1138. return make_token(Token::CARET);
  1139. }
  1140. case '&':
  1141. if (_peek() == '&') {
  1142. _advance();
  1143. return make_token(Token::AMPERSAND_AMPERSAND);
  1144. } else if (_peek() == '=') {
  1145. _advance();
  1146. return make_token(Token::AMPERSAND_EQUAL);
  1147. } else if (_peek() == '"' || _peek() == '\'') {
  1148. // String Name
  1149. return string();
  1150. } else {
  1151. return make_token(Token::AMPERSAND);
  1152. }
  1153. case '|':
  1154. if (_peek() == '|') {
  1155. _advance();
  1156. return make_token(Token::PIPE_PIPE);
  1157. } else if (_peek() == '=') {
  1158. _advance();
  1159. return make_token(Token::PIPE_EQUAL);
  1160. } else {
  1161. return make_token(Token::PIPE);
  1162. }
  1163. // Potential VCS conflict markers.
  1164. case '=':
  1165. if (_peek() == '=') {
  1166. return check_vcs_marker('=', Token::EQUAL_EQUAL);
  1167. } else {
  1168. return make_token(Token::EQUAL);
  1169. }
  1170. case '<':
  1171. if (_peek() == '=') {
  1172. _advance();
  1173. return make_token(Token::LESS_EQUAL);
  1174. } else if (_peek() == '<') {
  1175. if (_peek(1) == '=') {
  1176. _advance();
  1177. _advance(); // Advance both '<' and '='
  1178. return make_token(Token::LESS_LESS_EQUAL);
  1179. } else {
  1180. return check_vcs_marker('<', Token::LESS_LESS);
  1181. }
  1182. } else {
  1183. return make_token(Token::LESS);
  1184. }
  1185. case '>':
  1186. if (_peek() == '=') {
  1187. _advance();
  1188. return make_token(Token::GREATER_EQUAL);
  1189. } else if (_peek() == '>') {
  1190. if (_peek(1) == '=') {
  1191. _advance();
  1192. _advance(); // Advance both '>' and '='
  1193. return make_token(Token::GREATER_GREATER_EQUAL);
  1194. } else {
  1195. return check_vcs_marker('>', Token::GREATER_GREATER);
  1196. }
  1197. } else {
  1198. return make_token(Token::GREATER);
  1199. }
  1200. default:
  1201. return make_error(vformat(R"(Unknown character "%s".")", String(&c, 1)));
  1202. }
  1203. }
  1204. GDScriptTokenizer::GDScriptTokenizer() {
  1205. #ifdef TOOLS_ENABLED
  1206. if (EditorSettings::get_singleton()) {
  1207. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
  1208. }
  1209. #endif // TOOLS_ENABLED
  1210. }