Path: blob/master/modules/gdscript/gdscript_tokenizer.cpp
20831 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/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) {374if (cursor_column == start_column) {375token.cursor_place = CURSOR_BEGINNING;376} else if (cursor_column < column) {377token.cursor_place = CURSOR_MIDDLE;378} else {379token.cursor_place = CURSOR_END;380}381}382} else {383// Multi line token.384if (cursor_line == start_line && cursor_column >= start_column) {385// Is in first line.386if (cursor_column == start_column) {387token.cursor_place = CURSOR_BEGINNING;388} else {389token.cursor_place = CURSOR_MIDDLE;390}391} else if (cursor_line == line && cursor_column <= last_column) {392// Is in last line.393if (cursor_column < column) {394token.cursor_place = CURSOR_MIDDLE;395} else {396token.cursor_place = CURSOR_END;397}398} else if (cursor_line > start_line && cursor_line < line) {399// Is in middle line.400token.cursor_place = CURSOR_MIDDLE;401}402}403}404405last_token = token;406return token;407}408409GDScriptTokenizer::Token GDScriptTokenizerText::make_literal(const Variant &p_literal) {410Token token = make_token(Token::LITERAL);411token.literal = p_literal;412return token;413}414415GDScriptTokenizer::Token GDScriptTokenizerText::make_identifier(const StringName &p_identifier) {416Token identifier = make_token(Token::IDENTIFIER);417identifier.literal = p_identifier;418return identifier;419}420421GDScriptTokenizer::Token GDScriptTokenizerText::make_error(const String &p_message) {422Token error = make_token(Token::ERROR);423error.literal = p_message;424425return error;426}427428void GDScriptTokenizerText::push_error(const String &p_message) {429Token error = make_error(p_message);430error_stack.push_back(error);431}432433void GDScriptTokenizerText::push_error(const Token &p_error) {434error_stack.push_back(p_error);435}436437GDScriptTokenizer::Token GDScriptTokenizerText::make_paren_error(char32_t p_paren) {438if (paren_stack.is_empty()) {439return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));440}441Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));442paren_stack.pop_back(); // Remove opening one anyway.443return error;444}445446GDScriptTokenizer::Token GDScriptTokenizerText::check_vcs_marker(char32_t p_test, Token::Type p_double_type) {447const char32_t *next = _current + 1;448int chars = 2; // Two already matched.449450// Test before consuming characters, since we don't want to consume more than needed.451while (*next == p_test) {452chars++;453next++;454}455if (chars >= 7) {456// It is a VCS conflict marker.457while (chars > 1) {458// Consume all characters (first was already consumed by scan()).459_advance();460chars--;461}462return make_token(Token::VCS_CONFLICT_MARKER);463} else {464// It is only a regular double character token, so we consume the second character.465_advance();466return make_token(p_double_type);467}468}469470GDScriptTokenizer::Token GDScriptTokenizerText::annotation() {471if (is_unicode_identifier_start(_peek())) {472_advance(); // Consume start character.473} else {474push_error("Expected annotation identifier after \"@\".");475}476while (is_unicode_identifier_continue(_peek())) {477// Consume all identifier characters.478_advance();479}480Token annotation = make_token(Token::ANNOTATION);481annotation.literal = StringName(annotation.source);482return annotation;483}484485#define KEYWORDS(KEYWORD_GROUP, KEYWORD) \486KEYWORD_GROUP('a') \487KEYWORD("as", Token::AS) \488KEYWORD("and", Token::AND) \489KEYWORD("assert", Token::ASSERT) \490KEYWORD("await", Token::AWAIT) \491KEYWORD_GROUP('b') \492KEYWORD("break", Token::BREAK) \493KEYWORD("breakpoint", Token::BREAKPOINT) \494KEYWORD_GROUP('c') \495KEYWORD("class", Token::CLASS) \496KEYWORD("class_name", Token::CLASS_NAME) \497KEYWORD("const", Token::TK_CONST) \498KEYWORD("continue", Token::CONTINUE) \499KEYWORD_GROUP('e') \500KEYWORD("elif", Token::ELIF) \501KEYWORD("else", Token::ELSE) \502KEYWORD("enum", Token::ENUM) \503KEYWORD("extends", Token::EXTENDS) \504KEYWORD_GROUP('f') \505KEYWORD("for", Token::FOR) \506KEYWORD("func", Token::FUNC) \507KEYWORD_GROUP('i') \508KEYWORD("if", Token::IF) \509KEYWORD("in", Token::TK_IN) \510KEYWORD("is", Token::IS) \511KEYWORD_GROUP('m') \512KEYWORD("match", Token::MATCH) \513KEYWORD_GROUP('n') \514KEYWORD("namespace", Token::NAMESPACE) \515KEYWORD("not", Token::NOT) \516KEYWORD_GROUP('o') \517KEYWORD("or", Token::OR) \518KEYWORD_GROUP('p') \519KEYWORD("pass", Token::PASS) \520KEYWORD("preload", Token::PRELOAD) \521KEYWORD_GROUP('r') \522KEYWORD("return", Token::RETURN) \523KEYWORD_GROUP('s') \524KEYWORD("self", Token::SELF) \525KEYWORD("signal", Token::SIGNAL) \526KEYWORD("static", Token::STATIC) \527KEYWORD("super", Token::SUPER) \528KEYWORD_GROUP('t') \529KEYWORD("trait", Token::TRAIT) \530KEYWORD_GROUP('v') \531KEYWORD("var", Token::VAR) \532KEYWORD("void", Token::TK_VOID) \533KEYWORD_GROUP('w') \534KEYWORD("while", Token::WHILE) \535KEYWORD("when", Token::WHEN) \536KEYWORD_GROUP('y') \537KEYWORD("yield", Token::YIELD) \538KEYWORD_GROUP('I') \539KEYWORD("INF", Token::CONST_INF) \540KEYWORD_GROUP('N') \541KEYWORD("NAN", Token::CONST_NAN) \542KEYWORD_GROUP('P') \543KEYWORD("PI", Token::CONST_PI) \544KEYWORD_GROUP('T') \545KEYWORD("TAU", Token::CONST_TAU)546547#define MIN_KEYWORD_LENGTH 2548#define MAX_KEYWORD_LENGTH 10549550#ifdef DEBUG_ENABLED551void GDScriptTokenizerText::make_keyword_list() {552#define KEYWORD_LINE(keyword, token_type) keyword,553#define KEYWORD_GROUP_IGNORE(group)554keyword_list = {555KEYWORDS(KEYWORD_GROUP_IGNORE, KEYWORD_LINE)556};557#undef KEYWORD_LINE558#undef KEYWORD_GROUP_IGNORE559}560#endif // DEBUG_ENABLED561562GDScriptTokenizer::Token GDScriptTokenizerText::potential_identifier() {563bool only_ascii = _peek(-1) < 128;564565// Consume all identifier characters.566while (is_unicode_identifier_continue(_peek())) {567char32_t c = _advance();568only_ascii = only_ascii && c < 128;569}570571int len = _current - _start;572573if (len == 1 && _peek(-1) == '_') {574// Lone underscore.575Token token = make_token(Token::UNDERSCORE);576token.literal = "_";577return token;578}579580String name = String::utf32(Span(_start, len));581if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) {582// Cannot be a keyword, as the length doesn't match any.583return make_identifier(name);584}585586if (!only_ascii) {587// Kept here in case the order with push_error matters.588Token id = make_identifier(name);589590#ifdef DEBUG_ENABLED591// Additional checks for identifiers but only in debug and if it's available in TextServer.592if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY)) {593int64_t confusable = TS->is_confusable(name, keyword_list);594if (confusable >= 0) {595push_error(vformat(R"(Identifier "%s" is visually similar to the GDScript keyword "%s" and thus not allowed.)", name, keyword_list[confusable]));596}597}598#endif // DEBUG_ENABLED599600// Cannot be a keyword, as keywords are ASCII only.601return id;602}603604// Define some helper macros for the switch case.605#define KEYWORD_GROUP_CASE(char) \606break; \607case char:608#define KEYWORD(keyword, token_type) \609{ \610const int keyword_length = sizeof(keyword) - 1; \611static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \612static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \613if (keyword_length == len && name == keyword) { \614Token kw = make_token(token_type); \615kw.literal = name; \616return kw; \617} \618}619620// Find if it's a keyword.621switch (_start[0]) {622default:623KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)624break;625}626627// Check if it's a special literal628if (len == 4) {629if (name == "true") {630return make_literal(true);631} else if (name == "null") {632return make_literal(Variant());633}634} else if (len == 5) {635if (name == "false") {636return make_literal(false);637}638}639640// Not a keyword, so must be an identifier.641return make_identifier(name);642643#undef KEYWORD_GROUP_CASE644#undef KEYWORD645}646647#undef MAX_KEYWORD_LENGTH648#undef MIN_KEYWORD_LENGTH649#undef KEYWORDS650651void GDScriptTokenizerText::newline(bool p_make_token) {652// Don't overwrite previous newline, nor create if we want a line continuation.653if (p_make_token && !pending_newline && !line_continuation) {654Token newline(Token::NEWLINE);655newline.start_line = line;656newline.end_line = line;657newline.start_column = column - 1;658newline.end_column = column;659pending_newline = true;660last_token = newline;661last_newline = newline;662}663664// Increment line/column counters.665line++;666column = 1;667}668669GDScriptTokenizer::Token GDScriptTokenizerText::number() {670int base = 10;671bool has_decimal = false;672bool has_exponent = false;673bool has_error = false;674bool need_digits = false;675bool (*digit_check_func)(char32_t) = is_digit;676677// Sign before hexadecimal or binary.678if ((_peek(-1) == '+' || _peek(-1) == '-') && _peek() == '0') {679_advance();680}681682if (_peek(-1) == '.') {683has_decimal = true;684} else if (_peek(-1) == '0') {685if (_peek() == 'x' || _peek() == 'X') {686// Hexadecimal.687base = 16;688digit_check_func = is_hex_digit;689need_digits = true;690_advance();691} else if (_peek() == 'b' || _peek() == 'B') {692// Binary.693base = 2;694digit_check_func = is_binary_digit;695need_digits = true;696_advance();697}698}699700if (base != 10 && is_underscore(_peek())) { // Disallow `0x_` and `0b_`.701Token error = make_error(vformat(R"(Unexpected underscore after "0%c".)", _peek(-1)));702error.start_column = column;703error.end_column = column + 1;704push_error(error);705has_error = true;706}707bool previous_was_underscore = false; // Allow `_` to be used in a number, for readability.708while (digit_check_func(_peek()) || is_underscore(_peek())) {709if (is_underscore(_peek())) {710if (previous_was_underscore) {711Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");712error.start_column = column;713error.end_column = column + 1;714push_error(error);715}716previous_was_underscore = true;717} else {718need_digits = false;719previous_was_underscore = false;720}721_advance();722}723724// It might be a ".." token (instead of decimal point) so we check if it's not.725if (_peek() == '.' && _peek(1) != '.') {726if (base == 10 && !has_decimal) {727has_decimal = true;728} else if (base == 10) {729Token error = make_error("Cannot use a decimal point twice in a number.");730error.start_column = column;731error.end_column = column + 1;732push_error(error);733has_error = true;734} else if (base == 16) {735Token error = make_error("Cannot use a decimal point in a hexadecimal number.");736error.start_column = column;737error.end_column = column + 1;738push_error(error);739has_error = true;740} else {741Token error = make_error("Cannot use a decimal point in a binary number.");742error.start_column = column;743error.end_column = column + 1;744push_error(error);745has_error = true;746}747if (!has_error) {748_advance();749750// Consume decimal digits.751if (is_underscore(_peek())) { // Disallow `10._`, but allow `10.`.752Token error = make_error(R"(Unexpected underscore after decimal point.)");753error.start_column = column;754error.end_column = column + 1;755push_error(error);756has_error = true;757}758previous_was_underscore = false;759while (is_digit(_peek()) || is_underscore(_peek())) {760if (is_underscore(_peek())) {761if (previous_was_underscore) {762Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");763error.start_column = column;764error.end_column = column + 1;765push_error(error);766}767previous_was_underscore = true;768} else {769previous_was_underscore = false;770}771_advance();772}773}774}775if (base == 10) {776if (_peek() == 'e' || _peek() == 'E') {777has_exponent = true;778_advance();779if (_peek() == '+' || _peek() == '-') {780// Exponent sign.781_advance();782}783// Consume exponent digits.784if (!is_digit(_peek())) {785Token error = make_error(R"(Expected exponent value after "e".)");786error.start_column = column;787error.end_column = column + 1;788push_error(error);789}790previous_was_underscore = false;791while (is_digit(_peek()) || is_underscore(_peek())) {792if (is_underscore(_peek())) {793if (previous_was_underscore) {794Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");795error.start_column = column;796error.end_column = column + 1;797push_error(error);798}799previous_was_underscore = true;800} else {801previous_was_underscore = false;802}803_advance();804}805}806}807808if (need_digits) {809// No digits in hex or bin literal.810Token error = make_error(vformat(R"(Expected %s digit after "0%c".)", (base == 16 ? "hexadecimal" : "binary"), (base == 16 ? 'x' : 'b')));811error.start_column = column;812error.end_column = column + 1;813return error;814}815816// Detect extra decimal point.817if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {818Token error = make_error("Cannot use a decimal point twice in a number.");819error.start_column = column;820error.end_column = column + 1;821push_error(error);822has_error = true;823} else if (is_unicode_identifier_start(_peek()) || is_unicode_identifier_continue(_peek())) {824// Letter at the end of the number.825push_error("Invalid numeric notation.");826}827828// Create a string with the whole number.829int len = _current - _start;830String number = String::utf32(Span(_start, len)).remove_char('_');831832// Convert to the appropriate literal type.833if (base == 16) {834int64_t value = number.hex_to_int();835return make_literal(value);836} else if (base == 2) {837int64_t value = number.bin_to_int();838return make_literal(value);839} else if (has_decimal || has_exponent) {840double value = number.to_float();841return make_literal(value);842} else {843int64_t value = number.to_int();844return make_literal(value);845}846}847848GDScriptTokenizer::Token GDScriptTokenizerText::string() {849enum StringType {850STRING_REGULAR,851STRING_NAME,852STRING_NODEPATH,853};854855bool is_raw = false;856bool is_multiline = false;857StringType type = STRING_REGULAR;858859if (_peek(-1) == 'r') {860is_raw = true;861_advance();862} else if (_peek(-1) == '&') {863type = STRING_NAME;864_advance();865} else if (_peek(-1) == '^') {866type = STRING_NODEPATH;867_advance();868}869870char32_t quote_char = _peek(-1);871872if (_peek() == quote_char && _peek(1) == quote_char) {873is_multiline = true;874// Consume all quotes.875_advance();876_advance();877}878879String result;880char32_t prev = 0;881int prev_pos = 0;882883for (;;) {884// Consume actual string.885if (_is_at_end()) {886return make_error("Unterminated string.");887}888889char32_t ch = _peek();890891if (ch == 0x200E || ch == 0x200F || (ch >= 0x202A && ch <= 0x202E) || (ch >= 0x2066 && ch <= 0x2069)) {892Token error;893if (is_raw) {894error = make_error("Invisible text direction control character present in the string, use regular string literal instead of r-string.");895} else {896error = make_error("Invisible text direction control character present in the string, escape it (\"\\u" + String::num_int64(ch, 16) + "\") to avoid confusion.");897}898error.start_column = column;899error.end_column = column + 1;900push_error(error);901}902903if (ch == '\\') {904// Escape pattern.905_advance();906if (_is_at_end()) {907return make_error("Unterminated string.");908}909910if (is_raw) {911if (_peek() == quote_char) {912_advance();913if (_is_at_end()) {914return make_error("Unterminated string.");915}916result += '\\';917result += quote_char;918} else if (_peek() == '\\') { // For `\\\"`.919_advance();920if (_is_at_end()) {921return make_error("Unterminated string.");922}923result += '\\';924result += '\\';925} else {926result += '\\';927}928} else {929// Grab escape character.930char32_t code = _peek();931_advance();932if (_is_at_end()) {933return make_error("Unterminated string.");934}935936char32_t escaped = 0;937bool valid_escape = true;938939switch (code) {940case 'a':941escaped = '\a';942break;943case 'b':944escaped = '\b';945break;946case 'f':947escaped = '\f';948break;949case 'n':950escaped = '\n';951break;952case 'r':953escaped = '\r';954break;955case 't':956escaped = '\t';957break;958case 'v':959escaped = '\v';960break;961case '\'':962escaped = '\'';963break;964case '\"':965escaped = '\"';966break;967case '\\':968escaped = '\\';969break;970case 'U':971case 'u': {972// Hexadecimal sequence.973int hex_len = (code == 'U') ? 6 : 4;974for (int j = 0; j < hex_len; j++) {975if (_is_at_end()) {976return make_error("Unterminated string.");977}978979char32_t digit = _peek();980char32_t value = 0;981if (is_digit(digit)) {982value = digit - '0';983} else if (digit >= 'a' && digit <= 'f') {984value = digit - 'a';985value += 10;986} else if (digit >= 'A' && digit <= 'F') {987value = digit - 'A';988value += 10;989} else {990// Make error, but keep parsing the string.991Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");992error.start_column = column;993error.end_column = column + 1;994push_error(error);995valid_escape = false;996break;997}998999escaped <<= 4;1000escaped |= value;10011002_advance();1003}1004} break;1005case '\r':1006if (_peek() != '\n') {1007// Carriage return without newline in string. (???)1008// Just add it to the string and keep going.1009result += ch;1010_advance();1011break;1012}1013[[fallthrough]];1014case '\n':1015// Escaping newline.1016newline(false);1017valid_escape = false; // Don't add to the string.1018break;1019default:1020Token error = make_error("Invalid escape in string.");1021error.start_column = column - 2;1022push_error(error);1023valid_escape = false;1024break;1025}1026// Parse UTF-16 pair.1027if (valid_escape) {1028if ((escaped & 0xfffffc00) == 0xd800) {1029if (prev == 0) {1030prev = escaped;1031prev_pos = column - 2;1032continue;1033} else {1034Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");1035error.start_column = column - 2;1036push_error(error);1037valid_escape = false;1038prev = 0;1039}1040} else if ((escaped & 0xfffffc00) == 0xdc00) {1041if (prev == 0) {1042Token error = make_error("Invalid UTF-16 sequence in string, unpaired trail surrogate.");1043error.start_column = column - 2;1044push_error(error);1045valid_escape = false;1046} else {1047escaped = (prev << 10UL) + escaped - ((0xd800 << 10UL) + 0xdc00 - 0x10000);1048prev = 0;1049}1050}1051if (prev != 0) {1052Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");1053error.start_column = prev_pos;1054push_error(error);1055prev = 0;1056}1057}10581059if (valid_escape) {1060result += escaped;1061}1062}1063} else if (ch == quote_char) {1064if (prev != 0) {1065Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1066error.start_column = prev_pos;1067push_error(error);1068prev = 0;1069}1070_advance();1071if (is_multiline) {1072if (_peek() == quote_char && _peek(1) == quote_char) {1073// Ended the multiline string. Consume all quotes.1074_advance();1075_advance();1076break;1077} else {1078// Not a multiline string termination, add consumed quote.1079result += quote_char;1080}1081} else {1082// Ended single-line string.1083break;1084}1085} else {1086if (prev != 0) {1087Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1088error.start_column = prev_pos;1089push_error(error);1090prev = 0;1091}1092result += ch;1093_advance();1094if (ch == '\n') {1095newline(false);1096}1097}1098}1099if (prev != 0) {1100Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");1101error.start_column = prev_pos;1102push_error(error);1103prev = 0;1104}11051106// Make the literal.1107Variant string;1108switch (type) {1109case STRING_NAME:1110string = StringName(result);1111break;1112case STRING_NODEPATH:1113string = NodePath(result);1114break;1115case STRING_REGULAR:1116string = result;1117break;1118}11191120return make_literal(string);1121}11221123void GDScriptTokenizerText::check_indent() {1124ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");11251126if (_is_at_end()) {1127// Send dedents for every indent level.1128pending_indents -= indent_level();1129indent_stack.clear();1130return;1131}11321133for (;;) {1134char32_t current_indent_char = _peek();1135int indent_count = 0;11361137if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {1138// First character of the line is not whitespace, so we clear all indentation levels.1139// Unless we are in a continuation or in multiline mode (inside expression).1140if (line_continuation || multiline_mode) {1141return;1142}1143pending_indents -= indent_level();1144indent_stack.clear();1145return;1146}11471148if (_peek() == '\r') {1149_advance();1150if (_peek() != '\n') {1151push_error("Stray carriage return character in source code.");1152}1153}1154if (_peek() == '\n') {1155// Empty line, keep going.1156_advance();1157newline(false);1158continue;1159}11601161// Check indent level.1162bool mixed = false;1163while (!_is_at_end()) {1164char32_t space = _peek();1165if (space == '\t') {1166// Consider individual tab columns.1167column += tab_size - 1;1168indent_count += tab_size;1169} else if (space == ' ') {1170indent_count += 1;1171} else {1172break;1173}1174mixed = mixed || space != current_indent_char;1175_advance();1176}11771178if (_is_at_end()) {1179// Reached the end with an empty line, so just dedent as much as needed.1180pending_indents -= indent_level();1181indent_stack.clear();1182return;1183}11841185if (_peek() == '\r') {1186_advance();1187if (_peek() != '\n') {1188push_error("Stray carriage return character in source code.");1189}1190}1191if (_peek() == '\n') {1192// Empty line, keep going.1193_advance();1194newline(false);1195continue;1196}1197if (_peek() == '#') {1198// Comment. Advance to the next line.1199#ifdef TOOLS_ENABLED1200String comment;1201while (_peek() != '\n' && !_is_at_end()) {1202comment += _advance();1203}1204comments[line] = CommentData(comment, true);1205#else1206while (_peek() != '\n' && !_is_at_end()) {1207_advance();1208}1209#endif // TOOLS_ENABLED1210if (_is_at_end()) {1211// Reached the end with an empty line, so just dedent as much as needed.1212pending_indents -= indent_level();1213indent_stack.clear();1214return;1215}1216_advance(); // Consume '\n'.1217newline(false);1218continue;1219}12201221if (mixed && !line_continuation && !multiline_mode) {1222Token error = make_error("Mixed use of tabs and spaces for indentation.");1223error.start_line = line;1224error.start_column = 1;1225push_error(error);1226}12271228if (line_continuation || multiline_mode) {1229// We cleared up all the whitespace at the beginning of the line.1230// If this is a line continuation or we're in multiline mode then we don't want any indentation changes.1231return;1232}12331234// Check if indentation character is consistent.1235if (indent_char == '\0') {1236// First time indenting, choose character now.1237indent_char = current_indent_char;1238} else if (current_indent_char != indent_char) {1239Token error = make_error(vformat("Used %s character for indentation instead of %s as used before in the file.",1240_get_indent_char_name(current_indent_char), _get_indent_char_name(indent_char)));1241error.start_line = line;1242error.start_column = 1;1243push_error(error);1244}12451246// Now we can do actual indentation changes.12471248// Check if indent or dedent.1249int previous_indent = 0;1250if (indent_level() > 0) {1251previous_indent = indent_stack.back()->get();1252}1253if (indent_count == previous_indent) {1254// No change in indentation.1255return;1256}1257if (indent_count > previous_indent) {1258// Indentation increased.1259indent_stack.push_back(indent_count);1260pending_indents++;1261} else {1262// Indentation decreased (dedent).1263if (indent_level() == 0) {1264push_error("Tokenizer bug: trying to dedent without previous indent.");1265return;1266}1267while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {1268indent_stack.pop_back();1269pending_indents--;1270}1271if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {1272// Mismatched indentation alignment.1273Token error = make_error("Unindent doesn't match the previous indentation level.");1274error.start_line = line;1275error.start_column = 1;1276error.end_column = column + 1;1277push_error(error);1278// Still, we'll be lenient and keep going, so keep this level in the stack.1279indent_stack.push_back(indent_count);1280}1281}1282break; // Get out of the loop in any case.1283}1284}12851286String GDScriptTokenizerText::_get_indent_char_name(char32_t ch) {1287ERR_FAIL_COND_V(ch != ' ' && ch != '\t', String::chr(ch).c_escape());12881289return ch == ' ' ? "space" : "tab";1290}12911292void GDScriptTokenizerText::_skip_whitespace() {1293if (pending_indents != 0) {1294// Still have some indent/dedent tokens to give.1295return;1296}12971298bool is_bol = column == 1; // Beginning of line.12991300if (is_bol) {1301check_indent();1302return;1303}13041305for (;;) {1306char32_t c = _peek();1307switch (c) {1308case ' ':1309_advance();1310break;1311case '\t':1312_advance();1313// Consider individual tab columns.1314column += tab_size - 1;1315break;1316case '\r':1317_advance(); // Consume either way.1318if (_peek() != '\n') {1319push_error("Stray carriage return character in source code.");1320return;1321}1322break;1323case '\n':1324_advance();1325newline(!is_bol); // Don't create new line token if line is empty.1326check_indent();1327break;1328case '#': {1329// Comment.1330#ifdef TOOLS_ENABLED1331String comment;1332while (_peek() != '\n' && !_is_at_end()) {1333comment += _advance();1334}1335comments[line] = CommentData(comment, is_bol);1336#else1337while (_peek() != '\n' && !_is_at_end()) {1338_advance();1339}1340#endif // TOOLS_ENABLED1341if (_is_at_end()) {1342return;1343}1344_advance(); // Consume '\n'1345newline(!is_bol);1346check_indent();1347} break;1348default:1349return;1350}1351}1352}13531354GDScriptTokenizer::Token GDScriptTokenizerText::scan() {1355if (has_error()) {1356return pop_error();1357}13581359_skip_whitespace();13601361if (pending_newline) {1362pending_newline = false;1363if (!multiline_mode) {1364// Don't return newline tokens on multiline mode.1365return last_newline;1366}1367}13681369// Check for potential errors after skipping whitespace().1370if (has_error()) {1371return pop_error();1372}13731374_start = _current;1375start_line = line;1376start_column = column;13771378if (pending_indents != 0) {1379// Adjust position for indent.1380_start -= start_column - 1;1381start_column = 1;1382if (pending_indents > 0) {1383// Indents.1384pending_indents--;1385return make_token(Token::INDENT);1386} else {1387// Dedents.1388pending_indents++;1389Token dedent = make_token(Token::DEDENT);1390dedent.end_column += 1;1391return dedent;1392}1393}13941395if (_is_at_end()) {1396return make_token(Token::TK_EOF);1397}13981399const char32_t c = _advance();14001401if (c == '\\') {1402// Line continuation with backslash.1403if (_peek() == '\r') {1404if (_peek(1) != '\n') {1405return make_error("Unexpected carriage return character.");1406}1407_advance();1408}1409if (_peek() != '\n') {1410return make_error("Expected new line after \"\\\".");1411}1412_advance();1413newline(false);1414line_continuation = true;1415_skip_whitespace(); // Skip whitespace/comment lines after `\`. See GH-89403.1416continuation_lines.push_back(line);1417return scan(); // Recurse to get next token.1418}14191420line_continuation = false;14211422if (is_digit(c)) {1423return number();1424} else if (c == 'r' && (_peek() == '"' || _peek() == '\'')) {1425// Raw string literals.1426return string();1427} else if (is_unicode_identifier_start(c)) {1428return potential_identifier();1429}14301431switch (c) {1432// String literals.1433case '"':1434case '\'':1435return string();14361437// Annotation.1438case '@':1439return annotation();14401441// Single characters.1442case '~':1443return make_token(Token::TILDE);1444case ',':1445return make_token(Token::COMMA);1446case ':':1447return make_token(Token::COLON);1448case ';':1449return make_token(Token::SEMICOLON);1450case '$':1451return make_token(Token::DOLLAR);1452case '?':1453return make_token(Token::QUESTION_MARK);1454case '`':1455return make_token(Token::BACKTICK);14561457// Parens.1458case '(':1459push_paren('(');1460return make_token(Token::PARENTHESIS_OPEN);1461case '[':1462push_paren('[');1463return make_token(Token::BRACKET_OPEN);1464case '{':1465push_paren('{');1466return make_token(Token::BRACE_OPEN);1467case ')':1468if (!pop_paren('(')) {1469return make_paren_error(c);1470}1471return make_token(Token::PARENTHESIS_CLOSE);1472case ']':1473if (!pop_paren('[')) {1474return make_paren_error(c);1475}1476return make_token(Token::BRACKET_CLOSE);1477case '}':1478if (!pop_paren('{')) {1479return make_paren_error(c);1480}1481return make_token(Token::BRACE_CLOSE);14821483// Double characters.1484case '!':1485if (_peek() == '=') {1486_advance();1487return make_token(Token::BANG_EQUAL);1488} else {1489return make_token(Token::BANG);1490}1491case '.':1492if (_peek() == '.') {1493_advance();1494if (_peek() == '.') {1495_advance();1496return make_token(Token::PERIOD_PERIOD_PERIOD);1497}1498return make_token(Token::PERIOD_PERIOD);1499} else if (is_digit(_peek())) {1500// Number starting with '.'.1501return number();1502} else {1503return make_token(Token::PERIOD);1504}1505case '+':1506if (_peek() == '=') {1507_advance();1508return make_token(Token::PLUS_EQUAL);1509} else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {1510// Number starting with '+'.1511return number();1512} else {1513return make_token(Token::PLUS);1514}1515case '-':1516if (_peek() == '=') {1517_advance();1518return make_token(Token::MINUS_EQUAL);1519} else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {1520// Number starting with '-'.1521return number();1522} else if (_peek() == '>') {1523_advance();1524return make_token(Token::FORWARD_ARROW);1525} else {1526return make_token(Token::MINUS);1527}1528case '*':1529if (_peek() == '=') {1530_advance();1531return make_token(Token::STAR_EQUAL);1532} else if (_peek() == '*') {1533if (_peek(1) == '=') {1534_advance();1535_advance(); // Advance both '*' and '='1536return make_token(Token::STAR_STAR_EQUAL);1537}1538_advance();1539return make_token(Token::STAR_STAR);1540} else {1541return make_token(Token::STAR);1542}1543case '/':1544if (_peek() == '=') {1545_advance();1546return make_token(Token::SLASH_EQUAL);1547} else {1548return make_token(Token::SLASH);1549}1550case '%':1551if (_peek() == '=') {1552_advance();1553return make_token(Token::PERCENT_EQUAL);1554} else {1555return make_token(Token::PERCENT);1556}1557case '^':1558if (_peek() == '=') {1559_advance();1560return make_token(Token::CARET_EQUAL);1561} else if (_peek() == '"' || _peek() == '\'') {1562// Node path1563return string();1564} else {1565return make_token(Token::CARET);1566}1567case '&':1568if (_peek() == '&') {1569_advance();1570return make_token(Token::AMPERSAND_AMPERSAND);1571} else if (_peek() == '=') {1572_advance();1573return make_token(Token::AMPERSAND_EQUAL);1574} else if (_peek() == '"' || _peek() == '\'') {1575// String Name1576return string();1577} else {1578return make_token(Token::AMPERSAND);1579}1580case '|':1581if (_peek() == '|') {1582_advance();1583return make_token(Token::PIPE_PIPE);1584} else if (_peek() == '=') {1585_advance();1586return make_token(Token::PIPE_EQUAL);1587} else {1588return make_token(Token::PIPE);1589}15901591// Potential VCS conflict markers.1592case '=':1593if (_peek() == '=') {1594return check_vcs_marker('=', Token::EQUAL_EQUAL);1595} else {1596return make_token(Token::EQUAL);1597}1598case '<':1599if (_peek() == '=') {1600_advance();1601return make_token(Token::LESS_EQUAL);1602} else if (_peek() == '<') {1603if (_peek(1) == '=') {1604_advance();1605_advance(); // Advance both '<' and '='1606return make_token(Token::LESS_LESS_EQUAL);1607} else {1608return check_vcs_marker('<', Token::LESS_LESS);1609}1610} else {1611return make_token(Token::LESS);1612}1613case '>':1614if (_peek() == '=') {1615_advance();1616return make_token(Token::GREATER_EQUAL);1617} else if (_peek() == '>') {1618if (_peek(1) == '=') {1619_advance();1620_advance(); // Advance both '>' and '='1621return make_token(Token::GREATER_GREATER_EQUAL);1622} else {1623return check_vcs_marker('>', Token::GREATER_GREATER);1624}1625} else {1626return make_token(Token::GREATER);1627}16281629default:1630if (is_whitespace(c)) {1631return make_error(vformat(R"(Invalid white space character U+%04X.)", static_cast<int32_t>(c)));1632} else {1633return make_error(vformat(R"(Invalid character "%c" (U+%04X).)", c, static_cast<int32_t>(c)));1634}1635}1636}16371638GDScriptTokenizerText::GDScriptTokenizerText() {1639#ifdef TOOLS_ENABLED1640if (EditorSettings::get_singleton()) {1641tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");1642}1643#endif // TOOLS_ENABLED1644#ifdef DEBUG_ENABLED1645make_keyword_list();1646#endif // DEBUG_ENABLED1647}164816491650