Path: blob/master/modules/gdscript/gdscript_tokenizer.cpp
10277 views
/**************************************************************************/1/* gdscript_tokenizer.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdscript_tokenizer.h"3132#include "core/error/error_macros.h"33#include "core/string/char_utils.h"3435#ifdef DEBUG_ENABLED36#include "servers/text_server.h"37#endif3839#ifdef TOOLS_ENABLED40#include "editor/settings/editor_settings.h"41#endif4243static const char *token_names[] = {44"Empty", // EMPTY,45// Basic46"Annotation", // ANNOTATION47"Identifier", // IDENTIFIER,48"Literal", // LITERAL,49// Comparison50"<", // LESS,51"<=", // LESS_EQUAL,52">", // GREATER,53">=", // GREATER_EQUAL,54"==", // EQUAL_EQUAL,55"!=", // BANG_EQUAL,56// Logical57"and", // AND,58"or", // OR,59"not", // NOT,60"&&", // AMPERSAND_AMPERSAND,61"||", // PIPE_PIPE,62"!", // BANG,63// Bitwise64"&", // AMPERSAND,65"|", // PIPE,66"~", // TILDE,67"^", // CARET,68"<<", // LESS_LESS,69">>", // GREATER_GREATER,70// Math71"+", // PLUS,72"-", // MINUS,73"*", // STAR,74"**", // STAR_STAR,75"/", // SLASH,76"%", // PERCENT,77// Assignment78"=", // EQUAL,79"+=", // PLUS_EQUAL,80"-=", // MINUS_EQUAL,81"*=", // STAR_EQUAL,82"**=", // STAR_STAR_EQUAL,83"/=", // SLASH_EQUAL,84"%=", // PERCENT_EQUAL,85"<<=", // LESS_LESS_EQUAL,86">>=", // GREATER_GREATER_EQUAL,87"&=", // AMPERSAND_EQUAL,88"|=", // PIPE_EQUAL,89"^=", // CARET_EQUAL,90// Control flow91"if", // IF,92"elif", // ELIF,93"else", // ELSE,94"for", // FOR,95"while", // WHILE,96"break", // BREAK,97"continue", // CONTINUE,98"pass", // PASS,99"return", // RETURN,100"match", // MATCH,101"when", // WHEN,102// Keywords103"as", // AS,104"assert", // ASSERT,105"await", // AWAIT,106"breakpoint", // BREAKPOINT,107"class", // CLASS,108"class_name", // CLASS_NAME,109"const", // TK_CONST,110"enum", // ENUM,111"extends", // EXTENDS,112"func", // FUNC,113"in", // TK_IN,114"is", // IS,115"namespace", // NAMESPACE116"preload", // PRELOAD,117"self", // SELF,118"signal", // SIGNAL,119"static", // STATIC,120"super", // SUPER,121"trait", // TRAIT,122"var", // VAR,123"void", // TK_VOID,124"yield", // YIELD,125// Punctuation126"[", // BRACKET_OPEN,127"]", // BRACKET_CLOSE,128"{", // BRACE_OPEN,129"}", // BRACE_CLOSE,130"(", // PARENTHESIS_OPEN,131")", // PARENTHESIS_CLOSE,132",", // COMMA,133";", // SEMICOLON,134".", // PERIOD,135"..", // PERIOD_PERIOD,136"...", // PERIOD_PERIOD_PERIOD,137":", // COLON,138"$", // DOLLAR,139"->", // FORWARD_ARROW,140"_", // UNDERSCORE,141// Whitespace142"Newline", // NEWLINE,143"Indent", // INDENT,144"Dedent", // DEDENT,145// Constants146"PI", // CONST_PI,147"TAU", // CONST_TAU,148"INF", // CONST_INF,149"NaN", // CONST_NAN,150// Error message improvement151"VCS conflict marker", // VCS_CONFLICT_MARKER,152"`", // BACKTICK,153"?", // QUESTION_MARK,154// Special155"Error", // ERROR,156"End of file", // EOF,157};158159// Avoid desync.160static_assert(std::size(token_names) == GDScriptTokenizer::Token::TK_MAX, "Amount of token names don't match the amount of token types.");161162const char *GDScriptTokenizer::Token::get_name() const {163ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");164return token_names[type];165}166167String GDScriptTokenizer::Token::get_debug_name() const {168switch (type) {169case IDENTIFIER:170return vformat(R"(identifier "%s")", source);171default:172return vformat(R"("%s")", get_name());173}174}175176bool GDScriptTokenizer::Token::can_precede_bin_op() const {177switch (type) {178case IDENTIFIER:179case LITERAL:180case SELF:181case BRACKET_CLOSE:182case BRACE_CLOSE:183case PARENTHESIS_CLOSE:184case CONST_PI:185case CONST_TAU:186case CONST_INF:187case CONST_NAN:188return true;189default:190return false;191}192}193194bool GDScriptTokenizer::Token::is_identifier() const {195// Note: Most keywords should not be recognized as identifiers.196// These are only exceptions for stuff that already is on the engine's API.197switch (type) {198case IDENTIFIER:199case MATCH: // Used in String.match().200case WHEN: // New keyword, avoid breaking existing code.201// Allow constants to be treated as regular identifiers.202case CONST_PI:203case CONST_INF:204case CONST_NAN:205case CONST_TAU:206return true;207default:208return false;209}210}211212bool GDScriptTokenizer::Token::is_node_name() const {213// This is meant to allow keywords with the $ notation, but not as general identifiers.214switch (type) {215case IDENTIFIER:216case AND:217case AS:218case ASSERT:219case AWAIT:220case BREAK:221case BREAKPOINT:222case CLASS_NAME:223case CLASS:224case TK_CONST:225case CONST_PI:226case CONST_INF:227case CONST_NAN:228case CONST_TAU:229case CONTINUE:230case ELIF:231case ELSE:232case ENUM:233case EXTENDS:234case FOR:235case FUNC:236case IF:237case TK_IN:238case IS:239case MATCH:240case NAMESPACE:241case NOT:242case OR:243case PASS:244case PRELOAD:245case RETURN:246case SELF:247case SIGNAL:248case STATIC:249case SUPER:250case TRAIT:251case UNDERSCORE:252case VAR:253case TK_VOID:254case WHILE:255case WHEN:256case YIELD:257return true;258default:259return false;260}261}262263String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {264ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");265return token_names[p_token_type];266}267268void GDScriptTokenizerText::set_source_code(const String &p_source_code) {269source = p_source_code;270_source = source.get_data();271_current = _source;272_start = _source;273line = 1;274column = 1;275length = p_source_code.length();276position = 0;277}278279void GDScriptTokenizerText::set_cursor_position(int p_line, int p_column) {280cursor_line = p_line;281cursor_column = p_column;282}283284void GDScriptTokenizerText::set_multiline_mode(bool p_state) {285multiline_mode = p_state;286}287288void GDScriptTokenizerText::push_expression_indented_block() {289indent_stack_stack.push_back(indent_stack);290}291292void GDScriptTokenizerText::pop_expression_indented_block() {293ERR_FAIL_COND(indent_stack_stack.is_empty());294indent_stack = indent_stack_stack.back()->get();295indent_stack_stack.pop_back();296}297298int GDScriptTokenizerText::get_cursor_line() const {299return cursor_line;300}301302int GDScriptTokenizerText::get_cursor_column() const {303return cursor_column;304}305306bool GDScriptTokenizerText::is_past_cursor() const {307if (line < cursor_line) {308return false;309}310if (line > cursor_line) {311return true;312}313if (column < cursor_column) {314return false;315}316return true;317}318319char32_t GDScriptTokenizerText::_advance() {320if (unlikely(_is_at_end())) {321return '\0';322}323_current++;324column++;325position++;326if (unlikely(_is_at_end())) {327// Add extra newline even if it's not there, to satisfy the parser.328newline(true);329// Also add needed unindent.330check_indent();331}332return _peek(-1);333}334335void GDScriptTokenizerText::push_paren(char32_t p_char) {336paren_stack.push_back(p_char);337}338339bool GDScriptTokenizerText::pop_paren(char32_t p_expected) {340if (paren_stack.is_empty()) {341return false;342}343char32_t actual = paren_stack.back()->get();344paren_stack.pop_back();345346return actual == p_expected;347}348349GDScriptTokenizer::Token GDScriptTokenizerText::pop_error() {350Token error = error_stack.back()->get();351error_stack.pop_back();352return error;353}354355GDScriptTokenizer::Token GDScriptTokenizerText::make_token(Token::Type p_type) {356Token token(p_type);357token.start_line = start_line;358token.end_line = line;359token.start_column = start_column;360token.end_column = column;361token.source = String::utf32(Span(_start, _current - _start));362363if (p_type != Token::ERROR && cursor_line > -1) {364// Also count whitespace after token.365int offset = 0;366while (_peek(offset) == ' ' || _peek(offset) == '\t') {367offset++;368}369int last_column = column + offset;370// Check cursor position in token.371if (start_line == line) {372// Single line token.373if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {374token.cursor_position = cursor_column - start_column;375if (cursor_column == start_column) {376token.cursor_place = CURSOR_BEGINNING;377} else if (cursor_column < column) {378token.cursor_place = CURSOR_MIDDLE;379} else {380token.cursor_place = CURSOR_END;381}382}383} else {384// Multi line token.385if (cursor_line == start_line && cursor_column >= start_column) {386// Is in first line.387token.cursor_position = cursor_column - start_column;388if (cursor_column == start_column) {389token.cursor_place = CURSOR_BEGINNING;390} else {391token.cursor_place = CURSOR_MIDDLE;392}393} else if (cursor_line == line && cursor_column <= last_column) {394// Is in last line.395token.cursor_position = cursor_column - start_column;396if (cursor_column < column) {397token.cursor_place = CURSOR_MIDDLE;398} else {399token.cursor_place = CURSOR_END;400}401} else if (cursor_line > start_line && cursor_line < line) {402// Is in middle line.403token.cursor_position = CURSOR_MIDDLE;404}405}406}407408last_token = token;409return token;410}411412GDScriptTokenizer::Token GDScriptTokenizerText::make_literal(const Variant &p_literal) {413Token token = make_token(Token::LITERAL);414token.literal = p_literal;415return token;416}417418GDScriptTokenizer::Token GDScriptTokenizerText::make_identifier(const StringName &p_identifier) {419Token identifier = make_token(Token::IDENTIFIER);420identifier.literal = p_identifier;421return identifier;422}423424GDScriptTokenizer::Token GDScriptTokenizerText::make_error(const String &p_message) {425Token error = make_token(Token::ERROR);426error.literal = p_message;427428return error;429}430431void GDScriptTokenizerText::push_error(const String &p_message) {432Token error = make_error(p_message);433error_stack.push_back(error);434}435436void GDScriptTokenizerText::push_error(const Token &p_error) {437error_stack.push_back(p_error);438}439440GDScriptTokenizer::Token GDScriptTokenizerText::make_paren_error(char32_t p_paren) {441if (paren_stack.is_empty()) {442return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));443}444Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));445paren_stack.pop_back(); // Remove opening one anyway.446return error;447}448449GDScriptTokenizer::Token GDScriptTokenizerText::check_vcs_marker(char32_t p_test, Token::Type p_double_type) {450const char32_t *next = _current + 1;451int chars = 2; // Two already matched.452453// Test before consuming characters, since we don't want to consume more than needed.454while (*next == p_test) {455chars++;456next++;457}458if (chars >= 7) {459// It is a VCS conflict marker.460while (chars > 1) {461// Consume all characters (first was already consumed by scan()).462_advance();463chars--;464}465return make_token(Token::VCS_CONFLICT_MARKER);466} else {467// It is only a regular double character token, so we consume the second character.468_advance();469return make_token(p_double_type);470}471}472473GDScriptTokenizer::Token GDScriptTokenizerText::annotation() {474if (is_unicode_identifier_start(_peek())) {475_advance(); // Consume start character.476} else {477push_error("Expected annotation identifier after \"@\".");478}479while (is_unicode_identifier_continue(_peek())) {480// Consume all identifier characters.481_advance();482}483Token annotation = make_token(Token::ANNOTATION);484annotation.literal = StringName(annotation.source);485return annotation;486}487488#define KEYWORDS(KEYWORD_GROUP, KEYWORD) \489KEYWORD_GROUP('a') \490KEYWORD("as", Token::AS) \491KEYWORD("and", Token::AND) \492KEYWORD("assert", Token::ASSERT) \493KEYWORD("await", Token::AWAIT) \494KEYWORD_GROUP('b') \495KEYWORD("break", Token::BREAK) \496KEYWORD("breakpoint", Token::BREAKPOINT) \497KEYWORD_GROUP('c') \498KEYWORD("class", Token::CLASS) \499KEYWORD("class_name", Token::CLASS_NAME) \500KEYWORD("const", Token::TK_CONST) \501KEYWORD("continue", Token::CONTINUE) \502KEYWORD_GROUP('e') \503KEYWORD("elif", Token::ELIF) \504KEYWORD("else", Token::ELSE) \505KEYWORD("enum", Token::ENUM) \506KEYWORD("extends", Token::EXTENDS) \507KEYWORD_GROUP('f') \508KEYWORD("for", Token::FOR) \509KEYWORD("func", Token::FUNC) \510KEYWORD_GROUP('i') \511KEYWORD("if", Token::IF) \512KEYWORD("in", Token::TK_IN) \513KEYWORD("is", Token::IS) \514KEYWORD_GROUP('m') \515KEYWORD("match", Token::MATCH) \516KEYWORD_GROUP('n') \517KEYWORD("namespace", Token::NAMESPACE) \518KEYWORD("not", Token::NOT) \519KEYWORD_GROUP('o') \520KEYWORD("or", Token::OR) \521KEYWORD_GROUP('p') \522KEYWORD("pass", Token::PASS) \523KEYWORD("preload", Token::PRELOAD) \524KEYWORD_GROUP('r') \525KEYWORD("return", Token::RETURN) \526KEYWORD_GROUP('s') \527KEYWORD("self", Token::SELF) \528KEYWORD("signal", Token::SIGNAL) \529KEYWORD("static", Token::STATIC) \530KEYWORD("super", Token::SUPER) \531KEYWORD_GROUP('t') \532KEYWORD("trait", Token::TRAIT) \533KEYWORD_GROUP('v') \534KEYWORD("var", Token::VAR) \535KEYWORD("void", Token::TK_VOID) \536KEYWORD_GROUP('w') \537KEYWORD("while", Token::WHILE) \538KEYWORD("when", Token::WHEN) \539KEYWORD_GROUP('y') \540KEYWORD("yield", Token::YIELD) \541KEYWORD_GROUP('I') \542KEYWORD("INF", Token::CONST_INF) \543KEYWORD_GROUP('N') \544KEYWORD("NAN", Token::CONST_NAN) \545KEYWORD_GROUP('P') \546KEYWORD("PI", Token::CONST_PI) \547KEYWORD_GROUP('T') \548KEYWORD("TAU", Token::CONST_TAU)549550#define MIN_KEYWORD_LENGTH 2551#define MAX_KEYWORD_LENGTH 10552553#ifdef DEBUG_ENABLED554void GDScriptTokenizerText::make_keyword_list() {555#define KEYWORD_LINE(keyword, token_type) keyword,556#define KEYWORD_GROUP_IGNORE(group)557keyword_list = {558KEYWORDS(KEYWORD_GROUP_IGNORE, KEYWORD_LINE)559};560#undef KEYWORD_LINE561#undef KEYWORD_GROUP_IGNORE562}563#endif // DEBUG_ENABLED564565GDScriptTokenizer::Token GDScriptTokenizerText::potential_identifier() {566bool only_ascii = _peek(-1) < 128;567568// Consume all identifier characters.569while (is_unicode_identifier_continue(_peek())) {570char32_t c = _advance();571only_ascii = only_ascii && c < 128;572}573574int len = _current - _start;575576if (len == 1 && _peek(-1) == '_') {577// Lone underscore.578Token token = make_token(Token::UNDERSCORE);579token.literal = "_";580return token;581}582583String name = String::utf32(Span(_start, len));584if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) {585// Cannot be a keyword, as the length doesn't match any.586return make_identifier(name);587}588589if (!only_ascii) {590// Kept here in case the order with push_error matters.591Token id = make_identifier(name);592593#ifdef DEBUG_ENABLED594// Additional checks for identifiers but only in debug and if it's available in TextServer.595if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY)) {596int64_t confusable = TS->is_confusable(name, keyword_list);597if (confusable >= 0) {598push_error(vformat(R"(Identifier "%s" is visually similar to the GDScript keyword "%s" and thus not allowed.)", name, keyword_list[confusable]));599}600}601#endif // DEBUG_ENABLED602603// Cannot be a keyword, as keywords are ASCII only.604return id;605}606607// Define some helper macros for the switch case.608#define KEYWORD_GROUP_CASE(char) \609break; \610case char:611#define KEYWORD(keyword, token_type) \612{ \613const int keyword_length = sizeof(keyword) - 1; \614static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \615static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \616if (keyword_length == len && name == keyword) { \617Token kw = make_token(token_type); \618kw.literal = name; \619return kw; \620} \621}622623// Find if it's a keyword.624switch (_start[0]) {625default:626KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)627break;628}629630// Check if it's a special literal631if (len == 4) {632if (name == "true") {633return make_literal(true);634} else if (name == "null") {635return make_literal(Variant());636}637} else if (len == 5) {638if (name == "false") {639return make_literal(false);640}641}642643// Not a keyword, so must be an identifier.644return make_identifier(name);645646#undef KEYWORD_GROUP_CASE647#undef KEYWORD648}649650#undef MAX_KEYWORD_LENGTH651#undef MIN_KEYWORD_LENGTH652#undef KEYWORDS653654void GDScriptTokenizerText::newline(bool p_make_token) {655// Don't overwrite previous newline, nor create if we want a line continuation.656if (p_make_token && !pending_newline && !line_continuation) {657Token newline(Token::NEWLINE);658newline.start_line = line;659newline.end_line = line;660newline.start_column = column - 1;661newline.end_column = column;662pending_newline = true;663last_token = newline;664last_newline = newline;665}666667// Increment line/column counters.668line++;669column = 1;670}671672GDScriptTokenizer::Token GDScriptTokenizerText::number() {673int base = 10;674bool has_decimal = false;675bool has_exponent = false;676bool has_error = false;677bool need_digits = false;678bool (*digit_check_func)(char32_t) = is_digit;679680// Sign before hexadecimal or binary.681if ((_peek(-1) == '+' || _peek(-1) == '-') && _peek() == '0') {682_advance();683}684685if (_peek(-1) == '.') {686has_decimal = true;687} else if (_peek(-1) == '0') {688if (_peek() == 'x' || _peek() == 'X') {689// Hexadecimal.690base = 16;691digit_check_func = is_hex_digit;692need_digits = true;693_advance();694} else if (_peek() == 'b' || _peek() == 'B') {695// Binary.696base = 2;697digit_check_func = is_binary_digit;698need_digits = true;699_advance();700}701}702703if (base != 10 && is_underscore(_peek())) { // Disallow `0x_` and `0b_`.704Token error = make_error(vformat(R"(Unexpected underscore after "0%c".)", _peek(-1)));705error.start_column = column;706error.end_column = column + 1;707push_error(error);708has_error = true;709}710bool previous_was_underscore = false; // Allow `_` to be used in a number, for readability.711while (digit_check_func(_peek()) || is_underscore(_peek())) {712if (is_underscore(_peek())) {713if (previous_was_underscore) {714Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");715error.start_column = column;716error.end_column = column + 1;717push_error(error);718}719previous_was_underscore = true;720} else {721need_digits = false;722previous_was_underscore = false;723}724_advance();725}726727// It might be a ".." token (instead of decimal point) so we check if it's not.728if (_peek() == '.' && _peek(1) != '.') {729if (base == 10 && !has_decimal) {730has_decimal = true;731} else if (base == 10) {732Token error = make_error("Cannot use a decimal point twice in a number.");733error.start_column = column;734error.end_column = column + 1;735push_error(error);736has_error = true;737} else if (base == 16) {738Token error = make_error("Cannot use a decimal point in a hexadecimal number.");739error.start_column = column;740error.end_column = column + 1;741push_error(error);742has_error = true;743} else {744Token error = make_error("Cannot use a decimal point in a binary number.");745error.start_column = column;746error.end_column = column + 1;747push_error(error);748has_error = true;749}750if (!has_error) {751_advance();752753// Consume decimal digits.754if (is_underscore(_peek())) { // Disallow `10._`, but allow `10.`.755Token error = make_error(R"(Unexpected underscore after decimal point.)");756error.start_column = column;757error.end_column = column + 1;758push_error(error);759has_error = true;760}761previous_was_underscore = false;762while (is_digit(_peek()) || is_underscore(_peek())) {763if (is_underscore(_peek())) {764if (previous_was_underscore) {765Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");766error.start_column = column;767error.end_column = column + 1;768push_error(error);769}770previous_was_underscore = true;771} else {772previous_was_underscore = false;773}774_advance();775}776}777}778if (base == 10) {779if (_peek() == 'e' || _peek() == 'E') {780has_exponent = true;781_advance();782if (_peek() == '+' || _peek() == '-') {783// Exponent sign.784_advance();785}786// Consume exponent digits.787if (!is_digit(_peek())) {788Token error = make_error(R"(Expected exponent value after "e".)");789error.start_column = column;790error.end_column = column + 1;791push_error(error);792}793previous_was_underscore = false;794while (is_digit(_peek()) || is_underscore(_peek())) {795if (is_underscore(_peek())) {796if (previous_was_underscore) {797Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");798error.start_column = column;799error.end_column = column + 1;800push_error(error);801}802previous_was_underscore = true;803} else {804previous_was_underscore = false;805}806_advance();807}808}809}810811if (need_digits) {812// No digits in hex or bin literal.813Token error = make_error(vformat(R"(Expected %s digit after "0%c".)", (base == 16 ? "hexadecimal" : "binary"), (base == 16 ? 'x' : 'b')));814error.start_column = column;815error.end_column = column + 1;816return error;817}818819// Detect extra decimal point.820if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {821Token error = make_error("Cannot use a decimal point twice in a number.");822error.start_column = column;823error.end_column = column + 1;824push_error(error);825has_error = true;826} else if (is_unicode_identifier_start(_peek()) || is_unicode_identifier_continue(_peek())) {827// Letter at the end of the number.828push_error("Invalid numeric notation.");829}830831// Create a string with the whole number.832int len = _current - _start;833String number = String::utf32(Span(_start, len)).remove_char('_');834835// Convert to the appropriate literal type.836if (base == 16) {837int64_t value = number.hex_to_int();838return make_literal(value);839} else if (base == 2) {840int64_t value = number.bin_to_int();841return make_literal(value);842} else if (has_decimal || has_exponent) {843double value = number.to_float();844return make_literal(value);845} else {846int64_t value = number.to_int();847return make_literal(value);848}849}850851GDScriptTokenizer::Token GDScriptTokenizerText::string() {852enum StringType {853STRING_REGULAR,854STRING_NAME,855STRING_NODEPATH,856};857858bool is_raw = false;859bool is_multiline = false;860StringType type = STRING_REGULAR;861862if (_peek(-1) == 'r') {863is_raw = true;864_advance();865} else if (_peek(-1) == '&') {866type = STRING_NAME;867_advance();868} else if (_peek(-1) == '^') {869type = STRING_NODEPATH;870_advance();871}872873char32_t quote_char = _peek(-1);874875if (_peek() == quote_char && _peek(1) == quote_char) {876is_multiline = true;877// Consume all quotes.878_advance();879_advance();880}881882String result;883char32_t prev = 0;884int prev_pos = 0;885886for (;;) {887// Consume actual string.888if (_is_at_end()) {889return make_error("Unterminated string.");890}891892char32_t ch = _peek();893894if (ch == 0x200E || ch == 0x200F || (ch >= 0x202A && ch <= 0x202E) || (ch >= 0x2066 && ch <= 0x2069)) {895Token error;896if (is_raw) {897error = make_error("Invisible text direction control character present in the string, use regular string literal instead of r-string.");898} else {899error = make_error("Invisible text direction control character present in the string, escape it (\"\\u" + String::num_int64(ch, 16) + "\") to avoid confusion.");900}901error.start_column = column;902error.end_column = column + 1;903push_error(error);904}905906if (ch == '\\') {907// Escape pattern.908_advance();909if (_is_at_end()) {910return make_error("Unterminated string.");911}912913if (is_raw) {914if (_peek() == quote_char) {915_advance();916if (_is_at_end()) {917return make_error("Unterminated string.");918}919result += '\\';920result += quote_char;921} else if (_peek() == '\\') { // For `\\\"`.922_advance();923if (_is_at_end()) {924return make_error("Unterminated string.");925}926result += '\\';927result += '\\';928} else {929result += '\\';930}931} else {932// Grab escape character.933char32_t code = _peek();934_advance();935if (_is_at_end()) {936return make_error("Unterminated string.");937}938939char32_t escaped = 0;940bool valid_escape = true;941942switch (code) {943case 'a':944escaped = '\a';945break;946case 'b':947escaped = '\b';948break;949case 'f':950escaped = '\f';951break;952case 'n':953escaped = '\n';954break;955case 'r':956escaped = '\r';957break;958case 't':959escaped = '\t';960break;961case 'v':962escaped = '\v';963break;964case '\'':965escaped = '\'';966break;967case '\"':968escaped = '\"';969break;970case '\\':971escaped = '\\';972break;973case 'U':974case 'u': {975// Hexadecimal sequence.976int hex_len = (code == 'U') ? 6 : 4;977for (int j = 0; j < hex_len; j++) {978if (_is_at_end()) {979return make_error("Unterminated string.");980}981982char32_t digit = _peek();983char32_t value = 0;984if (is_digit(digit)) {985value = digit - '0';986} else if (digit >= 'a' && digit <= 'f') {987value = digit - 'a';988value += 10;989} else if (digit >= 'A' && digit <= 'F') {990value = digit - 'A';991value += 10;992} else {993// Make error, but keep parsing the string.994Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");995error.start_column = column;996error.end_column = column + 1;997push_error(error);998valid_escape = false;999break;1000}10011002escaped <<= 4;1003escaped |= value;10041005_advance();1006}1007} break;1008case '\r':1009if (_peek() != '\n') {1010// Carriage return without newline in string. (???)1011// Just add it to the string and keep going.1012result += ch;1013_advance();1014break;1015}1016[[fallthrough]];1017case '\n':1018// Escaping newline.1019newline(false);1020valid_escape = false; // Don't add to the string.1021break;1022default:1023Token error = make_error("Invalid escape in string.");1024error.start_column = column - 2;1025push_error(error);1026valid_escape = false;1027break;1028}1029// Parse UTF-16 pair.1030if (valid_escape) {1031if ((escaped & 0xfffffc00) == 0xd800) {1032if (prev == 0) {1033prev = escaped;1034prev_pos = column - 2;1035continue;1036} else {1037Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");1038error.start_column = column - 2;1039push_error(error);1040valid_escape = false;1041prev = 0;1042}1043} else if ((escaped & 0xfffffc00) == 0xdc00) {1044if (prev == 0) {1045Token error = make_error("Invalid UTF-16 sequence in string, unpaired trail surrogate.");1046error.start_column = column - 2;1047push_error(error);1048valid_escape = false;1049} else {1050escaped = (prev << 10UL) + escaped - ((0xd800 << 10UL) + 0xdc00 - 0x10000);1051prev = 0;1052}1053}1054if (prev != 0) {1055Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");1056error.start_column = prev_pos;1057push_error(error);1058prev = 0;1059}1060}10611062if (valid_escape) {1063result += escaped;1064}1065}1066} else if (ch == quote_char) {1067if (prev != 0) {1068Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1069error.start_column = prev_pos;1070push_error(error);1071prev = 0;1072}1073_advance();1074if (is_multiline) {1075if (_peek() == quote_char && _peek(1) == quote_char) {1076// Ended the multiline string. Consume all quotes.1077_advance();1078_advance();1079break;1080} else {1081// Not a multiline string termination, add consumed quote.1082result += quote_char;1083}1084} else {1085// Ended single-line string.1086break;1087}1088} else {1089if (prev != 0) {1090Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1091error.start_column = prev_pos;1092push_error(error);1093prev = 0;1094}1095result += ch;1096_advance();1097if (ch == '\n') {1098newline(false);1099}1100}1101}1102if (prev != 0) {1103Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1104error.start_column = prev_pos;1105push_error(error);1106prev = 0;1107}11081109// Make the literal.1110Variant string;1111switch (type) {1112case STRING_NAME:1113string = StringName(result);1114break;1115case STRING_NODEPATH:1116string = NodePath(result);1117break;1118case STRING_REGULAR:1119string = result;1120break;1121}11221123return make_literal(string);1124}11251126void GDScriptTokenizerText::check_indent() {1127ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");11281129if (_is_at_end()) {1130// Send dedents for every indent level.1131pending_indents -= indent_level();1132indent_stack.clear();1133return;1134}11351136for (;;) {1137char32_t current_indent_char = _peek();1138int indent_count = 0;11391140if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {1141// First character of the line is not whitespace, so we clear all indentation levels.1142// Unless we are in a continuation or in multiline mode (inside expression).1143if (line_continuation || multiline_mode) {1144return;1145}1146pending_indents -= indent_level();1147indent_stack.clear();1148return;1149}11501151if (_peek() == '\r') {1152_advance();1153if (_peek() != '\n') {1154push_error("Stray carriage return character in source code.");1155}1156}1157if (_peek() == '\n') {1158// Empty line, keep going.1159_advance();1160newline(false);1161continue;1162}11631164// Check indent level.1165bool mixed = false;1166while (!_is_at_end()) {1167char32_t space = _peek();1168if (space == '\t') {1169// Consider individual tab columns.1170column += tab_size - 1;1171indent_count += tab_size;1172} else if (space == ' ') {1173indent_count += 1;1174} else {1175break;1176}1177mixed = mixed || space != current_indent_char;1178_advance();1179}11801181if (_is_at_end()) {1182// Reached the end with an empty line, so just dedent as much as needed.1183pending_indents -= indent_level();1184indent_stack.clear();1185return;1186}11871188if (_peek() == '\r') {1189_advance();1190if (_peek() != '\n') {1191push_error("Stray carriage return character in source code.");1192}1193}1194if (_peek() == '\n') {1195// Empty line, keep going.1196_advance();1197newline(false);1198continue;1199}1200if (_peek() == '#') {1201// Comment. Advance to the next line.1202#ifdef TOOLS_ENABLED1203String comment;1204while (_peek() != '\n' && !_is_at_end()) {1205comment += _advance();1206}1207comments[line] = CommentData(comment, true);1208#else1209while (_peek() != '\n' && !_is_at_end()) {1210_advance();1211}1212#endif // TOOLS_ENABLED1213if (_is_at_end()) {1214// Reached the end with an empty line, so just dedent as much as needed.1215pending_indents -= indent_level();1216indent_stack.clear();1217return;1218}1219_advance(); // Consume '\n'.1220newline(false);1221continue;1222}12231224if (mixed && !line_continuation && !multiline_mode) {1225Token error = make_error("Mixed use of tabs and spaces for indentation.");1226error.start_line = line;1227error.start_column = 1;1228push_error(error);1229}12301231if (line_continuation || multiline_mode) {1232// We cleared up all the whitespace at the beginning of the line.1233// If this is a line continuation or we're in multiline mode then we don't want any indentation changes.1234return;1235}12361237// Check if indentation character is consistent.1238if (indent_char == '\0') {1239// First time indenting, choose character now.1240indent_char = current_indent_char;1241} else if (current_indent_char != indent_char) {1242Token error = make_error(vformat("Used %s character for indentation instead of %s as used before in the file.",1243_get_indent_char_name(current_indent_char), _get_indent_char_name(indent_char)));1244error.start_line = line;1245error.start_column = 1;1246push_error(error);1247}12481249// Now we can do actual indentation changes.12501251// Check if indent or dedent.1252int previous_indent = 0;1253if (indent_level() > 0) {1254previous_indent = indent_stack.back()->get();1255}1256if (indent_count == previous_indent) {1257// No change in indentation.1258return;1259}1260if (indent_count > previous_indent) {1261// Indentation increased.1262indent_stack.push_back(indent_count);1263pending_indents++;1264} else {1265// Indentation decreased (dedent).1266if (indent_level() == 0) {1267push_error("Tokenizer bug: trying to dedent without previous indent.");1268return;1269}1270while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {1271indent_stack.pop_back();1272pending_indents--;1273}1274if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {1275// Mismatched indentation alignment.1276Token error = make_error("Unindent doesn't match the previous indentation level.");1277error.start_line = line;1278error.start_column = 1;1279error.end_column = column + 1;1280push_error(error);1281// Still, we'll be lenient and keep going, so keep this level in the stack.1282indent_stack.push_back(indent_count);1283}1284}1285break; // Get out of the loop in any case.1286}1287}12881289String GDScriptTokenizerText::_get_indent_char_name(char32_t ch) {1290ERR_FAIL_COND_V(ch != ' ' && ch != '\t', String::chr(ch).c_escape());12911292return ch == ' ' ? "space" : "tab";1293}12941295void GDScriptTokenizerText::_skip_whitespace() {1296if (pending_indents != 0) {1297// Still have some indent/dedent tokens to give.1298return;1299}13001301bool is_bol = column == 1; // Beginning of line.13021303if (is_bol) {1304check_indent();1305return;1306}13071308for (;;) {1309char32_t c = _peek();1310switch (c) {1311case ' ':1312_advance();1313break;1314case '\t':1315_advance();1316// Consider individual tab columns.1317column += tab_size - 1;1318break;1319case '\r':1320_advance(); // Consume either way.1321if (_peek() != '\n') {1322push_error("Stray carriage return character in source code.");1323return;1324}1325break;1326case '\n':1327_advance();1328newline(!is_bol); // Don't create new line token if line is empty.1329check_indent();1330break;1331case '#': {1332// Comment.1333#ifdef TOOLS_ENABLED1334String comment;1335while (_peek() != '\n' && !_is_at_end()) {1336comment += _advance();1337}1338comments[line] = CommentData(comment, is_bol);1339#else1340while (_peek() != '\n' && !_is_at_end()) {1341_advance();1342}1343#endif // TOOLS_ENABLED1344if (_is_at_end()) {1345return;1346}1347_advance(); // Consume '\n'1348newline(!is_bol);1349check_indent();1350} break;1351default:1352return;1353}1354}1355}13561357GDScriptTokenizer::Token GDScriptTokenizerText::scan() {1358if (has_error()) {1359return pop_error();1360}13611362_skip_whitespace();13631364if (pending_newline) {1365pending_newline = false;1366if (!multiline_mode) {1367// Don't return newline tokens on multiline mode.1368return last_newline;1369}1370}13711372// Check for potential errors after skipping whitespace().1373if (has_error()) {1374return pop_error();1375}13761377_start = _current;1378start_line = line;1379start_column = column;13801381if (pending_indents != 0) {1382// Adjust position for indent.1383_start -= start_column - 1;1384start_column = 1;1385if (pending_indents > 0) {1386// Indents.1387pending_indents--;1388return make_token(Token::INDENT);1389} else {1390// Dedents.1391pending_indents++;1392Token dedent = make_token(Token::DEDENT);1393dedent.end_column += 1;1394return dedent;1395}1396}13971398if (_is_at_end()) {1399return make_token(Token::TK_EOF);1400}14011402const char32_t c = _advance();14031404if (c == '\\') {1405// Line continuation with backslash.1406if (_peek() == '\r') {1407if (_peek(1) != '\n') {1408return make_error("Unexpected carriage return character.");1409}1410_advance();1411}1412if (_peek() != '\n') {1413return make_error("Expected new line after \"\\\".");1414}1415_advance();1416newline(false);1417line_continuation = true;1418_skip_whitespace(); // Skip whitespace/comment lines after `\`. See GH-89403.1419continuation_lines.push_back(line);1420return scan(); // Recurse to get next token.1421}14221423line_continuation = false;14241425if (is_digit(c)) {1426return number();1427} else if (c == 'r' && (_peek() == '"' || _peek() == '\'')) {1428// Raw string literals.1429return string();1430} else if (is_unicode_identifier_start(c)) {1431return potential_identifier();1432}14331434switch (c) {1435// String literals.1436case '"':1437case '\'':1438return string();14391440// Annotation.1441case '@':1442return annotation();14431444// Single characters.1445case '~':1446return make_token(Token::TILDE);1447case ',':1448return make_token(Token::COMMA);1449case ':':1450return make_token(Token::COLON);1451case ';':1452return make_token(Token::SEMICOLON);1453case '$':1454return make_token(Token::DOLLAR);1455case '?':1456return make_token(Token::QUESTION_MARK);1457case '`':1458return make_token(Token::BACKTICK);14591460// Parens.1461case '(':1462push_paren('(');1463return make_token(Token::PARENTHESIS_OPEN);1464case '[':1465push_paren('[');1466return make_token(Token::BRACKET_OPEN);1467case '{':1468push_paren('{');1469return make_token(Token::BRACE_OPEN);1470case ')':1471if (!pop_paren('(')) {1472return make_paren_error(c);1473}1474return make_token(Token::PARENTHESIS_CLOSE);1475case ']':1476if (!pop_paren('[')) {1477return make_paren_error(c);1478}1479return make_token(Token::BRACKET_CLOSE);1480case '}':1481if (!pop_paren('{')) {1482return make_paren_error(c);1483}1484return make_token(Token::BRACE_CLOSE);14851486// Double characters.1487case '!':1488if (_peek() == '=') {1489_advance();1490return make_token(Token::BANG_EQUAL);1491} else {1492return make_token(Token::BANG);1493}1494case '.':1495if (_peek() == '.') {1496_advance();1497if (_peek() == '.') {1498_advance();1499return make_token(Token::PERIOD_PERIOD_PERIOD);1500}1501return make_token(Token::PERIOD_PERIOD);1502} else if (is_digit(_peek())) {1503// Number starting with '.'.1504return number();1505} else {1506return make_token(Token::PERIOD);1507}1508case '+':1509if (_peek() == '=') {1510_advance();1511return make_token(Token::PLUS_EQUAL);1512} else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {1513// Number starting with '+'.1514return number();1515} else {1516return make_token(Token::PLUS);1517}1518case '-':1519if (_peek() == '=') {1520_advance();1521return make_token(Token::MINUS_EQUAL);1522} else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {1523// Number starting with '-'.1524return number();1525} else if (_peek() == '>') {1526_advance();1527return make_token(Token::FORWARD_ARROW);1528} else {1529return make_token(Token::MINUS);1530}1531case '*':1532if (_peek() == '=') {1533_advance();1534return make_token(Token::STAR_EQUAL);1535} else if (_peek() == '*') {1536if (_peek(1) == '=') {1537_advance();1538_advance(); // Advance both '*' and '='1539return make_token(Token::STAR_STAR_EQUAL);1540}1541_advance();1542return make_token(Token::STAR_STAR);1543} else {1544return make_token(Token::STAR);1545}1546case '/':1547if (_peek() == '=') {1548_advance();1549return make_token(Token::SLASH_EQUAL);1550} else {1551return make_token(Token::SLASH);1552}1553case '%':1554if (_peek() == '=') {1555_advance();1556return make_token(Token::PERCENT_EQUAL);1557} else {1558return make_token(Token::PERCENT);1559}1560case '^':1561if (_peek() == '=') {1562_advance();1563return make_token(Token::CARET_EQUAL);1564} else if (_peek() == '"' || _peek() == '\'') {1565// Node path1566return string();1567} else {1568return make_token(Token::CARET);1569}1570case '&':1571if (_peek() == '&') {1572_advance();1573return make_token(Token::AMPERSAND_AMPERSAND);1574} else if (_peek() == '=') {1575_advance();1576return make_token(Token::AMPERSAND_EQUAL);1577} else if (_peek() == '"' || _peek() == '\'') {1578// String Name1579return string();1580} else {1581return make_token(Token::AMPERSAND);1582}1583case '|':1584if (_peek() == '|') {1585_advance();1586return make_token(Token::PIPE_PIPE);1587} else if (_peek() == '=') {1588_advance();1589return make_token(Token::PIPE_EQUAL);1590} else {1591return make_token(Token::PIPE);1592}15931594// Potential VCS conflict markers.1595case '=':1596if (_peek() == '=') {1597return check_vcs_marker('=', Token::EQUAL_EQUAL);1598} else {1599return make_token(Token::EQUAL);1600}1601case '<':1602if (_peek() == '=') {1603_advance();1604return make_token(Token::LESS_EQUAL);1605} else if (_peek() == '<') {1606if (_peek(1) == '=') {1607_advance();1608_advance(); // Advance both '<' and '='1609return make_token(Token::LESS_LESS_EQUAL);1610} else {1611return check_vcs_marker('<', Token::LESS_LESS);1612}1613} else {1614return make_token(Token::LESS);1615}1616case '>':1617if (_peek() == '=') {1618_advance();1619return make_token(Token::GREATER_EQUAL);1620} else if (_peek() == '>') {1621if (_peek(1) == '=') {1622_advance();1623_advance(); // Advance both '>' and '='1624return make_token(Token::GREATER_GREATER_EQUAL);1625} else {1626return check_vcs_marker('>', Token::GREATER_GREATER);1627}1628} else {1629return make_token(Token::GREATER);1630}16311632default:1633if (is_whitespace(c)) {1634return make_error(vformat(R"(Invalid white space character U+%04X.)", static_cast<int32_t>(c)));1635} else {1636return make_error(vformat(R"(Invalid character "%c" (U+%04X).)", c, static_cast<int32_t>(c)));1637}1638}1639}16401641GDScriptTokenizerText::GDScriptTokenizerText() {1642#ifdef TOOLS_ENABLED1643if (EditorSettings::get_singleton()) {1644tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");1645}1646#endif // TOOLS_ENABLED1647#ifdef DEBUG_ENABLED1648make_keyword_list();1649#endif // DEBUG_ENABLED1650}165116521653