Path: blob/master/modules/gdscript/gdscript_analyzer.cpp
11351 views
/**************************************************************************/1/* gdscript_analyzer.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_analyzer.h"3132#include "gdscript.h"33#include "gdscript_utility_callable.h"34#include "gdscript_utility_functions.h"3536#include "core/config/engine.h"37#include "core/config/project_settings.h"38#include "core/core_constants.h"39#include "core/io/file_access.h"40#include "core/io/resource_loader.h"41#include "core/object/class_db.h"42#include "core/object/script_language.h"43#include "core/templates/hash_map.h"44#include "scene/main/node.h"4546#if defined(TOOLS_ENABLED) && !defined(DISABLE_DEPRECATED)47#define SUGGEST_GODOT4_RENAMES48#include "editor/project_upgrade/renames_map_3_to_4.h"49#endif5051#define UNNAMED_ENUM "<anonymous enum>"52#define ENUM_SEPARATOR "."5354static MethodInfo info_from_utility_func(const StringName &p_function) {55ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());5657MethodInfo info(p_function);5859if (Variant::has_utility_function_return_value(p_function)) {60info.return_val.type = Variant::get_utility_function_return_type(p_function);61if (info.return_val.type == Variant::NIL) {62info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;63}64}6566if (Variant::is_utility_function_vararg(p_function)) {67info.flags |= METHOD_FLAG_VARARG;68} else {69for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {70PropertyInfo pi;71#ifdef DEBUG_ENABLED72pi.name = Variant::get_utility_function_argument_name(p_function, i);73#else74pi.name = "arg" + itos(i + 1);75#endif // DEBUG_ENABLED76pi.type = Variant::get_utility_function_argument_type(p_function, i);77info.arguments.push_back(pi);78}79}8081return info;82}8384static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {85GDScriptParser::DataType type;86type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;87type.kind = GDScriptParser::DataType::BUILTIN;88type.builtin_type = Variant::CALLABLE;89type.is_constant = true;90type.method_info = p_info;91return type;92}9394static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {95GDScriptParser::DataType type;96type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;97type.kind = GDScriptParser::DataType::BUILTIN;98type.builtin_type = Variant::SIGNAL;99type.is_constant = true;100type.method_info = p_info;101return type;102}103104static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {105GDScriptParser::DataType type;106type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;107type.kind = GDScriptParser::DataType::NATIVE;108type.builtin_type = Variant::OBJECT;109type.native_type = p_class_name;110type.is_constant = true;111type.is_meta_type = true;112return type;113}114115static GDScriptParser::DataType make_script_meta_type(const Ref<Script> &p_script) {116GDScriptParser::DataType type;117type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;118type.kind = GDScriptParser::DataType::SCRIPT;119type.builtin_type = Variant::OBJECT;120type.native_type = p_script->get_instance_base_type();121type.script_type = p_script;122type.script_path = p_script->get_path();123type.is_constant = true;124type.is_meta_type = true;125return type;126}127128// In enum types, native_type is used to store the class (native or otherwise) that the enum belongs to.129// This disambiguates between similarly named enums in base classes or outer classes130static GDScriptParser::DataType make_enum_type(const StringName &p_enum_name, const String &p_base_name, const bool p_meta = false) {131GDScriptParser::DataType type;132type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;133type.kind = GDScriptParser::DataType::ENUM;134type.builtin_type = p_meta ? Variant::DICTIONARY : Variant::INT;135type.enum_type = p_enum_name;136type.is_constant = true;137type.is_meta_type = p_meta;138139// For enums, native_type is only used to check compatibility in is_type_compatible()140// We can set anything readable here for error messages, as long as it uniquely identifies the type of the enum141if (p_base_name.is_empty()) {142type.native_type = p_enum_name;143} else {144type.native_type = p_base_name + ENUM_SEPARATOR + p_enum_name;145}146147return type;148}149150static GDScriptParser::DataType make_class_enum_type(const StringName &p_enum_name, GDScriptParser::ClassNode *p_class, const String &p_script_path, bool p_meta = true) {151GDScriptParser::DataType type = make_enum_type(p_enum_name, p_class->fqcn, p_meta);152153type.class_type = p_class;154type.script_path = p_script_path;155156return type;157}158159static GDScriptParser::DataType make_native_enum_type(const StringName &p_enum_name, const StringName &p_native_class, bool p_meta = true) {160// Find out which base class declared the enum, so the name is always the same even when coming from other contexts.161StringName native_base = p_native_class;162while (true && native_base != StringName()) {163if (ClassDB::has_enum(native_base, p_enum_name, true)) {164break;165}166native_base = ClassDB::get_parent_class_nocheck(native_base);167}168169GDScriptParser::DataType type = make_enum_type(p_enum_name, native_base, p_meta);170if (p_meta) {171// Native enum types are not dictionaries.172type.builtin_type = Variant::NIL;173type.is_pseudo_type = true;174}175176List<StringName> enum_values;177ClassDB::get_enum_constants(native_base, p_enum_name, &enum_values, true);178179for (const StringName &E : enum_values) {180type.enum_values[E] = ClassDB::get_integer_constant(native_base, E);181}182183return type;184}185186static GDScriptParser::DataType make_builtin_enum_type(const StringName &p_enum_name, Variant::Type p_type, bool p_meta = true) {187GDScriptParser::DataType type = make_enum_type(p_enum_name, Variant::get_type_name(p_type), p_meta);188if (p_meta) {189// Built-in enum types are not dictionaries.190type.builtin_type = Variant::NIL;191type.is_pseudo_type = true;192}193194List<StringName> enum_values;195Variant::get_enumerations_for_enum(p_type, p_enum_name, &enum_values);196197for (const StringName &E : enum_values) {198type.enum_values[E] = Variant::get_enum_value(p_type, p_enum_name, E);199}200201return type;202}203204static GDScriptParser::DataType make_global_enum_type(const StringName &p_enum_name, const StringName &p_base, bool p_meta = true) {205GDScriptParser::DataType type = make_enum_type(p_enum_name, p_base, p_meta);206if (p_meta) {207// Global enum types are not dictionaries.208type.builtin_type = Variant::NIL;209type.is_pseudo_type = true;210}211212HashMap<StringName, int64_t> enum_values;213CoreConstants::get_enum_values(type.native_type, &enum_values);214for (const KeyValue<StringName, int64_t> &element : enum_values) {215type.enum_values[element.key] = element.value;216}217218return type;219}220221static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {222GDScriptParser::DataType type;223type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;224type.kind = GDScriptParser::DataType::BUILTIN;225type.builtin_type = p_type;226type.is_constant = true;227type.is_meta_type = true;228return type;229}230231bool GDScriptAnalyzer::has_member_name_conflict_in_script_class(const StringName &p_member_name, const GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_member) {232if (p_class->members_indices.has(p_member_name)) {233int index = p_class->members_indices[p_member_name];234const GDScriptParser::ClassNode::Member *member = &p_class->members[index];235236if (member->type == GDScriptParser::ClassNode::Member::VARIABLE ||237member->type == GDScriptParser::ClassNode::Member::CONSTANT ||238member->type == GDScriptParser::ClassNode::Member::ENUM ||239member->type == GDScriptParser::ClassNode::Member::ENUM_VALUE ||240member->type == GDScriptParser::ClassNode::Member::CLASS ||241member->type == GDScriptParser::ClassNode::Member::SIGNAL) {242return true;243}244if (p_member->type != GDScriptParser::Node::FUNCTION && member->type == GDScriptParser::ClassNode::Member::FUNCTION) {245return true;246}247}248249return false;250}251252bool GDScriptAnalyzer::has_member_name_conflict_in_native_type(const StringName &p_member_name, const StringName &p_native_type_string) {253if (ClassDB::has_signal(p_native_type_string, p_member_name)) {254return true;255}256if (ClassDB::has_property(p_native_type_string, p_member_name)) {257return true;258}259if (ClassDB::has_integer_constant(p_native_type_string, p_member_name)) {260return true;261}262if (p_member_name == CoreStringName(script)) {263return true;264}265266return false;267}268269Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_member_name, const GDScriptParser::Node *p_member_node, const StringName &p_native_type_string) {270if (has_member_name_conflict_in_native_type(p_member_name, p_native_type_string)) {271push_error(vformat(R"(Member "%s" redefined (original in native class '%s'))", p_member_name, p_native_type_string), p_member_node);272return ERR_PARSE_ERROR;273}274275if (class_exists(p_member_name)) {276push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);277return ERR_PARSE_ERROR;278}279280if (GDScriptParser::get_builtin_type(p_member_name) < Variant::VARIANT_MAX) {281push_error(vformat(R"(The member "%s" cannot have the same name as a builtin type.)", p_member_name), p_member_node);282return ERR_PARSE_ERROR;283}284285return OK;286}287288Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::ClassNode *p_class_node, const StringName &p_member_name, const GDScriptParser::Node *p_member_node) {289// TODO check outer classes for static members only290const GDScriptParser::DataType *current_data_type = &p_class_node->base_type;291while (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::CLASS) {292GDScriptParser::ClassNode *current_class_node = current_data_type->class_type;293if (has_member_name_conflict_in_script_class(p_member_name, current_class_node, p_member_node)) {294String parent_class_name = current_class_node->fqcn;295if (current_class_node->identifier != nullptr) {296parent_class_name = current_class_node->identifier->name;297}298push_error(vformat(R"(The member "%s" already exists in parent class %s.)", p_member_name, parent_class_name), p_member_node);299return ERR_PARSE_ERROR;300}301current_data_type = ¤t_class_node->base_type;302}303304// No need for native class recursion because Node exposes all Object's properties.305if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {306if (current_data_type->native_type != StringName()) {307return check_native_member_name_conflict(308p_member_name,309p_member_node,310current_data_type->native_type);311}312}313314return OK;315}316317void GDScriptAnalyzer::get_class_node_current_scope_classes(GDScriptParser::ClassNode *p_node, List<GDScriptParser::ClassNode *> *p_list, GDScriptParser::Node *p_source) {318ERR_FAIL_NULL(p_node);319ERR_FAIL_NULL(p_list);320321if (p_list->find(p_node) != nullptr) {322return;323}324325p_list->push_back(p_node);326327// TODO: Try to solve class inheritance if not yet resolving.328329// Prioritize node base type over its outer class330if (p_node->base_type.class_type != nullptr) {331// TODO: 'ensure_cached_external_parser_for_class()' is only necessary because 'resolve_class_inheritance()' is not getting called here.332ensure_cached_external_parser_for_class(p_node->base_type.class_type, p_node, "Trying to fetch classes in the current scope", p_source);333get_class_node_current_scope_classes(p_node->base_type.class_type, p_list, p_source);334}335336if (p_node->outer != nullptr) {337// TODO: 'ensure_cached_external_parser_for_class()' is only necessary because 'resolve_class_inheritance()' is not getting called here.338ensure_cached_external_parser_for_class(p_node->outer, p_node, "Trying to fetch classes in the current scope", p_source);339get_class_node_current_scope_classes(p_node->outer, p_list, p_source);340}341}342343Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {344if (p_source == nullptr && parser->has_class(p_class)) {345p_source = p_class;346}347348Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class inheritance", p_source);349Finally finally([&]() {350for (GDScriptParser::ClassNode *look_class = p_class; look_class != nullptr; look_class = look_class->base_type.class_type) {351ensure_cached_external_parser_for_class(look_class->base_type.class_type, look_class, "Trying to resolve class inheritance", p_source);352}353});354355if (p_class->base_type.is_resolving()) {356push_error(vformat(R"(Could not resolve class "%s": Cyclic reference.)", type_from_metatype(p_class->get_datatype()).to_string()), p_source);357return ERR_PARSE_ERROR;358}359360if (!p_class->base_type.has_no_type()) {361// Already resolved.362return OK;363}364365if (!parser->has_class(p_class)) {366if (parser_ref.is_null()) {367// Error already pushed.368return ERR_PARSE_ERROR;369}370371Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);372if (err) {373push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);374return ERR_PARSE_ERROR;375}376377GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();378GDScriptParser *other_parser = parser_ref->get_parser();379380int error_count = other_parser->errors.size();381other_analyzer->resolve_class_inheritance(p_class);382if (other_parser->errors.size() > error_count) {383push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->fqcn), p_source);384return ERR_PARSE_ERROR;385}386387return OK;388}389390GDScriptParser::ClassNode *previous_class = parser->current_class;391parser->current_class = p_class;392393if (p_class->identifier) {394StringName class_name = p_class->identifier->name;395if (GDScriptParser::get_builtin_type(class_name) < Variant::VARIANT_MAX) {396push_error(vformat(R"(Class "%s" hides a built-in type.)", class_name), p_class->identifier);397} else if (class_exists(class_name)) {398push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);399} else if (ScriptServer::is_global_class(class_name) && (!GDScript::is_canonically_equal_paths(ScriptServer::get_global_class_path(class_name), parser->script_path) || p_class != parser->head)) {400push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);401} else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {402push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);403}404}405406GDScriptParser::DataType resolving_datatype;407resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;408p_class->base_type = resolving_datatype;409410// Set datatype for class.411GDScriptParser::DataType class_type;412class_type.is_constant = true;413class_type.is_meta_type = true;414class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;415class_type.kind = GDScriptParser::DataType::CLASS;416class_type.class_type = p_class;417class_type.script_path = parser->script_path;418class_type.builtin_type = Variant::OBJECT;419p_class->set_datatype(class_type);420421GDScriptParser::DataType result;422if (!p_class->extends_used) {423result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;424result.kind = GDScriptParser::DataType::NATIVE;425result.builtin_type = Variant::OBJECT;426result.native_type = SNAME("RefCounted");427} else {428result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;429430GDScriptParser::DataType base;431432int extends_index = 0;433434if (!p_class->extends_path.is_empty()) {435if (p_class->extends_path.is_relative_path()) {436p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path();437}438Ref<GDScriptParserRef> ext_parser = parser->get_depended_parser_for(p_class->extends_path);439if (ext_parser.is_null()) {440push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);441return ERR_PARSE_ERROR;442}443444Error err = ext_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);445if (err != OK) {446push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);447return err;448}449450#ifdef DEBUG_ENABLED451if (!parser->_is_tool && ext_parser->get_parser()->_is_tool) {452parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);453}454#endif // DEBUG_ENABLED455456base = ext_parser->get_parser()->head->get_datatype();457} else {458if (p_class->extends.is_empty()) {459push_error("Could not resolve an empty super class path.", p_class);460return ERR_PARSE_ERROR;461}462GDScriptParser::IdentifierNode *id = p_class->extends[extends_index++];463const StringName &name = id->name;464base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;465466if (ScriptServer::is_global_class(name)) {467String base_path = ScriptServer::get_global_class_path(name);468469if (GDScript::is_canonically_equal_paths(base_path, parser->script_path)) {470base = parser->head->get_datatype();471} else {472Ref<GDScriptParserRef> base_parser = parser->get_depended_parser_for(base_path);473if (base_parser.is_null()) {474push_error(vformat(R"(Could not resolve super class "%s".)", name), id);475return ERR_PARSE_ERROR;476}477478Error err = base_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);479if (err != OK) {480push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);481return err;482}483484#ifdef DEBUG_ENABLED485if (!parser->_is_tool && base_parser->get_parser()->_is_tool) {486parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);487}488#endif // DEBUG_ENABLED489490base = base_parser->get_parser()->head->get_datatype();491}492} else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {493const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);494if (info.path.get_extension().to_lower() != GDScriptLanguage::get_singleton()->get_extension()) {495push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), id);496return ERR_PARSE_ERROR;497}498499Ref<GDScriptParserRef> info_parser = parser->get_depended_parser_for(info.path);500if (info_parser.is_null()) {501push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), id);502return ERR_PARSE_ERROR;503}504505Error err = info_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);506if (err != OK) {507push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);508return err;509}510511#ifdef DEBUG_ENABLED512if (!parser->_is_tool && info_parser->get_parser()->_is_tool) {513parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);514}515#endif // DEBUG_ENABLED516517base = info_parser->get_parser()->head->get_datatype();518} else if (class_exists(name)) {519if (Engine::get_singleton()->has_singleton(name)) {520push_error(vformat(R"(Cannot inherit native class "%s" because it is an engine singleton.)", name), id);521return ERR_PARSE_ERROR;522}523base.kind = GDScriptParser::DataType::NATIVE;524base.builtin_type = Variant::OBJECT;525base.native_type = name;526} else {527// Look for other classes in script.528bool found = false;529List<GDScriptParser::ClassNode *> script_classes;530get_class_node_current_scope_classes(p_class, &script_classes, id);531for (GDScriptParser::ClassNode *look_class : script_classes) {532if (look_class->identifier && look_class->identifier->name == name) {533if (!look_class->get_datatype().is_set()) {534Error err = resolve_class_inheritance(look_class, id);535if (err) {536return err;537}538}539base = look_class->get_datatype();540found = true;541break;542}543if (look_class->has_member(name)) {544resolve_class_member(look_class, name, id);545GDScriptParser::ClassNode::Member member = look_class->get_member(name);546GDScriptParser::DataType member_datatype = member.get_datatype();547548switch (member.type) {549case GDScriptParser::ClassNode::Member::CLASS:550break; // OK.551case GDScriptParser::ClassNode::Member::CONSTANT:552if (member_datatype.kind != GDScriptParser::DataType::SCRIPT && member_datatype.kind != GDScriptParser::DataType::CLASS) {553push_error(vformat(R"(Constant "%s" is not a preloaded script or class.)", name), id);554return ERR_PARSE_ERROR;555}556break;557default:558push_error(vformat(R"(Cannot use %s "%s" in extends chain.)", member.get_type_name(), name), id);559return ERR_PARSE_ERROR;560}561562base = member_datatype;563found = true;564break;565}566}567568if (!found) {569push_error(vformat(R"(Could not find base class "%s".)", name), id);570return ERR_PARSE_ERROR;571}572}573}574575for (int index = extends_index; index < p_class->extends.size(); index++) {576GDScriptParser::IdentifierNode *id = p_class->extends[index];577578if (base.kind != GDScriptParser::DataType::CLASS) {579push_error(vformat(R"(Cannot get nested types for extension from non-GDScript type "%s".)", base.to_string()), id);580return ERR_PARSE_ERROR;581}582583reduce_identifier_from_base(id, &base);584GDScriptParser::DataType id_type = id->get_datatype();585586if (!id_type.is_set()) {587push_error(vformat(R"(Could not find nested type "%s".)", id->name), id);588return ERR_PARSE_ERROR;589} else if (id_type.kind != GDScriptParser::DataType::SCRIPT && id_type.kind != GDScriptParser::DataType::CLASS) {590push_error(vformat(R"(Identifier "%s" is not a preloaded script or class.)", id->name), id);591return ERR_PARSE_ERROR;592}593594base = id_type;595}596597result = base;598}599600if (!result.is_set() || result.has_no_type()) {601// TODO: More specific error messages.602push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);603return ERR_PARSE_ERROR;604}605606// Check for cyclic inheritance.607const GDScriptParser::ClassNode *base_class = result.class_type;608while (base_class) {609if (base_class->fqcn == p_class->fqcn) {610push_error("Cyclic inheritance.", p_class);611return ERR_PARSE_ERROR;612}613base_class = base_class->base_type.class_type;614}615616p_class->base_type = result;617class_type.native_type = result.native_type;618p_class->set_datatype(class_type);619620// Apply annotations.621for (GDScriptParser::AnnotationNode *&E : p_class->annotations) {622resolve_annotation(E);623E->apply(parser, p_class, p_class->outer);624}625626parser->current_class = previous_class;627628return OK;629}630631Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {632Error err = resolve_class_inheritance(p_class);633if (err) {634return err;635}636637if (p_recursive) {638for (int i = 0; i < p_class->members.size(); i++) {639if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {640err = resolve_class_inheritance(p_class->members[i].m_class, true);641if (err) {642return err;643}644}645}646}647648return OK;649}650651GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {652GDScriptParser::DataType bad_type;653bad_type.kind = GDScriptParser::DataType::VARIANT;654bad_type.type_source = GDScriptParser::DataType::INFERRED;655656if (p_type == nullptr) {657return bad_type;658}659660if (p_type->get_datatype().is_resolving()) {661push_error(R"(Could not resolve datatype: Cyclic reference.)", p_type);662return bad_type;663}664665if (!p_type->get_datatype().has_no_type()) {666return p_type->get_datatype();667}668669GDScriptParser::DataType resolving_datatype;670resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;671p_type->set_datatype(resolving_datatype);672673GDScriptParser::DataType result;674result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;675676if (p_type->type_chain.is_empty()) {677// void.678result.kind = GDScriptParser::DataType::BUILTIN;679result.builtin_type = Variant::NIL;680p_type->set_datatype(result);681return result;682}683684const GDScriptParser::IdentifierNode *first_id = p_type->type_chain[0];685StringName first = first_id->name;686bool type_found = false;687688if (first_id->suite && first_id->suite->has_local(first)) {689const GDScriptParser::SuiteNode::Local &local = first_id->suite->get_local(first);690if (local.type == GDScriptParser::SuiteNode::Local::CONSTANT) {691result = local.get_datatype();692if (!result.is_set()) {693// Don't try to resolve it as the constant can be declared below.694push_error(vformat(R"(Local constant "%s" is not resolved at this point.)", first), first_id);695return bad_type;696}697if (result.is_meta_type) {698type_found = true;699} else if (Ref<Script>(local.constant->initializer->reduced_value).is_valid()) {700Ref<GDScript> gdscript = local.constant->initializer->reduced_value;701if (gdscript.is_valid()) {702Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(gdscript->get_script_path());703if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {704push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), first_id);705return bad_type;706}707result = ref->get_parser()->head->get_datatype();708} else {709result = make_script_meta_type(local.constant->initializer->reduced_value);710}711type_found = true;712} else {713push_error(vformat(R"(Local constant "%s" is not a valid type.)", first), first_id);714return bad_type;715}716} else {717push_error(vformat(R"(Local %s "%s" cannot be used as a type.)", local.get_name(), first), first_id);718return bad_type;719}720}721722if (!type_found) {723if (first == SNAME("Variant")) {724if (p_type->type_chain.size() == 2) {725// May be nested enum.726const StringName enum_name = p_type->type_chain[1]->name;727const StringName qualified_name = String(first) + ENUM_SEPARATOR + String(p_type->type_chain[1]->name);728if (CoreConstants::is_global_enum(qualified_name)) {729result = make_global_enum_type(enum_name, first, true);730return result;731} else {732push_error(vformat(R"(Name "%s" is not a nested type of "Variant".)", enum_name), p_type->type_chain[1]);733return bad_type;734}735} else if (p_type->type_chain.size() > 2) {736push_error(R"(Variant only contains enum types, which do not have nested types.)", p_type->type_chain[2]);737return bad_type;738}739result.kind = GDScriptParser::DataType::VARIANT;740} else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {741// Built-in types.742const Variant::Type builtin_type = GDScriptParser::get_builtin_type(first);743744if (p_type->type_chain.size() == 2) {745// May be nested enum.746const StringName enum_name = p_type->type_chain[1]->name;747if (Variant::has_enum(builtin_type, enum_name)) {748result = make_builtin_enum_type(enum_name, builtin_type, true);749return result;750} else {751push_error(vformat(R"(Name "%s" is not a nested type of "%s".)", enum_name, first), p_type->type_chain[1]);752return bad_type;753}754} else if (p_type->type_chain.size() > 2) {755push_error(R"(Built-in types only contain enum types, which do not have nested types.)", p_type->type_chain[2]);756return bad_type;757}758759result.kind = GDScriptParser::DataType::BUILTIN;760result.builtin_type = builtin_type;761762if (builtin_type == Variant::ARRAY) {763GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->get_container_type_or_null(0)));764if (container_type.kind != GDScriptParser::DataType::VARIANT) {765container_type.is_constant = false;766result.set_container_element_type(0, container_type);767}768}769if (builtin_type == Variant::DICTIONARY) {770GDScriptParser::DataType key_type = type_from_metatype(resolve_datatype(p_type->get_container_type_or_null(0)));771if (key_type.kind != GDScriptParser::DataType::VARIANT) {772key_type.is_constant = false;773result.set_container_element_type(0, key_type);774}775GDScriptParser::DataType value_type = type_from_metatype(resolve_datatype(p_type->get_container_type_or_null(1)));776if (value_type.kind != GDScriptParser::DataType::VARIANT) {777value_type.is_constant = false;778result.set_container_element_type(1, value_type);779}780}781} else if (class_exists(first)) {782// Native engine classes.783result.kind = GDScriptParser::DataType::NATIVE;784result.builtin_type = Variant::OBJECT;785result.native_type = first;786} else if (ScriptServer::is_global_class(first)) {787if (GDScript::is_canonically_equal_paths(parser->script_path, ScriptServer::get_global_class_path(first))) {788result = parser->head->get_datatype();789} else {790String path = ScriptServer::get_global_class_path(first);791String ext = path.get_extension();792if (ext == GDScriptLanguage::get_singleton()->get_extension()) {793Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(path);794if (ref.is_null() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {795push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);796return bad_type;797}798result = ref->get_parser()->head->get_datatype();799} else {800result = make_script_meta_type(ResourceLoader::load(path, "Script"));801}802}803} else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {804const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);805String script_path;806if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {807// Try to get script from scene if possible.808if (GDScriptLanguage::get_singleton()->has_any_global_constant(autoload.name)) {809Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(autoload.name);810Node *node = Object::cast_to<Node>(constant);811if (node != nullptr) {812Ref<GDScript> scr = node->get_script();813if (scr.is_valid()) {814script_path = scr->get_script_path();815}816}817}818} else if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {819script_path = autoload.path;820}821if (script_path.is_empty()) {822return bad_type;823}824Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(script_path);825if (ref.is_null()) {826push_error(vformat(R"(The referenced autoload "%s" (from "%s") could not be loaded.)", first, script_path), p_type);827return bad_type;828}829if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {830push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, script_path), p_type);831return bad_type;832}833result = ref->get_parser()->head->get_datatype();834} else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) {835// Native enum in current class.836result = make_native_enum_type(first, parser->current_class->base_type.native_type);837} else if (CoreConstants::is_global_enum(first)) {838if (p_type->type_chain.size() > 1) {839push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[1]);840return bad_type;841}842result = make_global_enum_type(first, StringName());843} else {844// Classes in current scope.845List<GDScriptParser::ClassNode *> script_classes;846bool found = false;847get_class_node_current_scope_classes(parser->current_class, &script_classes, p_type);848for (GDScriptParser::ClassNode *script_class : script_classes) {849if (found) {850break;851}852853if (script_class->identifier && script_class->identifier->name == first) {854result = script_class->get_datatype();855break;856}857if (script_class->members_indices.has(first)) {858resolve_class_member(script_class, first, p_type);859860GDScriptParser::ClassNode::Member member = script_class->get_member(first);861switch (member.type) {862case GDScriptParser::ClassNode::Member::CLASS:863result = member.get_datatype();864found = true;865break;866case GDScriptParser::ClassNode::Member::ENUM:867result = member.get_datatype();868found = true;869break;870case GDScriptParser::ClassNode::Member::CONSTANT:871if (member.get_datatype().is_meta_type) {872result = member.get_datatype();873found = true;874break;875} else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) {876Ref<GDScript> gdscript = member.constant->initializer->reduced_value;877if (gdscript.is_valid()) {878Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(gdscript->get_script_path());879if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {880push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type);881return bad_type;882}883result = ref->get_parser()->head->get_datatype();884} else {885result = make_script_meta_type(member.constant->initializer->reduced_value);886}887found = true;888break;889}890[[fallthrough]];891default:892push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);893return bad_type;894}895}896}897}898}899900if (!result.is_set()) {901push_error(vformat(R"(Could not find type "%s" in the current scope.)", first), p_type);902return bad_type;903}904905if (p_type->type_chain.size() > 1) {906if (result.kind == GDScriptParser::DataType::CLASS) {907for (int i = 1; i < p_type->type_chain.size(); i++) {908GDScriptParser::DataType base = result;909reduce_identifier_from_base(p_type->type_chain[i], &base);910result = p_type->type_chain[i]->get_datatype();911if (!result.is_set()) {912push_error(vformat(R"(Could not find type "%s" under base "%s".)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);913return bad_type;914} else if (!result.is_meta_type) {915push_error(vformat(R"(Member "%s" under base "%s" is not a valid type.)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);916return bad_type;917}918}919} else if (result.kind == GDScriptParser::DataType::NATIVE) {920// Only enums allowed for native.921if (ClassDB::has_enum(result.native_type, p_type->type_chain[1]->name)) {922if (p_type->type_chain.size() > 2) {923push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);924return bad_type;925} else {926result = make_native_enum_type(p_type->type_chain[1]->name, result.native_type);927}928} else {929push_error(vformat(R"(Could not find type "%s" in "%s".)", p_type->type_chain[1]->name, first), p_type->type_chain[1]);930return bad_type;931}932} else {933push_error(vformat(R"(Could not find nested type "%s" under base "%s".)", p_type->type_chain[1]->name, result.to_string()), p_type->type_chain[1]);934return bad_type;935}936}937938if (!p_type->container_types.is_empty()) {939if (result.builtin_type == Variant::ARRAY) {940if (p_type->container_types.size() != 1) {941push_error(R"(Typed arrays require exactly one collection element type.)", p_type);942return bad_type;943}944} else if (result.builtin_type == Variant::DICTIONARY) {945if (p_type->container_types.size() != 2) {946push_error(R"(Typed dictionaries require exactly two collection element types.)", p_type);947return bad_type;948}949} else {950push_error(R"(Only arrays and dictionaries can specify collection element types.)", p_type);951return bad_type;952}953}954955p_type->set_datatype(result);956return result;957}958959void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, const StringName &p_name, const GDScriptParser::Node *p_source) {960ERR_FAIL_COND(!p_class->has_member(p_name));961resolve_class_member(p_class, p_class->members_indices[p_name], p_source);962}963964void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, int p_index, const GDScriptParser::Node *p_source) {965ERR_FAIL_INDEX(p_index, p_class->members.size());966967GDScriptParser::ClassNode::Member &member = p_class->members.write[p_index];968if (p_source == nullptr && parser->has_class(p_class)) {969p_source = member.get_source_node();970}971972Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class member", p_source);973Finally finally([&]() {974ensure_cached_external_parser_for_class(member.get_datatype().class_type, p_class, "Trying to resolve datatype of class member", p_source);975GDScriptParser::DataType member_type = member.get_datatype();976for (int i = 0; i < member_type.get_container_element_type_count(); ++i) {977ensure_cached_external_parser_for_class(member_type.get_container_element_type(i).class_type, p_class, "Trying to resolve datatype of class member", p_source);978}979});980981if (member.get_datatype().is_resolving()) {982push_error(vformat(R"(Could not resolve member "%s": Cyclic reference.)", member.get_name()), p_source);983return;984}985986if (member.get_datatype().is_set()) {987return;988}989990// If it's already resolving, that's ok.991if (!p_class->base_type.is_resolving()) {992Error err = resolve_class_inheritance(p_class);993if (err) {994return;995}996}997998if (!parser->has_class(p_class)) {999if (parser_ref.is_null()) {1000// Error already pushed.1001return;1002}10031004Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);1005if (err) {1006push_error(vformat(R"(Could not parse script "%s": %s (While resolving external class member "%s").)", p_class->get_datatype().script_path, error_names[err], member.get_name()), p_source);1007return;1008}10091010GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();1011GDScriptParser *other_parser = parser_ref->get_parser();10121013int error_count = other_parser->errors.size();1014other_analyzer->resolve_class_member(p_class, p_index);1015if (other_parser->errors.size() > error_count) {1016push_error(vformat(R"(Could not resolve external class member "%s".)", member.get_name()), p_source);1017return;1018}10191020return;1021}10221023GDScriptParser::ClassNode *previous_class = parser->current_class;1024parser->current_class = p_class;10251026GDScriptParser::DataType resolving_datatype;1027resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;10281029{1030#ifdef DEBUG_ENABLED1031GDScriptParser::Node *member_node = member.get_source_node();1032if (member_node && member_node->type != GDScriptParser::Node::ANNOTATION) {1033// Apply @warning_ignore annotations before resolving member.1034for (GDScriptParser::AnnotationNode *&E : member_node->annotations) {1035if (E->name == SNAME("@warning_ignore")) {1036resolve_annotation(E);1037E->apply(parser, member.variable, p_class);1038}1039}1040}1041#endif // DEBUG_ENABLED1042switch (member.type) {1043case GDScriptParser::ClassNode::Member::VARIABLE: {1044bool previous_static_context = static_context;1045static_context = member.variable->is_static;10461047check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable);10481049member.variable->set_datatype(resolving_datatype);1050resolve_variable(member.variable, false);1051resolve_pending_lambda_bodies();10521053// Apply annotations.1054for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) {1055if (E->name != SNAME("@warning_ignore")) {1056resolve_annotation(E);1057E->apply(parser, member.variable, p_class);1058}1059}10601061static_context = previous_static_context;10621063#ifdef DEBUG_ENABLED1064if (member.variable->exported && member.variable->onready) {1065parser->push_warning(member.variable, GDScriptWarning::ONREADY_WITH_EXPORT);1066}1067if (member.variable->initializer) {1068// Check if it is call to get_node() on self (using shorthand $ or not), so we can check if @onready is needed.1069// This could be improved by traversing the expression fully and checking the presence of get_node at any level.1070if (!member.variable->is_static && !member.variable->onready && member.variable->initializer && (member.variable->initializer->type == GDScriptParser::Node::GET_NODE || member.variable->initializer->type == GDScriptParser::Node::CALL || member.variable->initializer->type == GDScriptParser::Node::CAST)) {1071GDScriptParser::Node *expr = member.variable->initializer;1072if (expr->type == GDScriptParser::Node::CAST) {1073expr = static_cast<GDScriptParser::CastNode *>(expr)->operand;1074}1075bool is_get_node = expr->type == GDScriptParser::Node::GET_NODE;1076bool is_using_shorthand = is_get_node;1077if (!is_get_node && expr->type == GDScriptParser::Node::CALL) {1078is_using_shorthand = false;1079GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(expr);1080if (call->function_name == SNAME("get_node")) {1081switch (call->get_callee_type()) {1082case GDScriptParser::Node::IDENTIFIER: {1083is_get_node = true;1084} break;1085case GDScriptParser::Node::SUBSCRIPT: {1086GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(call->callee);1087is_get_node = subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF;1088} break;1089default:1090break;1091}1092}1093}1094if (is_get_node) {1095String offending_syntax = "get_node()";1096if (is_using_shorthand) {1097GDScriptParser::GetNodeNode *get_node_node = static_cast<GDScriptParser::GetNodeNode *>(expr);1098offending_syntax = get_node_node->use_dollar ? "$" : "%";1099}1100parser->push_warning(member.variable, GDScriptWarning::GET_NODE_DEFAULT_WITHOUT_ONREADY, offending_syntax);1101}1102}1103}1104#endif // DEBUG_ENABLED1105} break;1106case GDScriptParser::ClassNode::Member::CONSTANT: {1107check_class_member_name_conflict(p_class, member.constant->identifier->name, member.constant);1108member.constant->set_datatype(resolving_datatype);1109resolve_constant(member.constant, false);11101111// Apply annotations.1112for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) {1113resolve_annotation(E);1114E->apply(parser, member.constant, p_class);1115}1116} break;1117case GDScriptParser::ClassNode::Member::SIGNAL: {1118check_class_member_name_conflict(p_class, member.signal->identifier->name, member.signal);11191120member.signal->set_datatype(resolving_datatype);11211122// This is the _only_ way to declare a signal. Therefore, we can generate its1123// MethodInfo inline so it's a tiny bit more efficient.1124MethodInfo mi = MethodInfo(member.signal->identifier->name);11251126for (int j = 0; j < member.signal->parameters.size(); j++) {1127GDScriptParser::ParameterNode *param = member.signal->parameters[j];1128GDScriptParser::DataType param_type = type_from_metatype(resolve_datatype(param->datatype_specifier));1129param->set_datatype(param_type);1130#ifdef DEBUG_ENABLED1131if (param->datatype_specifier == nullptr) {1132parser->push_warning(param, GDScriptWarning::UNTYPED_DECLARATION, "Parameter", param->identifier->name);1133}1134#endif // DEBUG_ENABLED1135mi.arguments.push_back(param_type.to_property_info(param->identifier->name));1136// Signals do not support parameter default values.1137}1138member.signal->set_datatype(make_signal_type(mi));1139member.signal->method_info = mi;11401141// Apply annotations.1142for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) {1143resolve_annotation(E);1144E->apply(parser, member.signal, p_class);1145}1146} break;1147case GDScriptParser::ClassNode::Member::ENUM: {1148check_class_member_name_conflict(p_class, member.m_enum->identifier->name, member.m_enum);11491150member.m_enum->set_datatype(resolving_datatype);1151GDScriptParser::DataType enum_type = make_class_enum_type(member.m_enum->identifier->name, p_class, parser->script_path, true);11521153const GDScriptParser::EnumNode *prev_enum = current_enum;1154current_enum = member.m_enum;11551156Dictionary dictionary;1157for (int j = 0; j < member.m_enum->values.size(); j++) {1158GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];11591160if (element.custom_value) {1161reduce_expression(element.custom_value);1162if (!element.custom_value->is_constant) {1163push_error(R"(Enum values must be constant.)", element.custom_value);1164} else if (element.custom_value->reduced_value.get_type() != Variant::INT) {1165push_error(R"(Enum values must be integers.)", element.custom_value);1166} else {1167element.value = element.custom_value->reduced_value;1168element.resolved = true;1169}1170} else {1171if (element.index > 0) {1172element.value = element.parent_enum->values[element.index - 1].value + 1;1173} else {1174element.value = 0;1175}1176element.resolved = true;1177}11781179enum_type.enum_values[element.identifier->name] = element.value;1180dictionary[String(element.identifier->name)] = element.value;11811182#ifdef DEBUG_ENABLED1183// Named enum identifiers do not shadow anything since you can only access them with `NamedEnum.ENUM_VALUE`.1184if (member.m_enum->identifier->name == StringName()) {1185is_shadowing(element.identifier, "enum member", false);1186}1187#endif // DEBUG_ENABLED1188}11891190current_enum = prev_enum;11911192dictionary.make_read_only();1193member.m_enum->set_datatype(enum_type);1194member.m_enum->dictionary = dictionary;11951196// Apply annotations.1197for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {1198resolve_annotation(E);1199E->apply(parser, member.m_enum, p_class);1200}1201} break;1202case GDScriptParser::ClassNode::Member::FUNCTION:1203for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {1204resolve_annotation(E);1205E->apply(parser, member.function, p_class);1206}1207resolve_function_signature(member.function, p_source);1208break;1209case GDScriptParser::ClassNode::Member::ENUM_VALUE: {1210member.enum_value.identifier->set_datatype(resolving_datatype);12111212if (member.enum_value.custom_value) {1213check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);12141215const GDScriptParser::EnumNode *prev_enum = current_enum;1216current_enum = member.enum_value.parent_enum;1217reduce_expression(member.enum_value.custom_value);1218current_enum = prev_enum;12191220if (!member.enum_value.custom_value->is_constant) {1221push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);1222} else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {1223push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);1224} else {1225member.enum_value.value = member.enum_value.custom_value->reduced_value;1226member.enum_value.resolved = true;1227}1228} else {1229check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);12301231if (member.enum_value.index > 0) {1232const GDScriptParser::EnumNode::Value &prev_value = member.enum_value.parent_enum->values[member.enum_value.index - 1];1233resolve_class_member(p_class, prev_value.identifier->name, member.enum_value.identifier);1234member.enum_value.value = prev_value.value + 1;1235} else {1236member.enum_value.value = 0;1237}1238member.enum_value.resolved = true;1239}12401241// Also update the original references.1242member.enum_value.parent_enum->values.set(member.enum_value.index, member.enum_value);12431244member.enum_value.identifier->set_datatype(make_class_enum_type(UNNAMED_ENUM, p_class, parser->script_path, false));1245} break;1246case GDScriptParser::ClassNode::Member::CLASS:1247check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);1248// If it's already resolving, that's ok.1249if (!member.m_class->base_type.is_resolving()) {1250resolve_class_inheritance(member.m_class, p_source);1251}1252break;1253case GDScriptParser::ClassNode::Member::GROUP:1254// No-op, but needed to silence warnings.1255break;1256case GDScriptParser::ClassNode::Member::UNDEFINED:1257ERR_PRINT("Trying to resolve undefined member.");1258break;1259}1260}12611262parser->current_class = previous_class;1263}12641265void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {1266if (p_source == nullptr && parser->has_class(p_class)) {1267p_source = p_class;1268}12691270Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class interface", p_source);12711272if (!p_class->resolved_interface) {1273#ifdef DEBUG_ENABLED1274bool has_static_data = p_class->has_static_data;1275#endif // DEBUG_ENABLED12761277if (!parser->has_class(p_class)) {1278if (parser_ref.is_null()) {1279// Error already pushed.1280return;1281}12821283Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);1284if (err) {1285push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);1286return;1287}12881289GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();1290GDScriptParser *other_parser = parser_ref->get_parser();12911292int error_count = other_parser->errors.size();1293other_analyzer->resolve_class_interface(p_class);1294if (other_parser->errors.size() > error_count) {1295push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);1296return;1297}12981299return;1300}13011302p_class->resolved_interface = true;13031304if (resolve_class_inheritance(p_class) != OK) {1305return;1306}13071308GDScriptParser::DataType base_type = p_class->base_type;1309if (base_type.kind == GDScriptParser::DataType::CLASS) {1310GDScriptParser::ClassNode *base_class = base_type.class_type;1311resolve_class_interface(base_class, p_class);1312}13131314for (int i = 0; i < p_class->members.size(); i++) {1315resolve_class_member(p_class, i);13161317#ifdef DEBUG_ENABLED1318if (!has_static_data) {1319GDScriptParser::ClassNode::Member member = p_class->members[i];1320if (member.type == GDScriptParser::ClassNode::Member::CLASS) {1321has_static_data = member.m_class->has_static_data;1322}1323}1324#endif // DEBUG_ENABLED1325}13261327#ifdef DEBUG_ENABLED1328if (!has_static_data && p_class->annotated_static_unload) {1329GDScriptParser::Node *static_unload = nullptr;1330for (GDScriptParser::AnnotationNode *node : p_class->annotations) {1331if (node->name == "@static_unload") {1332static_unload = node;1333break;1334}1335}1336parser->push_warning(static_unload ? static_unload : p_class, GDScriptWarning::REDUNDANT_STATIC_UNLOAD);1337}1338#endif // DEBUG_ENABLED1339}1340}13411342void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, bool p_recursive) {1343resolve_class_interface(p_class);13441345if (p_recursive) {1346for (int i = 0; i < p_class->members.size(); i++) {1347GDScriptParser::ClassNode::Member member = p_class->members[i];1348if (member.type == GDScriptParser::ClassNode::Member::CLASS) {1349resolve_class_interface(member.m_class, true);1350}1351}1352}1353}13541355void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {1356if (p_source == nullptr && parser->has_class(p_class)) {1357p_source = p_class;1358}13591360Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class body", p_source);13611362if (p_class->resolved_body) {1363return;1364}13651366if (!parser->has_class(p_class)) {1367if (parser_ref.is_null()) {1368// Error already pushed.1369return;1370}13711372Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);1373if (err) {1374push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);1375return;1376}13771378GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();1379GDScriptParser *other_parser = parser_ref->get_parser();13801381int error_count = other_parser->errors.size();1382other_analyzer->resolve_class_body(p_class);1383if (other_parser->errors.size() > error_count) {1384push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);1385return;1386}13871388return;1389}13901391p_class->resolved_body = true;13921393GDScriptParser::ClassNode *previous_class = parser->current_class;1394parser->current_class = p_class;13951396resolve_class_interface(p_class, p_source);13971398GDScriptParser::DataType base_type = p_class->base_type;1399if (base_type.kind == GDScriptParser::DataType::CLASS) {1400GDScriptParser::ClassNode *base_class = base_type.class_type;1401resolve_class_body(base_class, p_class);1402}14031404// Do functions, properties, and groups now.1405for (int i = 0; i < p_class->members.size(); i++) {1406GDScriptParser::ClassNode::Member member = p_class->members[i];1407if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {1408// Apply annotations.1409for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {1410resolve_annotation(E);1411E->apply(parser, member.function, p_class);1412}1413resolve_function_body(member.function);1414} else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE && member.variable->property != GDScriptParser::VariableNode::PROP_NONE) {1415if (member.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {1416if (member.variable->getter != nullptr) {1417member.variable->getter->return_type = member.variable->datatype_specifier;1418member.variable->getter->set_datatype(member.get_datatype());14191420resolve_function_body(member.variable->getter);1421}1422if (member.variable->setter != nullptr) {1423ERR_CONTINUE(member.variable->setter->parameters.is_empty());1424member.variable->setter->parameters[0]->datatype_specifier = member.variable->datatype_specifier;1425member.variable->setter->parameters[0]->set_datatype(member.get_datatype());14261427resolve_function_body(member.variable->setter);1428}1429}1430} else if (member.type == GDScriptParser::ClassNode::Member::GROUP) {1431// Apply annotation (`@export_{category,group,subgroup}`).1432resolve_annotation(member.annotation);1433member.annotation->apply(parser, nullptr, p_class);1434}1435}14361437// Check unused variables and datatypes of property getters and setters.1438for (int i = 0; i < p_class->members.size(); i++) {1439GDScriptParser::ClassNode::Member member = p_class->members[i];1440if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {1441#ifdef DEBUG_ENABLED1442if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {1443parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);1444}1445#endif // DEBUG_ENABLED14461447if (member.variable->property == GDScriptParser::VariableNode::PROP_SETGET) {1448GDScriptParser::FunctionNode *getter_function = nullptr;1449GDScriptParser::FunctionNode *setter_function = nullptr;14501451bool has_valid_getter = false;1452bool has_valid_setter = false;14531454if (member.variable->getter_pointer != nullptr) {1455if (p_class->has_function(member.variable->getter_pointer->name)) {1456getter_function = p_class->get_member(member.variable->getter_pointer->name).function;1457}14581459if (getter_function == nullptr) {1460push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable);1461} else {1462GDScriptParser::DataType return_datatype = getter_function->datatype;1463if (getter_function->return_type != nullptr) {1464return_datatype = getter_function->return_type->datatype;1465return_datatype.is_meta_type = false;1466}14671468if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) {1469push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable);1470} else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) {1471push_error(vformat(R"(Function with return type "%s" cannot be used as getter for a property of type "%s".)", return_datatype.to_string(), member.variable->datatype.to_string()), member.variable);14721473} else {1474has_valid_getter = true;1475#ifdef DEBUG_ENABLED1476if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) {1477parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);1478}1479#endif // DEBUG_ENABLED1480}1481}1482}14831484if (member.variable->setter_pointer != nullptr) {1485if (p_class->has_function(member.variable->setter_pointer->name)) {1486setter_function = p_class->get_member(member.variable->setter_pointer->name).function;1487}14881489if (setter_function == nullptr) {1490push_error(vformat(R"(Setter "%s" not found.)", member.variable->setter_pointer->name), member.variable);14911492} else if (setter_function->parameters.size() != 1) {1493push_error(vformat(R"(Function "%s" cannot be used as setter because of its signature.)", setter_function->identifier->name), member.variable);14941495} else if (!is_type_compatible(member.variable->datatype, setter_function->parameters[0]->datatype, true)) {1496push_error(vformat(R"(Function with argument type "%s" cannot be used as setter for a property of type "%s".)", setter_function->parameters[0]->datatype.to_string(), member.variable->datatype.to_string()), member.variable);14971498} else {1499has_valid_setter = true;15001501#ifdef DEBUG_ENABLED1502if (member.variable->datatype.builtin_type == Variant::FLOAT && setter_function->parameters[0]->datatype.builtin_type == Variant::INT) {1503parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);1504}1505#endif // DEBUG_ENABLED1506}1507}15081509if (member.variable->datatype.is_variant() && has_valid_getter && has_valid_setter) {1510if (!is_type_compatible(getter_function->datatype, setter_function->parameters[0]->datatype, true)) {1511push_error(vformat(R"(Getter with type "%s" cannot be used along with setter of type "%s".)", getter_function->datatype.to_string(), setter_function->parameters[0]->datatype.to_string()), member.variable);1512}1513}1514}1515} else if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {1516#ifdef DEBUG_ENABLED1517if (member.signal->usages == 0) {1518parser->push_warning(member.signal->identifier, GDScriptWarning::UNUSED_SIGNAL, member.signal->identifier->name);1519}1520#endif // DEBUG_ENABLED1521}1522}15231524if (!pending_body_resolution_lambdas.is_empty()) {1525ERR_PRINT("GDScript bug (please report): Not all pending lambda bodies were resolved in time.");1526resolve_pending_lambda_bodies();1527}15281529// Resolve base abstract class/method implementation requirements.1530if (!p_class->is_abstract) {1531HashSet<StringName> implemented_funcs;1532const GDScriptParser::ClassNode *base_class = p_class;1533while (base_class != nullptr) {1534if (!base_class->is_abstract && base_class != p_class) {1535break;1536}1537for (GDScriptParser::ClassNode::Member member : base_class->members) {1538if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {1539if (member.function->is_abstract) {1540if (base_class == p_class) {1541const String class_name = p_class->identifier == nullptr ? p_class->fqcn.get_file() : String(p_class->identifier->name);1542push_error(vformat(R"*(Class "%s" is not abstract but contains abstract methods. Mark the class as "@abstract" or remove "@abstract" from all methods in this class.)*", class_name), p_class);1543break;1544} else if (!implemented_funcs.has(member.function->identifier->name)) {1545const String class_name = p_class->identifier == nullptr ? p_class->fqcn.get_file() : String(p_class->identifier->name);1546const String base_class_name = base_class->identifier == nullptr ? base_class->fqcn.get_file() : String(base_class->identifier->name);1547push_error(vformat(R"*(Class "%s" must implement "%s.%s()" and other inherited abstract methods or be marked as "@abstract".)*", class_name, base_class_name, member.function->identifier->name), p_class);1548break;1549}1550} else {1551implemented_funcs.insert(member.function->identifier->name);1552}1553}1554}1555if (base_class->base_type.kind == GDScriptParser::DataType::CLASS) {1556base_class = base_class->base_type.class_type;1557} else if (base_class->base_type.kind == GDScriptParser::DataType::SCRIPT) {1558Ref<GDScriptParserRef> base_parser_ref = parser->get_depended_parser_for(base_class->base_type.script_path);1559ERR_BREAK(base_parser_ref.is_null());1560base_class = base_parser_ref->get_parser()->head;1561} else {1562break;1563}1564}1565}15661567parser->current_class = previous_class;1568}15691570void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, bool p_recursive) {1571resolve_class_body(p_class);15721573if (p_recursive) {1574for (int i = 0; i < p_class->members.size(); i++) {1575GDScriptParser::ClassNode::Member member = p_class->members[i];1576if (member.type == GDScriptParser::ClassNode::Member::CLASS) {1577resolve_class_body(member.m_class, true);1578}1579}1580}1581}15821583void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {1584ERR_FAIL_NULL_MSG(p_node, "Trying to resolve type of a null node.");15851586switch (p_node->type) {1587case GDScriptParser::Node::NONE:1588break; // Unreachable.1589case GDScriptParser::Node::CLASS:1590// NOTE: Currently this route is never executed, `resolve_class_*()` is called directly.1591if (OK == resolve_class_inheritance(static_cast<GDScriptParser::ClassNode *>(p_node), true)) {1592resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node), true);1593resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node), true);1594}1595break;1596case GDScriptParser::Node::CONSTANT:1597resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node), true);1598break;1599case GDScriptParser::Node::FOR:1600resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));1601break;1602case GDScriptParser::Node::IF:1603resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));1604break;1605case GDScriptParser::Node::SUITE:1606resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));1607break;1608case GDScriptParser::Node::VARIABLE:1609resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node), true);1610break;1611case GDScriptParser::Node::WHILE:1612resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));1613break;1614case GDScriptParser::Node::ANNOTATION:1615resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));1616break;1617case GDScriptParser::Node::ASSERT:1618resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));1619break;1620case GDScriptParser::Node::MATCH:1621resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));1622break;1623case GDScriptParser::Node::MATCH_BRANCH:1624resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);1625break;1626case GDScriptParser::Node::PARAMETER:1627resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));1628break;1629case GDScriptParser::Node::PATTERN:1630resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);1631break;1632case GDScriptParser::Node::RETURN:1633resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));1634break;1635case GDScriptParser::Node::TYPE:1636resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));1637break;1638// Resolving expression is the same as reducing them.1639case GDScriptParser::Node::ARRAY:1640case GDScriptParser::Node::ASSIGNMENT:1641case GDScriptParser::Node::AWAIT:1642case GDScriptParser::Node::BINARY_OPERATOR:1643case GDScriptParser::Node::CALL:1644case GDScriptParser::Node::CAST:1645case GDScriptParser::Node::DICTIONARY:1646case GDScriptParser::Node::GET_NODE:1647case GDScriptParser::Node::IDENTIFIER:1648case GDScriptParser::Node::LAMBDA:1649case GDScriptParser::Node::LITERAL:1650case GDScriptParser::Node::PRELOAD:1651case GDScriptParser::Node::SELF:1652case GDScriptParser::Node::SUBSCRIPT:1653case GDScriptParser::Node::TERNARY_OPERATOR:1654case GDScriptParser::Node::TYPE_TEST:1655case GDScriptParser::Node::UNARY_OPERATOR:1656reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);1657break;1658case GDScriptParser::Node::BREAK:1659case GDScriptParser::Node::BREAKPOINT:1660case GDScriptParser::Node::CONTINUE:1661case GDScriptParser::Node::ENUM:1662case GDScriptParser::Node::FUNCTION:1663case GDScriptParser::Node::PASS:1664case GDScriptParser::Node::SIGNAL:1665// Nothing to do.1666break;1667}1668}16691670void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {1671ERR_FAIL_COND_MSG(!parser->valid_annotations.has(p_annotation->name), vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));16721673if (p_annotation->is_resolved) {1674return;1675}1676p_annotation->is_resolved = true;16771678const MethodInfo &annotation_info = parser->valid_annotations[p_annotation->name].info;16791680for (int64_t i = 0, j = 0; i < p_annotation->arguments.size(); i++) {1681GDScriptParser::ExpressionNode *argument = p_annotation->arguments[i];1682const PropertyInfo &argument_info = annotation_info.arguments[j];16831684if (j + 1 < annotation_info.arguments.size()) {1685++j;1686}16871688reduce_expression(argument);16891690if (!argument->is_constant) {1691push_error(vformat(R"(Argument %d of annotation "%s" isn't a constant expression.)", i + 1, p_annotation->name), argument);1692return;1693}16941695Variant value = argument->reduced_value;16961697if (value.get_type() != argument_info.type) {1698#ifdef DEBUG_ENABLED1699if (argument_info.type == Variant::INT && value.get_type() == Variant::FLOAT) {1700parser->push_warning(argument, GDScriptWarning::NARROWING_CONVERSION);1701}1702#endif // DEBUG_ENABLED17031704if (!Variant::can_convert_strict(value.get_type(), argument_info.type)) {1705push_error(vformat(R"(Invalid argument for annotation "%s": argument %d should be "%s" but is "%s".)", p_annotation->name, i + 1, Variant::get_type_name(argument_info.type), argument->get_datatype().to_string()), argument);1706return;1707}17081709Variant converted_to;1710const Variant *converted_from = &value;1711Callable::CallError call_error;1712Variant::construct(argument_info.type, converted_to, &converted_from, 1, call_error);17131714if (call_error.error != Callable::CallError::CALL_OK) {1715push_error(vformat(R"(Cannot convert argument %d of annotation "%s" from "%s" to "%s".)", i + 1, p_annotation->name, Variant::get_type_name(value.get_type()), Variant::get_type_name(argument_info.type)), argument);1716return;1717}17181719value = converted_to;1720}17211722p_annotation->resolved_arguments.push_back(value);1723}1724}17251726void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function, const GDScriptParser::Node *p_source, bool p_is_lambda) {1727if (p_source == nullptr) {1728p_source = p_function;1729}17301731StringName function_name = p_function->identifier != nullptr ? p_function->identifier->name : StringName();17321733if (p_function->get_datatype().is_resolving()) {1734push_error(vformat(R"(Could not resolve function "%s": Cyclic reference.)", function_name), p_source);1735return;1736}17371738if (p_function->resolved_signature) {1739return;1740}1741p_function->resolved_signature = true;17421743GDScriptParser::FunctionNode *previous_function = parser->current_function;1744parser->current_function = p_function;1745bool previous_static_context = static_context;1746if (p_is_lambda) {1747// For lambdas this is determined from the context, the `static` keyword is not allowed.1748p_function->is_static = static_context;1749} else {1750// For normal functions, this is determined in the parser by the `static` keyword.1751static_context = p_function->is_static;1752}17531754MethodInfo method_info;1755method_info.name = function_name;1756if (p_function->is_static) {1757method_info.flags |= MethodFlags::METHOD_FLAG_STATIC;1758}17591760GDScriptParser::DataType prev_datatype = p_function->get_datatype();17611762GDScriptParser::DataType resolving_datatype;1763resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;1764p_function->set_datatype(resolving_datatype);17651766#ifdef TOOLS_ENABLED1767int default_value_count = 0;1768#endif // TOOLS_ENABLED17691770#ifdef DEBUG_ENABLED1771String function_visible_name = function_name;1772if (function_name == StringName()) {1773function_visible_name = p_is_lambda ? "<anonymous lambda>" : "<unknown function>";1774}1775#endif // DEBUG_ENABLED17761777for (int i = 0; i < p_function->parameters.size(); i++) {1778resolve_parameter(p_function->parameters[i]);1779method_info.arguments.push_back(p_function->parameters[i]->get_datatype().to_property_info(p_function->parameters[i]->identifier->name));1780#ifdef DEBUG_ENABLED1781if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_") && !p_function->is_abstract) {1782parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, function_visible_name, p_function->parameters[i]->identifier->name);1783}1784is_shadowing(p_function->parameters[i]->identifier, "function parameter", true);1785#endif // DEBUG_ENABLED17861787if (p_function->parameters[i]->initializer) {1788#ifdef TOOLS_ENABLED1789default_value_count++;1790#endif // TOOLS_ENABLED17911792if (p_function->parameters[i]->initializer->is_constant) {1793p_function->default_arg_values.push_back(p_function->parameters[i]->initializer->reduced_value);1794} else {1795p_function->default_arg_values.push_back(Variant()); // Prevent shift.1796}1797}1798}17991800if (p_function->is_vararg()) {1801resolve_parameter(p_function->rest_parameter);1802if (p_function->rest_parameter->datatype_specifier != nullptr) {1803GDScriptParser::DataType specified_type = p_function->rest_parameter->get_datatype();1804if (specified_type.kind != GDScriptParser::DataType::BUILTIN || specified_type.builtin_type != Variant::ARRAY) {1805push_error(vformat(R"(The rest parameter type must be "Array", but "%s" is specified.)", specified_type.to_string()), p_function->rest_parameter->datatype_specifier);1806} else if ((specified_type.has_container_element_type(0) && !specified_type.get_container_element_type(0).is_variant())) {1807push_error(R"(Typed arrays are currently not supported for the rest parameter.)", p_function->rest_parameter->datatype_specifier);1808}1809} else {1810GDScriptParser::DataType inferred_type;1811inferred_type.type_source = GDScriptParser::DataType::INFERRED;1812inferred_type.kind = GDScriptParser::DataType::BUILTIN;1813inferred_type.builtin_type = Variant::ARRAY;1814p_function->rest_parameter->set_datatype(inferred_type);1815#ifdef DEBUG_ENABLED1816parser->push_warning(p_function->rest_parameter, GDScriptWarning::UNTYPED_DECLARATION, "Parameter", p_function->rest_parameter->identifier->name);1817#endif1818}1819#ifdef DEBUG_ENABLED1820if (p_function->rest_parameter->usages == 0 && !String(p_function->rest_parameter->identifier->name).begins_with("_") && !p_function->is_abstract) {1821parser->push_warning(p_function->rest_parameter->identifier, GDScriptWarning::UNUSED_PARAMETER, function_visible_name, p_function->rest_parameter->identifier->name);1822}1823is_shadowing(p_function->rest_parameter->identifier, "function parameter", true);1824#endif // DEBUG_ENABLED1825}18261827if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._init) {1828// Constructor.1829GDScriptParser::DataType return_type = parser->current_class->get_datatype();1830return_type.is_meta_type = false;1831p_function->set_datatype(return_type);1832if (p_function->return_type) {1833GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);1834if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {1835push_error("Constructor cannot have an explicit return type.", p_function->return_type);1836}1837}1838} else if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._static_init) {1839// Static constructor.1840GDScriptParser::DataType return_type;1841return_type.kind = GDScriptParser::DataType::BUILTIN;1842return_type.builtin_type = Variant::NIL;1843p_function->set_datatype(return_type);1844if (p_function->return_type) {1845GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);1846if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {1847push_error("Static constructor cannot have an explicit return type.", p_function->return_type);1848}1849}1850} else {1851if (p_function->return_type != nullptr) {1852p_function->set_datatype(type_from_metatype(resolve_datatype(p_function->return_type)));1853} else {1854// In case the function is not typed, we can safely assume it's a Variant, so it's okay to mark as "inferred" here.1855// It's not "undetected" to not mix up with unknown functions.1856GDScriptParser::DataType return_type;1857return_type.type_source = GDScriptParser::DataType::INFERRED;1858return_type.kind = GDScriptParser::DataType::VARIANT;1859p_function->set_datatype(return_type);1860}18611862#ifdef TOOLS_ENABLED1863// Check if the function signature matches the parent. If not it's an error since it breaks polymorphism.1864// Not for the constructor which can vary in signature.1865GDScriptParser::DataType base_type = parser->current_class->base_type;1866base_type.is_meta_type = false;1867GDScriptParser::DataType parent_return_type;1868List<GDScriptParser::DataType> parameters_types;1869int default_par_count = 0;1870BitField<MethodFlags> method_flags = {};1871StringName native_base;1872if (!p_is_lambda && get_function_signature(p_function, false, base_type, function_name, parent_return_type, parameters_types, default_par_count, method_flags, &native_base)) {1873bool valid = p_function->is_static == method_flags.has_flag(METHOD_FLAG_STATIC);18741875if (p_function->return_type != nullptr) {1876// Check return type covariance.1877GDScriptParser::DataType return_type = p_function->get_datatype();1878if (return_type.is_variant()) {1879// `is_type_compatible()` returns `true` if one of the types is `Variant`.1880// Don't allow an explicitly specified `Variant` if the parent return type is narrower.1881valid = valid && parent_return_type.is_variant();1882} else if (return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {1883// `is_type_compatible()` returns `true` if target is an `Object` and source is `null`.1884// Don't allow `void` if the parent return type is a hard non-`void` type.1885if (parent_return_type.is_hard_type() && !(parent_return_type.kind == GDScriptParser::DataType::BUILTIN && parent_return_type.builtin_type == Variant::NIL)) {1886valid = false;1887}1888} else {1889valid = valid && is_type_compatible(parent_return_type, return_type);1890}1891}18921893int parent_min_argc = parameters_types.size() - default_par_count;1894int parent_max_argc = (method_flags & METHOD_FLAG_VARARG) ? INT_MAX : parameters_types.size();1895int current_min_argc = p_function->parameters.size() - default_value_count;1896int current_max_argc = p_function->is_vararg() ? INT_MAX : p_function->parameters.size();18971898// `[current_min_argc..current_max_argc]` must include `[parent_min_argc..parent_max_argc]`.1899valid = valid && current_min_argc <= parent_min_argc && parent_max_argc <= current_max_argc;19001901if (valid) {1902int i = 0;1903for (const GDScriptParser::DataType &parent_par_type : parameters_types) {1904if (i >= p_function->parameters.size()) {1905break;1906}1907const GDScriptParser::DataType ¤t_par_type = p_function->parameters[i]->datatype;1908i++;1909// Check parameter type contravariance.1910if (parent_par_type.is_variant() && parent_par_type.is_hard_type()) {1911// `is_type_compatible()` returns `true` if one of the types is `Variant`.1912// Don't allow narrowing a hard `Variant`.1913valid = valid && current_par_type.is_variant();1914} else {1915valid = valid && is_type_compatible(current_par_type, parent_par_type);1916}1917}1918}19191920if (!valid) {1921// Compute parent signature as a string to show in the error message.1922String parent_signature = String(function_name) + "(";1923int j = 0;1924for (const GDScriptParser::DataType &par_type : parameters_types) {1925if (j > 0) {1926parent_signature += ", ";1927}1928String parameter = par_type.to_string();1929if (parameter == "null") {1930parameter = "Variant";1931}1932parent_signature += parameter;1933if (j >= parameters_types.size() - default_par_count) {1934parent_signature += " = <default>";1935}19361937j++;1938}1939if (method_flags & METHOD_FLAG_VARARG) {1940if (!parameters_types.is_empty()) {1941parent_signature += ", ";1942}1943parent_signature += "...";1944}1945parent_signature += ") -> ";19461947const String return_type = parent_return_type.to_string_strict();1948if (return_type == "null") {1949parent_signature += "void";1950} else {1951parent_signature += return_type;1952}19531954push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function);1955}1956#ifdef DEBUG_ENABLED1957if (native_base != StringName()) {1958parser->push_warning(p_function, GDScriptWarning::NATIVE_METHOD_OVERRIDE, function_name, native_base);1959}1960#endif // DEBUG_ENABLED1961}1962#endif // TOOLS_ENABLED1963}19641965#ifdef DEBUG_ENABLED1966if (p_function->return_type == nullptr) {1967parser->push_warning(p_function, GDScriptWarning::UNTYPED_DECLARATION, "Function", function_visible_name);1968}1969#endif // DEBUG_ENABLED19701971method_info.default_arguments.append_array(p_function->default_arg_values);1972method_info.return_val = p_function->get_datatype().to_property_info("");1973p_function->info = method_info;19741975if (p_function->get_datatype().is_resolving()) {1976p_function->set_datatype(prev_datatype);1977}19781979parser->current_function = previous_function;1980static_context = previous_static_context;1981}19821983void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function, bool p_is_lambda) {1984if (p_function->resolved_body) {1985return;1986}1987p_function->resolved_body = true;19881989if (p_function->body->statements.is_empty()) {1990// Non-abstract functions must have a body.1991if (p_function->source_lambda != nullptr) {1992push_error(R"(A lambda function must have a ":" followed by a body.)", p_function);1993} else if (!p_function->is_abstract) {1994push_error(R"(A function must either have a ":" followed by a body, or be marked as "@abstract".)", p_function);1995}1996return;1997} else {1998// Abstract functions must not have a body.1999if (p_function->is_abstract) {2000push_error(R"(An abstract function cannot have a body.)", p_function->body);2001return;2002}2003}20042005GDScriptParser::FunctionNode *previous_function = parser->current_function;2006parser->current_function = p_function;20072008bool previous_static_context = static_context;2009static_context = p_function->is_static;20102011resolve_suite(p_function->body);20122013if (!p_function->get_datatype().is_hard_type() && p_function->body->get_datatype().is_set()) {2014// Use the suite inferred type if return isn't explicitly set.2015p_function->set_datatype(p_function->body->get_datatype());2016} else if (p_function->get_datatype().is_hard_type() && (p_function->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_function->get_datatype().builtin_type != Variant::NIL)) {2017if (!p_function->body->has_return && (p_is_lambda || p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init)) {2018push_error(R"(Not all code paths return a value.)", p_function);2019}2020}20212022parser->current_function = previous_function;2023static_context = previous_static_context;2024}20252026void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {2027if (p_statement == nullptr) {2028return;2029}2030switch (p_statement->type) {2031case GDScriptParser::Node::IF:2032case GDScriptParser::Node::FOR:2033case GDScriptParser::Node::MATCH:2034case GDScriptParser::Node::PATTERN:2035case GDScriptParser::Node::RETURN:2036case GDScriptParser::Node::WHILE:2037// Use return or nested suite type as this suite type.2038if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {2039// Mixed types.2040// TODO: This could use the common supertype instead.2041p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;2042p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;2043} else {2044p_suite->set_datatype(p_statement->get_datatype());2045p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;2046}2047break;2048default:2049break;2050}2051}20522053void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {2054for (int i = 0; i < p_suite->statements.size(); i++) {2055GDScriptParser::Node *stmt = p_suite->statements[i];2056// Apply annotations.2057for (GDScriptParser::AnnotationNode *&E : stmt->annotations) {2058resolve_annotation(E);2059E->apply(parser, stmt, nullptr); // TODO: Provide `p_class`.2060}20612062resolve_node(stmt);2063resolve_pending_lambda_bodies();2064decide_suite_type(p_suite, stmt);2065}2066}20672068void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assignable, const char *p_kind) {2069GDScriptParser::DataType type;2070type.kind = GDScriptParser::DataType::VARIANT;20712072bool is_constant = p_assignable->type == GDScriptParser::Node::CONSTANT;20732074#ifdef DEBUG_ENABLED2075if (p_assignable->identifier != nullptr && p_assignable->identifier->suite != nullptr && p_assignable->identifier->suite->parent_block != nullptr) {2076if (p_assignable->identifier->suite->parent_block->has_local(p_assignable->identifier->name)) {2077const GDScriptParser::SuiteNode::Local &local = p_assignable->identifier->suite->parent_block->get_local(p_assignable->identifier->name);2078parser->push_warning(p_assignable->identifier, GDScriptWarning::CONFUSABLE_LOCAL_DECLARATION, local.get_name(), p_assignable->identifier->name);2079}2080}2081#endif // DEBUG_ENABLED20822083GDScriptParser::DataType specified_type;2084bool has_specified_type = p_assignable->datatype_specifier != nullptr;2085if (has_specified_type) {2086specified_type = type_from_metatype(resolve_datatype(p_assignable->datatype_specifier));2087type = specified_type;2088}20892090if (p_assignable->initializer != nullptr) {2091reduce_expression(p_assignable->initializer);20922093if (p_assignable->initializer->type == GDScriptParser::Node::ARRAY) {2094GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_assignable->initializer);2095if (has_specified_type && specified_type.has_container_element_type(0)) {2096update_array_literal_element_type(array, specified_type.get_container_element_type(0));2097}2098} else if (p_assignable->initializer->type == GDScriptParser::Node::DICTIONARY) {2099GDScriptParser::DictionaryNode *dictionary = static_cast<GDScriptParser::DictionaryNode *>(p_assignable->initializer);2100if (has_specified_type && specified_type.has_container_element_types()) {2101update_dictionary_literal_element_type(dictionary, specified_type.get_container_element_type_or_variant(0), specified_type.get_container_element_type_or_variant(1));2102}2103}21042105if (is_constant && !p_assignable->initializer->is_constant) {2106bool is_initializer_value_reduced = false;2107Variant initializer_value = make_expression_reduced_value(p_assignable->initializer, is_initializer_value_reduced);2108if (is_initializer_value_reduced) {2109p_assignable->initializer->is_constant = true;2110p_assignable->initializer->reduced_value = initializer_value;2111} else {2112push_error(vformat(R"(Assigned value for %s "%s" isn't a constant expression.)", p_kind, p_assignable->identifier->name), p_assignable->initializer);2113}2114}21152116if (has_specified_type && p_assignable->initializer->is_constant) {2117update_const_expression_builtin_type(p_assignable->initializer, specified_type, "assign");2118}2119GDScriptParser::DataType initializer_type = p_assignable->initializer->get_datatype();21202121if (p_assignable->infer_datatype) {2122if (!initializer_type.is_set() || initializer_type.has_no_type() || !initializer_type.is_hard_type()) {2123push_error(vformat(R"(Cannot infer the type of "%s" %s because the value doesn't have a set type.)", p_assignable->identifier->name, p_kind), p_assignable->initializer);2124} else if (initializer_type.kind == GDScriptParser::DataType::BUILTIN && initializer_type.builtin_type == Variant::NIL && !is_constant) {2125push_error(vformat(R"(Cannot infer the type of "%s" %s because the value is "null".)", p_assignable->identifier->name, p_kind), p_assignable->initializer);2126}2127#ifdef DEBUG_ENABLED2128if (initializer_type.is_hard_type() && initializer_type.is_variant()) {2129parser->push_warning(p_assignable, GDScriptWarning::INFERENCE_ON_VARIANT, p_kind);2130}2131#endif // DEBUG_ENABLED2132} else {2133if (!initializer_type.is_set()) {2134push_error(vformat(R"(Could not resolve type for %s "%s".)", p_kind, p_assignable->identifier->name), p_assignable->initializer);2135}2136}21372138if (!has_specified_type) {2139type = initializer_type;21402141if (!type.is_set() || (type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL && !is_constant)) {2142type.kind = GDScriptParser::DataType::VARIANT;2143}21442145if (p_assignable->infer_datatype || is_constant) {2146type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;2147} else {2148type.type_source = GDScriptParser::DataType::INFERRED;2149}2150} else if (!specified_type.is_variant()) {2151if (initializer_type.is_variant() || !initializer_type.is_hard_type()) {2152mark_node_unsafe(p_assignable->initializer);2153p_assignable->use_conversion_assign = true;2154if (!initializer_type.is_variant() && !is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {2155downgrade_node_type_source(p_assignable->initializer);2156}2157} else if (!is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {2158if (!is_constant && is_type_compatible(initializer_type, specified_type)) {2159mark_node_unsafe(p_assignable->initializer);2160p_assignable->use_conversion_assign = true;2161} else {2162push_error(vformat(R"(Cannot assign a value of type %s to %s "%s" with specified type %s.)", initializer_type.to_string(), p_kind, p_assignable->identifier->name, specified_type.to_string()), p_assignable->initializer);2163}2164} else if ((specified_type.has_container_element_type(0) && !initializer_type.has_container_element_type(0)) || (specified_type.has_container_element_type(1) && !initializer_type.has_container_element_type(1))) {2165mark_node_unsafe(p_assignable->initializer);2166#ifdef DEBUG_ENABLED2167} else if (specified_type.builtin_type == Variant::INT && initializer_type.builtin_type == Variant::FLOAT) {2168parser->push_warning(p_assignable->initializer, GDScriptWarning::NARROWING_CONVERSION);2169#endif // DEBUG_ENABLED2170}2171}2172}21732174#ifdef DEBUG_ENABLED2175const bool is_parameter = p_assignable->type == GDScriptParser::Node::PARAMETER;2176if (!has_specified_type) {2177const String declaration_type = is_constant ? "Constant" : (is_parameter ? "Parameter" : "Variable");2178if (p_assignable->infer_datatype || is_constant) {2179// Do not produce the `INFERRED_DECLARATION` warning on type import because there is no way to specify the true type.2180// And removing the metatype makes it impossible to use the constant as a type hint (especially for enums).2181const bool is_type_import = is_constant && p_assignable->initializer != nullptr && p_assignable->initializer->datatype.is_meta_type;2182if (!is_type_import) {2183parser->push_warning(p_assignable, GDScriptWarning::INFERRED_DECLARATION, declaration_type, p_assignable->identifier->name);2184}2185} else {2186parser->push_warning(p_assignable, GDScriptWarning::UNTYPED_DECLARATION, declaration_type, p_assignable->identifier->name);2187}2188} else if (!is_parameter && specified_type.kind == GDScriptParser::DataType::ENUM && p_assignable->initializer == nullptr) {2189// Warn about enum variables without default value. Unless the enum defines the "0" value, then it's fine.2190bool has_zero_value = false;2191for (const KeyValue<StringName, int64_t> &kv : specified_type.enum_values) {2192if (kv.value == 0) {2193has_zero_value = true;2194break;2195}2196}2197if (!has_zero_value) {2198parser->push_warning(p_assignable, GDScriptWarning::ENUM_VARIABLE_WITHOUT_DEFAULT, p_assignable->identifier->name);2199}2200}2201#endif // DEBUG_ENABLED22022203type.is_constant = is_constant;2204type.is_read_only = false;2205p_assignable->set_datatype(type);2206}22072208void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable, bool p_is_local) {2209static constexpr const char *kind = "variable";2210resolve_assignable(p_variable, kind);22112212#ifdef DEBUG_ENABLED2213if (p_is_local) {2214if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {2215parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);2216}2217}2218is_shadowing(p_variable->identifier, kind, p_is_local);2219#endif // DEBUG_ENABLED2220}22212222void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant, bool p_is_local) {2223static constexpr const char *kind = "constant";2224resolve_assignable(p_constant, kind);22252226#ifdef DEBUG_ENABLED2227if (p_is_local) {2228if (p_constant->usages == 0 && !String(p_constant->identifier->name).begins_with("_")) {2229parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);2230}2231}2232is_shadowing(p_constant->identifier, kind, p_is_local);2233#endif // DEBUG_ENABLED2234}22352236void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {2237static constexpr const char *kind = "parameter";2238resolve_assignable(p_parameter, kind);2239}22402241void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {2242reduce_expression(p_if->condition);22432244resolve_suite(p_if->true_block);2245p_if->set_datatype(p_if->true_block->get_datatype());22462247if (p_if->false_block != nullptr) {2248resolve_suite(p_if->false_block);2249decide_suite_type(p_if, p_if->false_block);2250}2251}22522253void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {2254GDScriptParser::DataType variable_type;2255GDScriptParser::DataType list_type;22562257if (p_for->list) {2258resolve_node(p_for->list, false);22592260bool is_range = false;2261if (p_for->list->type == GDScriptParser::Node::CALL) {2262GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);2263if (call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {2264if (static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name == "range") {2265if (call->arguments.is_empty()) {2266push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call);2267} else if (call->arguments.size() > 3) {2268push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call);2269}2270is_range = true;2271variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;2272variable_type.kind = GDScriptParser::DataType::BUILTIN;2273variable_type.builtin_type = Variant::INT;2274}2275}2276}22772278list_type = p_for->list->get_datatype();22792280if (!list_type.is_hard_type()) {2281mark_node_unsafe(p_for->list);2282}22832284if (is_range) {2285// Already solved.2286} else if (list_type.is_variant()) {2287variable_type.kind = GDScriptParser::DataType::VARIANT;2288mark_node_unsafe(p_for->list);2289} else if (list_type.has_container_element_type(0)) {2290variable_type = list_type.get_container_element_type(0);2291variable_type.type_source = list_type.type_source;2292} else if (list_type.is_typed_container_type()) {2293variable_type = list_type.get_typed_container_type();2294variable_type.type_source = list_type.type_source;2295} else if (list_type.builtin_type == Variant::INT || list_type.builtin_type == Variant::FLOAT || list_type.builtin_type == Variant::STRING) {2296variable_type.type_source = list_type.type_source;2297variable_type.kind = GDScriptParser::DataType::BUILTIN;2298variable_type.builtin_type = list_type.builtin_type;2299} else if (list_type.builtin_type == Variant::VECTOR2I || list_type.builtin_type == Variant::VECTOR3I) {2300variable_type.type_source = list_type.type_source;2301variable_type.kind = GDScriptParser::DataType::BUILTIN;2302variable_type.builtin_type = Variant::INT;2303} else if (list_type.builtin_type == Variant::VECTOR2 || list_type.builtin_type == Variant::VECTOR3) {2304variable_type.type_source = list_type.type_source;2305variable_type.kind = GDScriptParser::DataType::BUILTIN;2306variable_type.builtin_type = Variant::FLOAT;2307} else if (list_type.builtin_type == Variant::OBJECT) {2308GDScriptParser::DataType return_type;2309List<GDScriptParser::DataType> par_types;2310int default_arg_count = 0;2311BitField<MethodFlags> method_flags = {};2312if (get_function_signature(p_for->list, false, list_type, CoreStringName(_iter_get), return_type, par_types, default_arg_count, method_flags)) {2313variable_type = return_type;2314variable_type.type_source = list_type.type_source;2315} else if (!list_type.is_hard_type()) {2316variable_type.kind = GDScriptParser::DataType::VARIANT;2317} else {2318push_error(vformat(R"(Unable to iterate on object of type "%s".)", list_type.to_string()), p_for->list);2319}2320} else if (list_type.builtin_type == Variant::ARRAY || list_type.builtin_type == Variant::DICTIONARY || !list_type.is_hard_type()) {2321variable_type.kind = GDScriptParser::DataType::VARIANT;2322} else {2323push_error(vformat(R"(Unable to iterate on value of type "%s".)", list_type.to_string()), p_for->list);2324}2325}23262327if (p_for->variable) {2328if (p_for->datatype_specifier) {2329GDScriptParser::DataType specified_type = type_from_metatype(resolve_datatype(p_for->datatype_specifier));2330if (!specified_type.is_variant()) {2331if (variable_type.is_variant() || !variable_type.is_hard_type()) {2332mark_node_unsafe(p_for->variable);2333p_for->use_conversion_assign = true;2334} else if (!is_type_compatible(specified_type, variable_type, true, p_for->variable)) {2335if (is_type_compatible(variable_type, specified_type)) {2336mark_node_unsafe(p_for->variable);2337p_for->use_conversion_assign = true;2338} else {2339push_error(vformat(R"(Unable to iterate on value of type "%s" with variable of type "%s".)", list_type.to_string(), specified_type.to_string()), p_for->datatype_specifier);2340}2341} else if (!is_type_compatible(specified_type, variable_type)) {2342p_for->use_conversion_assign = true;2343}2344if (p_for->list) {2345if (p_for->list->type == GDScriptParser::Node::ARRAY) {2346update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_for->list), specified_type);2347} else if (p_for->list->type == GDScriptParser::Node::DICTIONARY) {2348update_dictionary_literal_element_type(static_cast<GDScriptParser::DictionaryNode *>(p_for->list), specified_type, GDScriptParser::DataType::get_variant_type());2349}2350}2351}2352p_for->variable->set_datatype(specified_type);2353} else {2354p_for->variable->set_datatype(variable_type);2355#ifdef DEBUG_ENABLED2356if (variable_type.is_hard_type()) {2357parser->push_warning(p_for->variable, GDScriptWarning::INFERRED_DECLARATION, R"("for" iterator variable)", p_for->variable->name);2358} else {2359parser->push_warning(p_for->variable, GDScriptWarning::UNTYPED_DECLARATION, R"("for" iterator variable)", p_for->variable->name);2360}2361#endif // DEBUG_ENABLED2362}2363}23642365resolve_suite(p_for->loop);2366p_for->set_datatype(p_for->loop->get_datatype());2367#ifdef DEBUG_ENABLED2368if (p_for->variable) {2369is_shadowing(p_for->variable, R"("for" iterator variable)", true);2370}2371#endif // DEBUG_ENABLED2372}23732374void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {2375resolve_node(p_while->condition, false);23762377resolve_suite(p_while->loop);2378p_while->set_datatype(p_while->loop->get_datatype());2379}23802381void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {2382reduce_expression(p_assert->condition);2383if (p_assert->message != nullptr) {2384reduce_expression(p_assert->message);2385if (!p_assert->message->get_datatype().has_no_type() && (p_assert->message->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_assert->message->get_datatype().builtin_type != Variant::STRING)) {2386push_error(R"(Expected string for assert error message.)", p_assert->message);2387}2388}23892390p_assert->set_datatype(p_assert->condition->get_datatype());23912392#ifdef DEBUG_ENABLED2393if (p_assert->condition->is_constant) {2394if (p_assert->condition->reduced_value.booleanize()) {2395parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);2396} else if (!(p_assert->condition->type == GDScriptParser::Node::LITERAL && static_cast<GDScriptParser::LiteralNode *>(p_assert->condition)->value.get_type() == Variant::BOOL)) {2397parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);2398}2399}2400#endif // DEBUG_ENABLED2401}24022403void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {2404reduce_expression(p_match->test);24052406for (int i = 0; i < p_match->branches.size(); i++) {2407resolve_match_branch(p_match->branches[i], p_match->test);24082409decide_suite_type(p_match, p_match->branches[i]);2410}2411}24122413void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {2414// Apply annotations.2415for (GDScriptParser::AnnotationNode *&E : p_match_branch->annotations) {2416resolve_annotation(E);2417E->apply(parser, p_match_branch, nullptr); // TODO: Provide `p_class`.2418}24192420for (int i = 0; i < p_match_branch->patterns.size(); i++) {2421resolve_match_pattern(p_match_branch->patterns[i], p_match_test);2422}24232424if (p_match_branch->guard_body) {2425resolve_suite(p_match_branch->guard_body);2426}24272428resolve_suite(p_match_branch->block);24292430decide_suite_type(p_match_branch, p_match_branch->block);2431}24322433void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {2434if (p_match_pattern == nullptr) {2435return;2436}24372438GDScriptParser::DataType result;24392440switch (p_match_pattern->pattern_type) {2441case GDScriptParser::PatternNode::PT_LITERAL:2442if (p_match_pattern->literal) {2443reduce_literal(p_match_pattern->literal);2444result = p_match_pattern->literal->get_datatype();2445}2446break;2447case GDScriptParser::PatternNode::PT_EXPRESSION:2448if (p_match_pattern->expression) {2449GDScriptParser::ExpressionNode *expr = p_match_pattern->expression;2450reduce_expression(expr);2451result = expr->get_datatype();2452if (!expr->is_constant) {2453while (expr && expr->type == GDScriptParser::Node::SUBSCRIPT) {2454GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(expr);2455if (!sub->is_attribute) {2456expr = nullptr;2457} else {2458expr = sub->base;2459}2460}2461if (!expr || expr->type != GDScriptParser::Node::IDENTIFIER) {2462push_error(R"(Expression in match pattern must be a constant expression, an identifier, or an attribute access ("A.B").)", expr);2463}2464}2465}2466break;2467case GDScriptParser::PatternNode::PT_BIND:2468if (p_match_test != nullptr) {2469result = p_match_test->get_datatype();2470} else {2471result.kind = GDScriptParser::DataType::VARIANT;2472}2473p_match_pattern->bind->set_datatype(result);2474#ifdef DEBUG_ENABLED2475is_shadowing(p_match_pattern->bind, "pattern bind", true);2476if (p_match_pattern->bind->usages == 0 && !String(p_match_pattern->bind->name).begins_with("_")) {2477parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNUSED_VARIABLE, p_match_pattern->bind->name);2478}2479#endif // DEBUG_ENABLED2480break;2481case GDScriptParser::PatternNode::PT_ARRAY:2482for (int i = 0; i < p_match_pattern->array.size(); i++) {2483resolve_match_pattern(p_match_pattern->array[i], nullptr);2484decide_suite_type(p_match_pattern, p_match_pattern->array[i]);2485}2486result = p_match_pattern->get_datatype();2487break;2488case GDScriptParser::PatternNode::PT_DICTIONARY:2489for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {2490if (p_match_pattern->dictionary[i].key) {2491reduce_expression(p_match_pattern->dictionary[i].key);2492if (!p_match_pattern->dictionary[i].key->is_constant) {2493push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->dictionary[i].key);2494}2495}24962497if (p_match_pattern->dictionary[i].value_pattern) {2498resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);2499decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);2500}2501}2502result = p_match_pattern->get_datatype();2503break;2504case GDScriptParser::PatternNode::PT_WILDCARD:2505case GDScriptParser::PatternNode::PT_REST:2506result.kind = GDScriptParser::DataType::VARIANT;2507break;2508}25092510p_match_pattern->set_datatype(result);2511}25122513void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {2514GDScriptParser::DataType result;25152516GDScriptParser::DataType expected_type;2517bool has_expected_type = parser->current_function != nullptr;2518if (has_expected_type) {2519expected_type = parser->current_function->get_datatype();2520}25212522if (p_return->return_value != nullptr) {2523bool is_void_function = has_expected_type && expected_type.is_hard_type() && expected_type.kind == GDScriptParser::DataType::BUILTIN && expected_type.builtin_type == Variant::NIL;2524bool is_call = p_return->return_value->type == GDScriptParser::Node::CALL;2525if (is_void_function && is_call) {2526// Pretend the call is a root expression to allow those that are "void".2527reduce_call(static_cast<GDScriptParser::CallNode *>(p_return->return_value), false, true);2528} else {2529reduce_expression(p_return->return_value);2530}2531if (is_void_function) {2532p_return->void_return = true;2533const GDScriptParser::DataType &return_type = p_return->return_value->datatype;2534if (is_call && !return_type.is_hard_type()) {2535String function_name = parser->current_function->identifier ? parser->current_function->identifier->name.operator String() : String("<anonymous function>");2536String called_function_name = static_cast<GDScriptParser::CallNode *>(p_return->return_value)->function_name.operator String();2537#ifdef DEBUG_ENABLED2538parser->push_warning(p_return, GDScriptWarning::UNSAFE_VOID_RETURN, function_name, called_function_name);2539#endif // DEBUG_ENABLED2540mark_node_unsafe(p_return);2541} else if (!is_call) {2542push_error("A void function cannot return a value.", p_return);2543}2544result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;2545result.kind = GDScriptParser::DataType::BUILTIN;2546result.builtin_type = Variant::NIL;2547result.is_constant = true;2548} else {2549if (p_return->return_value->type == GDScriptParser::Node::ARRAY && has_expected_type && expected_type.has_container_element_type(0)) {2550update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_return->return_value), expected_type.get_container_element_type(0));2551} else if (p_return->return_value->type == GDScriptParser::Node::DICTIONARY && has_expected_type && expected_type.has_container_element_types()) {2552update_dictionary_literal_element_type(static_cast<GDScriptParser::DictionaryNode *>(p_return->return_value),2553expected_type.get_container_element_type_or_variant(0), expected_type.get_container_element_type_or_variant(1));2554}2555if (has_expected_type && expected_type.is_hard_type() && p_return->return_value->is_constant) {2556update_const_expression_builtin_type(p_return->return_value, expected_type, "return");2557}2558result = p_return->return_value->get_datatype();2559}2560} else {2561// Return type is null by default.2562result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;2563result.kind = GDScriptParser::DataType::BUILTIN;2564result.builtin_type = Variant::NIL;2565result.is_constant = true;2566}25672568if (has_expected_type && !expected_type.is_variant()) {2569if (result.is_variant() || !result.is_hard_type()) {2570mark_node_unsafe(p_return);2571if (!is_type_compatible(expected_type, result, true, p_return)) {2572downgrade_node_type_source(p_return);2573}2574} else if (!is_type_compatible(expected_type, result, true, p_return)) {2575mark_node_unsafe(p_return);2576if (!is_type_compatible(result, expected_type)) {2577push_error(vformat(R"(Cannot return value of type "%s" because the function return type is "%s".)", result.to_string(), expected_type.to_string()), p_return);2578}2579#ifdef DEBUG_ENABLED2580} else if (expected_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {2581parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);2582#endif // DEBUG_ENABLED2583}2584}25852586p_return->set_datatype(result);2587}25882589void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression, bool p_is_root) {2590// This one makes some magic happen.25912592if (p_expression == nullptr) {2593return;2594}25952596if (p_expression->reduced) {2597// Don't do this more than once.2598return;2599}26002601p_expression->reduced = true;26022603switch (p_expression->type) {2604case GDScriptParser::Node::ARRAY:2605reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));2606break;2607case GDScriptParser::Node::ASSIGNMENT:2608reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));2609break;2610case GDScriptParser::Node::AWAIT:2611reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));2612break;2613case GDScriptParser::Node::BINARY_OPERATOR:2614reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));2615break;2616case GDScriptParser::Node::CALL:2617reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);2618break;2619case GDScriptParser::Node::CAST:2620reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));2621break;2622case GDScriptParser::Node::DICTIONARY:2623reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));2624break;2625case GDScriptParser::Node::GET_NODE:2626reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));2627break;2628case GDScriptParser::Node::IDENTIFIER:2629reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));2630break;2631case GDScriptParser::Node::LAMBDA:2632reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));2633break;2634case GDScriptParser::Node::LITERAL:2635reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));2636break;2637case GDScriptParser::Node::PRELOAD:2638reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));2639break;2640case GDScriptParser::Node::SELF:2641reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));2642break;2643case GDScriptParser::Node::SUBSCRIPT:2644reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));2645break;2646case GDScriptParser::Node::TERNARY_OPERATOR:2647reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression), p_is_root);2648break;2649case GDScriptParser::Node::TYPE_TEST:2650reduce_type_test(static_cast<GDScriptParser::TypeTestNode *>(p_expression));2651break;2652case GDScriptParser::Node::UNARY_OPERATOR:2653reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));2654break;2655// Non-expressions. Here only to make sure new nodes aren't forgotten.2656case GDScriptParser::Node::NONE:2657case GDScriptParser::Node::ANNOTATION:2658case GDScriptParser::Node::ASSERT:2659case GDScriptParser::Node::BREAK:2660case GDScriptParser::Node::BREAKPOINT:2661case GDScriptParser::Node::CLASS:2662case GDScriptParser::Node::CONSTANT:2663case GDScriptParser::Node::CONTINUE:2664case GDScriptParser::Node::ENUM:2665case GDScriptParser::Node::FOR:2666case GDScriptParser::Node::FUNCTION:2667case GDScriptParser::Node::IF:2668case GDScriptParser::Node::MATCH:2669case GDScriptParser::Node::MATCH_BRANCH:2670case GDScriptParser::Node::PARAMETER:2671case GDScriptParser::Node::PASS:2672case GDScriptParser::Node::PATTERN:2673case GDScriptParser::Node::RETURN:2674case GDScriptParser::Node::SIGNAL:2675case GDScriptParser::Node::SUITE:2676case GDScriptParser::Node::TYPE:2677case GDScriptParser::Node::VARIABLE:2678case GDScriptParser::Node::WHILE:2679ERR_FAIL_MSG("Reaching unreachable case");2680}26812682if (p_expression->get_datatype().kind == GDScriptParser::DataType::UNRESOLVED) {2683// Prevent `is_type_compatible()` errors for incomplete expressions.2684// The error can still occur if `reduce_*()` is called directly.2685GDScriptParser::DataType dummy;2686dummy.kind = GDScriptParser::DataType::VARIANT;2687p_expression->set_datatype(dummy);2688}2689}26902691void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {2692for (int i = 0; i < p_array->elements.size(); i++) {2693GDScriptParser::ExpressionNode *element = p_array->elements[i];2694reduce_expression(element);2695}26962697// It's array in any case.2698GDScriptParser::DataType arr_type;2699arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;2700arr_type.kind = GDScriptParser::DataType::BUILTIN;2701arr_type.builtin_type = Variant::ARRAY;2702arr_type.is_constant = true;27032704p_array->set_datatype(arr_type);2705}27062707#ifdef DEBUG_ENABLED2708static bool enum_has_value(const GDScriptParser::DataType p_type, int64_t p_value) {2709for (const KeyValue<StringName, int64_t> &E : p_type.enum_values) {2710if (E.value == p_value) {2711return true;2712}2713}2714return false;2715}2716#endif // DEBUG_ENABLED27172718void GDScriptAnalyzer::update_const_expression_builtin_type(GDScriptParser::ExpressionNode *p_expression, const GDScriptParser::DataType &p_type, const char *p_usage, bool p_is_cast) {2719if (p_expression->get_datatype() == p_type) {2720return;2721}2722if (p_type.kind != GDScriptParser::DataType::BUILTIN && p_type.kind != GDScriptParser::DataType::ENUM) {2723return;2724}27252726GDScriptParser::DataType expression_type = p_expression->get_datatype();2727bool is_enum_cast = p_is_cast && p_type.kind == GDScriptParser::DataType::ENUM && p_type.is_meta_type == false && expression_type.builtin_type == Variant::INT;2728if (!is_enum_cast && !is_type_compatible(p_type, expression_type, true, p_expression)) {2729push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, expression_type.to_string(), p_type.to_string()), p_expression);2730return;2731}27322733GDScriptParser::DataType value_type = type_from_variant(p_expression->reduced_value, p_expression);2734if (expression_type.is_variant() && !is_enum_cast && !is_type_compatible(p_type, value_type, true, p_expression)) {2735push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, value_type.to_string(), p_type.to_string()), p_expression);2736return;2737}27382739#ifdef DEBUG_ENABLED2740if (p_type.kind == GDScriptParser::DataType::ENUM && value_type.builtin_type == Variant::INT && !enum_has_value(p_type, p_expression->reduced_value)) {2741parser->push_warning(p_expression, GDScriptWarning::INT_AS_ENUM_WITHOUT_MATCH, p_usage, p_expression->reduced_value.stringify(), p_type.to_string());2742}2743#endif // DEBUG_ENABLED27442745if (value_type.builtin_type == p_type.builtin_type) {2746p_expression->set_datatype(p_type);2747return;2748}27492750Variant converted_to;2751const Variant *converted_from = &p_expression->reduced_value;2752Callable::CallError call_error;2753Variant::construct(p_type.builtin_type, converted_to, &converted_from, 1, call_error);2754if (call_error.error) {2755push_error(vformat(R"(Failed to convert a value of type "%s" to "%s".)", value_type.to_string(), p_type.to_string()), p_expression);2756return;2757}27582759#ifdef DEBUG_ENABLED2760if (p_type.builtin_type == Variant::INT && value_type.builtin_type == Variant::FLOAT) {2761parser->push_warning(p_expression, GDScriptWarning::NARROWING_CONVERSION);2762}2763#endif // DEBUG_ENABLED27642765p_expression->reduced_value = converted_to;2766p_expression->set_datatype(p_type);2767}27682769// When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.2770// This function determines which type is that (if any).2771void GDScriptAnalyzer::update_array_literal_element_type(GDScriptParser::ArrayNode *p_array, const GDScriptParser::DataType &p_element_type) {2772GDScriptParser::DataType expected_type = p_element_type;2773expected_type.container_element_types.clear(); // Nested types (like `Array[Array[int]]`) are not currently supported.27742775for (int i = 0; i < p_array->elements.size(); i++) {2776GDScriptParser::ExpressionNode *element_node = p_array->elements[i];2777if (element_node->is_constant) {2778update_const_expression_builtin_type(element_node, expected_type, "include");2779}2780const GDScriptParser::DataType &actual_type = element_node->get_datatype();2781if (actual_type.has_no_type() || actual_type.is_variant() || !actual_type.is_hard_type()) {2782mark_node_unsafe(element_node);2783continue;2784}2785if (!is_type_compatible(expected_type, actual_type, true, p_array)) {2786if (is_type_compatible(actual_type, expected_type)) {2787mark_node_unsafe(element_node);2788continue;2789}2790push_error(vformat(R"(Cannot have an element of type "%s" in an array of type "Array[%s]".)", actual_type.to_string(), expected_type.to_string()), element_node);2791return;2792}2793}27942795GDScriptParser::DataType array_type = p_array->get_datatype();2796array_type.set_container_element_type(0, expected_type);2797p_array->set_datatype(array_type);2798}27992800// When a dictionary literal is stored (or passed as function argument) to a typed context, we then assume the dictionary is typed.2801// This function determines which type is that (if any).2802void GDScriptAnalyzer::update_dictionary_literal_element_type(GDScriptParser::DictionaryNode *p_dictionary, const GDScriptParser::DataType &p_key_element_type, const GDScriptParser::DataType &p_value_element_type) {2803GDScriptParser::DataType expected_key_type = p_key_element_type;2804GDScriptParser::DataType expected_value_type = p_value_element_type;2805expected_key_type.container_element_types.clear(); // Nested types (like `Dictionary[String, Array[int]]`) are not currently supported.2806expected_value_type.container_element_types.clear();28072808for (int i = 0; i < p_dictionary->elements.size(); i++) {2809GDScriptParser::ExpressionNode *key_element_node = p_dictionary->elements[i].key;2810if (key_element_node->is_constant) {2811update_const_expression_builtin_type(key_element_node, expected_key_type, "include");2812}2813const GDScriptParser::DataType &actual_key_type = key_element_node->get_datatype();2814if (actual_key_type.has_no_type() || actual_key_type.is_variant() || !actual_key_type.is_hard_type()) {2815mark_node_unsafe(key_element_node);2816} else if (!is_type_compatible(expected_key_type, actual_key_type, true, p_dictionary)) {2817if (is_type_compatible(actual_key_type, expected_key_type)) {2818mark_node_unsafe(key_element_node);2819} else {2820push_error(vformat(R"(Cannot have a key of type "%s" in a dictionary of type "Dictionary[%s, %s]".)", actual_key_type.to_string(), expected_key_type.to_string(), expected_value_type.to_string()), key_element_node);2821return;2822}2823}28242825GDScriptParser::ExpressionNode *value_element_node = p_dictionary->elements[i].value;2826if (value_element_node->is_constant) {2827update_const_expression_builtin_type(value_element_node, expected_value_type, "include");2828}2829const GDScriptParser::DataType &actual_value_type = value_element_node->get_datatype();2830if (actual_value_type.has_no_type() || actual_value_type.is_variant() || !actual_value_type.is_hard_type()) {2831mark_node_unsafe(value_element_node);2832} else if (!is_type_compatible(expected_value_type, actual_value_type, true, p_dictionary)) {2833if (is_type_compatible(actual_value_type, expected_value_type)) {2834mark_node_unsafe(value_element_node);2835} else {2836push_error(vformat(R"(Cannot have a value of type "%s" in a dictionary of type "Dictionary[%s, %s]".)", actual_value_type.to_string(), expected_key_type.to_string(), expected_value_type.to_string()), value_element_node);2837return;2838}2839}2840}28412842GDScriptParser::DataType dictionary_type = p_dictionary->get_datatype();2843dictionary_type.set_container_element_type(0, expected_key_type);2844dictionary_type.set_container_element_type(1, expected_value_type);2845p_dictionary->set_datatype(dictionary_type);2846}28472848void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {2849reduce_expression(p_assignment->assigned_value);28502851#ifdef DEBUG_ENABLED2852// Increment assignment count for local variables.2853// Before we reduce the assignee because we don't want to warn about not being assigned when performing the assignment.2854if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {2855GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);2856if (id->source == GDScriptParser::IdentifierNode::LOCAL_VARIABLE && id->variable_source) {2857id->variable_source->assignments++;2858}2859}2860#endif // DEBUG_ENABLED28612862reduce_expression(p_assignment->assignee);28632864#ifdef DEBUG_ENABLED2865{2866bool is_subscript = false;2867GDScriptParser::ExpressionNode *base = p_assignment->assignee;2868while (base && base->type == GDScriptParser::Node::SUBSCRIPT) {2869is_subscript = true;2870base = static_cast<GDScriptParser::SubscriptNode *>(base)->base;2871}2872if (base && base->type == GDScriptParser::Node::IDENTIFIER) {2873GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(base);2874if (current_lambda && current_lambda->captures_indices.has(id->name)) {2875bool need_warn = false;2876if (is_subscript) {2877const GDScriptParser::DataType &id_type = id->datatype;2878if (id_type.is_hard_type()) {2879switch (id_type.kind) {2880case GDScriptParser::DataType::BUILTIN:2881// TODO: Change `Variant::is_type_shared()` to include packed arrays?2882need_warn = !Variant::is_type_shared(id_type.builtin_type) && id_type.builtin_type < Variant::PACKED_BYTE_ARRAY;2883break;2884case GDScriptParser::DataType::ENUM:2885need_warn = true;2886break;2887default:2888break;2889}2890}2891} else {2892need_warn = true;2893}2894if (need_warn) {2895parser->push_warning(p_assignment, GDScriptWarning::CONFUSABLE_CAPTURE_REASSIGNMENT, id->name);2896}2897}2898}2899}2900#endif // DEBUG_ENABLED29012902if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {2903return;2904}29052906GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();29072908if (assignee_type.is_constant) {2909push_error("Cannot assign a new value to a constant.", p_assignment->assignee);2910return;2911} else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT && static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->is_constant) {2912const GDScriptParser::DataType &base_type = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->datatype;2913if (base_type.kind != GDScriptParser::DataType::SCRIPT && base_type.kind != GDScriptParser::DataType::CLASS) { // Static variables.2914push_error("Cannot assign a new value to a constant.", p_assignment->assignee);2915return;2916}2917} else if (assignee_type.is_read_only) {2918push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);2919return;2920} else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {2921GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee);2922while (sub) {2923const GDScriptParser::DataType &base_type = sub->base->datatype;2924if (base_type.is_hard_type() && base_type.is_read_only) {2925if (base_type.kind == GDScriptParser::DataType::BUILTIN && !Variant::is_type_shared(base_type.builtin_type)) {2926push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);2927return;2928}2929} else {2930break;2931}2932if (sub->base->type == GDScriptParser::Node::SUBSCRIPT) {2933sub = static_cast<GDScriptParser::SubscriptNode *>(sub->base);2934} else {2935sub = nullptr;2936}2937}2938}29392940// Check if assigned value is an array/dictionary literal, so we can make it a typed container too if appropriate.2941if (p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY && assignee_type.is_hard_type() && assignee_type.has_container_element_type(0)) {2942update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value), assignee_type.get_container_element_type(0));2943} else if (p_assignment->assigned_value->type == GDScriptParser::Node::DICTIONARY && assignee_type.is_hard_type() && assignee_type.has_container_element_types()) {2944update_dictionary_literal_element_type(static_cast<GDScriptParser::DictionaryNode *>(p_assignment->assigned_value),2945assignee_type.get_container_element_type_or_variant(0), assignee_type.get_container_element_type_or_variant(1));2946}29472948if (p_assignment->operation == GDScriptParser::AssignmentNode::OP_NONE && assignee_type.is_hard_type() && p_assignment->assigned_value->is_constant) {2949update_const_expression_builtin_type(p_assignment->assigned_value, assignee_type, "assign");2950}29512952GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();29532954bool assignee_is_variant = assignee_type.is_variant();2955bool assignee_is_hard = assignee_type.is_hard_type();2956bool assigned_is_variant = assigned_value_type.is_variant();2957bool assigned_is_hard = assigned_value_type.is_hard_type();2958bool compatible = true;2959bool downgrades_assignee = false;2960bool downgrades_assigned = false;2961GDScriptParser::DataType op_type = assigned_value_type;2962if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && !op_type.is_variant()) {2963op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);29642965if (assignee_is_variant) {2966// variant assignee2967mark_node_unsafe(p_assignment);2968} else if (!compatible) {2969// incompatible hard types and non-variant assignee2970mark_node_unsafe(p_assignment);2971if (assigned_is_variant) {2972// incompatible hard non-variant assignee and hard variant assigned2973p_assignment->use_conversion_assign = true;2974} else {2975// incompatible hard non-variant types2976push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);2977}2978} else if (op_type.type_source == GDScriptParser::DataType::UNDETECTED && !assigned_is_variant) {2979// incompatible non-variant types (at least one weak)2980downgrades_assignee = !assignee_is_hard;2981downgrades_assigned = !assigned_is_hard;2982}2983}2984p_assignment->set_datatype(op_type);29852986if (assignee_is_variant) {2987if (!assignee_is_hard) {2988// weak variant assignee2989mark_node_unsafe(p_assignment);2990}2991} else {2992if (assignee_is_hard && !assigned_is_hard) {2993// hard non-variant assignee and weak assigned2994mark_node_unsafe(p_assignment);2995p_assignment->use_conversion_assign = true;2996downgrades_assigned = downgrades_assigned || (!assigned_is_variant && !is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value));2997} else if (compatible) {2998if (op_type.is_variant()) {2999// non-variant assignee and variant result3000mark_node_unsafe(p_assignment);3001if (assignee_is_hard) {3002// hard non-variant assignee and variant result3003p_assignment->use_conversion_assign = true;3004} else {3005// weak non-variant assignee and variant result3006downgrades_assignee = true;3007}3008} else if (!is_type_compatible(assignee_type, op_type, assignee_is_hard, p_assignment->assigned_value)) {3009// non-variant assignee and incompatible result3010mark_node_unsafe(p_assignment);3011if (assignee_is_hard) {3012if (is_type_compatible(op_type, assignee_type)) {3013// hard non-variant assignee and maybe compatible result3014p_assignment->use_conversion_assign = true;3015} else {3016// hard non-variant assignee and incompatible result3017push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value);3018}3019} else {3020// weak non-variant assignee and incompatible result3021downgrades_assignee = true;3022}3023} else if ((assignee_type.has_container_element_type(0) && !op_type.has_container_element_type(0)) || (assignee_type.has_container_element_type(1) && !op_type.has_container_element_type(1))) {3024// Typed assignee and untyped result.3025mark_node_unsafe(p_assignment);3026}3027}3028}30293030if (downgrades_assignee) {3031downgrade_node_type_source(p_assignment->assignee);3032}3033if (downgrades_assigned) {3034downgrade_node_type_source(p_assignment->assigned_value);3035}30363037#ifdef DEBUG_ENABLED3038if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {3039parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);3040}3041// Check for assignment with operation before assignment.3042if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {3043GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);3044// Use == 1 here because this assignment was already counted in the beginning of the function.3045if (id->source == GDScriptParser::IdentifierNode::LOCAL_VARIABLE && id->variable_source && id->variable_source->assignments == 1) {3046parser->push_warning(p_assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, id->name, Variant::get_operator_name(p_assignment->variant_op));3047}3048}3049#endif // DEBUG_ENABLED3050}30513052void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {3053if (p_await->to_await == nullptr) {3054GDScriptParser::DataType await_type;3055await_type.kind = GDScriptParser::DataType::VARIANT;3056p_await->set_datatype(await_type);3057return;3058}30593060if (p_await->to_await->type == GDScriptParser::Node::CALL) {3061reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);3062} else {3063reduce_expression(p_await->to_await);3064}30653066GDScriptParser::DataType await_type = p_await->to_await->get_datatype();3067// We cannot infer the type of the result of waiting for a signal.3068if (await_type.is_hard_type() && await_type.kind == GDScriptParser::DataType::BUILTIN && await_type.builtin_type == Variant::SIGNAL) {3069await_type.kind = GDScriptParser::DataType::VARIANT;3070await_type.type_source = GDScriptParser::DataType::UNDETECTED;3071} else if (p_await->to_await->is_constant) {3072p_await->is_constant = p_await->to_await->is_constant;3073p_await->reduced_value = p_await->to_await->reduced_value;3074}3075await_type.is_coroutine = false;3076p_await->set_datatype(await_type);30773078#ifdef DEBUG_ENABLED3079GDScriptParser::DataType to_await_type = p_await->to_await->get_datatype();3080if (!to_await_type.is_coroutine && !to_await_type.is_variant() && to_await_type.builtin_type != Variant::SIGNAL) {3081parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);3082}3083#endif // DEBUG_ENABLED3084}30853086void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {3087reduce_expression(p_binary_op->left_operand);3088reduce_expression(p_binary_op->right_operand);30893090GDScriptParser::DataType left_type;3091if (p_binary_op->left_operand) {3092left_type = p_binary_op->left_operand->get_datatype();3093}3094GDScriptParser::DataType right_type;3095if (p_binary_op->right_operand) {3096right_type = p_binary_op->right_operand->get_datatype();3097}30983099if (!left_type.is_set() || !right_type.is_set()) {3100return;3101}31023103#ifdef DEBUG_ENABLED3104if (p_binary_op->variant_op == Variant::OP_DIVIDE &&3105(left_type.builtin_type == Variant::INT ||3106left_type.builtin_type == Variant::VECTOR2I ||3107left_type.builtin_type == Variant::VECTOR3I ||3108left_type.builtin_type == Variant::VECTOR4I) &&3109(right_type.builtin_type == Variant::INT ||3110right_type.builtin_type == left_type.builtin_type)) {3111parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);3112}3113#endif // DEBUG_ENABLED31143115if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {3116p_binary_op->is_constant = true;3117if (p_binary_op->variant_op < Variant::OP_MAX) {3118bool valid = false;3119Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid);3120if (!valid) {3121if (p_binary_op->reduced_value.get_type() == Variant::STRING) {3122push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);3123} else {3124push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",3125Variant::get_operator_name(p_binary_op->variant_op),3126Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),3127Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),3128p_binary_op);3129}3130}3131} else {3132ERR_PRINT("Parser bug: unknown binary operation.");3133}3134p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));31353136return;3137}31383139GDScriptParser::DataType result;31403141if ((p_binary_op->variant_op == Variant::OP_EQUAL || p_binary_op->variant_op == Variant::OP_NOT_EQUAL) &&3142((left_type.kind == GDScriptParser::DataType::BUILTIN && left_type.builtin_type == Variant::NIL) || (right_type.kind == GDScriptParser::DataType::BUILTIN && right_type.builtin_type == Variant::NIL))) {3143// "==" and "!=" operators always return a boolean when comparing to null.3144result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3145result.kind = GDScriptParser::DataType::BUILTIN;3146result.builtin_type = Variant::BOOL;3147} else if (p_binary_op->variant_op == Variant::OP_MODULE && left_type.builtin_type == Variant::STRING) {3148// The modulo operator (%) on string acts as formatting and will always return a string.3149result.type_source = left_type.type_source;3150result.kind = GDScriptParser::DataType::BUILTIN;3151result.builtin_type = Variant::STRING;3152} else if (left_type.is_variant() || right_type.is_variant()) {3153// Cannot infer type because one operand can be anything.3154result.kind = GDScriptParser::DataType::VARIANT;3155mark_node_unsafe(p_binary_op);3156} else if (p_binary_op->variant_op < Variant::OP_MAX) {3157bool valid = false;3158result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);3159if (!valid) {3160push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", left_type.to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);3161} else if (!result.is_hard_type()) {3162mark_node_unsafe(p_binary_op);3163}3164} else {3165ERR_PRINT("Parser bug: unknown binary operation.");3166}31673168p_binary_op->set_datatype(result);3169}31703171#ifdef SUGGEST_GODOT4_RENAMES3172const char *get_rename_from_map(const char *map[][2], String key) {3173for (int index = 0; map[index][0]; index++) {3174if (map[index][0] == key) {3175return map[index][1];3176}3177}3178return nullptr;3179}31803181// Checks if an identifier/function name has been renamed in Godot 4, uses ProjectConverter3To4 for rename map.3182// Returns the new name if found, nullptr otherwise.3183const char *check_for_renamed_identifier(String identifier, GDScriptParser::Node::Type type) {3184switch (type) {3185case GDScriptParser::Node::IDENTIFIER: {3186// Check properties3187const char *result = get_rename_from_map(RenamesMap3To4::gdscript_properties_renames, identifier);3188if (result) {3189return result;3190}3191// Check enum values3192result = get_rename_from_map(RenamesMap3To4::enum_renames, identifier);3193if (result) {3194return result;3195}3196// Check color constants3197result = get_rename_from_map(RenamesMap3To4::color_renames, identifier);3198if (result) {3199return result;3200}3201// Check type names3202result = get_rename_from_map(RenamesMap3To4::class_renames, identifier);3203if (result) {3204return result;3205}3206return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);3207}3208case GDScriptParser::Node::CALL: {3209const char *result = get_rename_from_map(RenamesMap3To4::gdscript_function_renames, identifier);3210if (result) {3211return result;3212}3213// Built-in Types are mistaken for function calls when the built-in type is not found.3214// Check built-in types if function rename not found3215return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);3216}3217// Signal references don't get parsed through the GDScriptAnalyzer. No support for signal rename hints.3218default:3219// No rename found, return null3220return nullptr;3221}3222}3223#endif // SUGGEST_GODOT4_RENAMES32243225void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {3226bool all_is_constant = true;3227HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.3228HashMap<int, GDScriptParser::DictionaryNode *> dictionaries; // Same, but for dictionaries.3229for (int i = 0; i < p_call->arguments.size(); i++) {3230reduce_expression(p_call->arguments[i]);3231if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {3232arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);3233} else if (p_call->arguments[i]->type == GDScriptParser::Node::DICTIONARY) {3234dictionaries[i] = static_cast<GDScriptParser::DictionaryNode *>(p_call->arguments[i]);3235}3236all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;3237}32383239GDScriptParser::Node::Type callee_type = p_call->get_callee_type();3240GDScriptParser::DataType call_type;32413242if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {3243// Call to name directly.3244StringName function_name = p_call->function_name;32453246if (function_name == SNAME("Object")) {3247push_error(R"*(Invalid constructor "Object()", use "Object.new()" instead.)*", p_call);3248p_call->set_datatype(call_type);3249return;3250}32513252Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);3253if (builtin_type < Variant::VARIANT_MAX) {3254// Is a builtin constructor.3255call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3256call_type.kind = GDScriptParser::DataType::BUILTIN;3257call_type.builtin_type = builtin_type;32583259bool safe_to_fold = true;3260switch (builtin_type) {3261// Those are stored by reference so not suited for compile-time construction.3262// Because in this case they would be the same reference in all constructed values.3263case Variant::OBJECT:3264case Variant::DICTIONARY:3265case Variant::ARRAY:3266case Variant::PACKED_BYTE_ARRAY:3267case Variant::PACKED_INT32_ARRAY:3268case Variant::PACKED_INT64_ARRAY:3269case Variant::PACKED_FLOAT32_ARRAY:3270case Variant::PACKED_FLOAT64_ARRAY:3271case Variant::PACKED_STRING_ARRAY:3272case Variant::PACKED_VECTOR2_ARRAY:3273case Variant::PACKED_VECTOR3_ARRAY:3274case Variant::PACKED_COLOR_ARRAY:3275case Variant::PACKED_VECTOR4_ARRAY:3276safe_to_fold = false;3277break;3278default:3279break;3280}32813282if (all_is_constant && safe_to_fold) {3283// Construct here.3284Vector<const Variant *> args;3285for (int i = 0; i < p_call->arguments.size(); i++) {3286args.push_back(&(p_call->arguments[i]->reduced_value));3287}32883289Callable::CallError err;3290Variant value;3291Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);32923293switch (err.error) {3294case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3295push_error(vformat(R"*(Invalid argument for "%s()" constructor: argument %d should be "%s" but is "%s".)*", Variant::get_type_name(builtin_type), err.argument + 1,3296Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),3297p_call->arguments[err.argument]);3298break;3299case Callable::CallError::CALL_ERROR_INVALID_METHOD: {3300String signature = Variant::get_type_name(builtin_type) + "(";3301for (int i = 0; i < p_call->arguments.size(); i++) {3302if (i > 0) {3303signature += ", ";3304}3305signature += p_call->arguments[i]->get_datatype().to_string();3306}3307signature += ")";3308push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);3309} break;3310case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3311push_error(vformat(R"*(Too many arguments for "%s()" constructor. Received %d but expected %d.)*", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);3312break;3313case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3314push_error(vformat(R"*(Too few arguments for "%s()" constructor. Received %d but expected %d.)*", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);3315break;3316case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3317case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3318break; // Can't happen in a builtin constructor.3319case Callable::CallError::CALL_OK:3320p_call->is_constant = true;3321p_call->reduced_value = value;3322break;3323}3324} else {3325// If there's one argument, try to use copy constructor (those aren't explicitly defined).3326if (p_call->arguments.size() == 1) {3327GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();3328if (arg_type.is_hard_type() && !arg_type.is_variant()) {3329if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {3330// Okay.3331p_call->set_datatype(call_type);3332return;3333}3334} else {3335#ifdef DEBUG_ENABLED3336mark_node_unsafe(p_call);3337// Constructors support overloads.3338Vector<String> types;3339for (int i = 0; i < Variant::VARIANT_MAX; i++) {3340if (i != builtin_type && Variant::can_convert_strict((Variant::Type)i, builtin_type)) {3341types.push_back(Variant::get_type_name((Variant::Type)i));3342}3343}3344String expected_types = function_name;3345if (types.size() == 1) {3346expected_types += "\" or \"" + types[0];3347} else if (types.size() >= 2) {3348for (int i = 0; i < types.size() - 1; i++) {3349expected_types += "\", \"" + types[i];3350}3351expected_types += "\", or \"" + types[types.size() - 1];3352}3353parser->push_warning(p_call->arguments[0], GDScriptWarning::UNSAFE_CALL_ARGUMENT, "1", "constructor", function_name, expected_types, "Variant");3354#endif // DEBUG_ENABLED3355p_call->set_datatype(call_type);3356return;3357}3358}33593360List<MethodInfo> constructors;3361Variant::get_constructor_list(builtin_type, &constructors);3362bool match = false;33633364for (const MethodInfo &info : constructors) {3365if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {3366continue;3367}3368if (p_call->arguments.size() > info.arguments.size()) {3369continue;3370}33713372bool types_match = true;33733374for (int64_t i = 0; i < p_call->arguments.size(); ++i) {3375GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);3376GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();3377if (!is_type_compatible(par_type, arg_type, true)) {3378types_match = false;3379break;3380#ifdef DEBUG_ENABLED3381} else {3382if (par_type.builtin_type == Variant::INT && arg_type.builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {3383parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, function_name);3384}3385#endif // DEBUG_ENABLED3386}3387}33883389if (types_match) {3390for (int64_t i = 0; i < p_call->arguments.size(); ++i) {3391GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);3392if (p_call->arguments[i]->is_constant) {3393update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");3394}3395#ifdef DEBUG_ENABLED3396if (!(par_type.is_variant() && par_type.is_hard_type())) {3397GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();3398if (arg_type.is_variant() || !arg_type.is_hard_type()) {3399mark_node_unsafe(p_call);3400parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "constructor", function_name, par_type.to_string(), arg_type.to_string_strict());3401}3402}3403#endif // DEBUG_ENABLED3404}3405match = true;3406call_type = type_from_property(info.return_val);3407break;3408}3409}34103411if (!match) {3412String signature = Variant::get_type_name(builtin_type) + "(";3413for (int i = 0; i < p_call->arguments.size(); i++) {3414if (i > 0) {3415signature += ", ";3416}3417signature += p_call->arguments[i]->get_datatype().to_string();3418}3419signature += ")";3420push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);3421}3422}34233424#ifdef DEBUG_ENABLED3425// Consider `Signal(self, "my_signal")` as an implicit use of the signal.3426if (builtin_type == Variant::SIGNAL && p_call->arguments.size() >= 2) {3427const GDScriptParser::ExpressionNode *object_arg = p_call->arguments[0];3428if (object_arg && object_arg->type == GDScriptParser::Node::SELF) {3429const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[1];3430if (signal_arg && signal_arg->is_constant) {3431const StringName &signal_name = signal_arg->reduced_value;3432if (parser->current_class->has_member(signal_name)) {3433const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);3434if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {3435member.signal->usages++;3436}3437}3438}3439}3440}3441#endif // DEBUG_ENABLED34423443p_call->set_datatype(call_type);3444return;3445} else if (GDScriptUtilityFunctions::function_exists(function_name)) {3446MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);34473448if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {3449push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);3450}34513452if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {3453// Can call on compilation.3454Vector<const Variant *> args;3455for (int i = 0; i < p_call->arguments.size(); i++) {3456args.push_back(&(p_call->arguments[i]->reduced_value));3457}34583459Variant value;3460Callable::CallError err;3461GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);34623463switch (err.error) {3464case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3465if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {3466push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);3467} else {3468// Do not use `type_from_property()` for expected type, since utility functions use their own checks.3469push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,3470Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),3471p_call->arguments[err.argument]);3472}3473break;3474case Callable::CallError::CALL_ERROR_INVALID_METHOD:3475push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);3476break;3477case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3478push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);3479break;3480case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3481push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);3482break;3483case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3484case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3485break; // Can't happen in a builtin constructor.3486case Callable::CallError::CALL_OK:3487p_call->is_constant = true;3488p_call->reduced_value = value;3489break;3490}3491} else {3492validate_call_arg(function_info, p_call);3493}3494p_call->set_datatype(type_from_property(function_info.return_val));3495return;3496} else if (Variant::has_utility_function(function_name)) {3497MethodInfo function_info = info_from_utility_func(function_name);34983499if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {3500push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);3501}35023503if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {3504// Can call on compilation.3505Vector<const Variant *> args;3506for (int i = 0; i < p_call->arguments.size(); i++) {3507args.push_back(&(p_call->arguments[i]->reduced_value));3508}35093510Variant value;3511Callable::CallError err;3512Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);35133514switch (err.error) {3515case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3516if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {3517push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);3518} else {3519// Do not use `type_from_property()` for expected type, since utility functions use their own checks.3520push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,3521Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),3522p_call->arguments[err.argument]);3523}3524break;3525case Callable::CallError::CALL_ERROR_INVALID_METHOD:3526push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);3527break;3528case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3529push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);3530break;3531case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3532push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);3533break;3534case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3535case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3536break; // Can't happen in a builtin constructor.3537case Callable::CallError::CALL_OK:3538p_call->is_constant = true;3539p_call->reduced_value = value;3540break;3541}3542} else {3543validate_call_arg(function_info, p_call);3544}3545p_call->set_datatype(type_from_property(function_info.return_val));3546return;3547}3548}35493550GDScriptParser::DataType base_type;3551call_type.kind = GDScriptParser::DataType::VARIANT;3552bool is_self = false;35533554if (p_call->is_super) {3555base_type = parser->current_class->base_type;3556base_type.is_meta_type = false;3557is_self = true;35583559if (p_call->callee == nullptr && current_lambda != nullptr) {3560push_error("Cannot use `super()` inside a lambda.", p_call);3561}3562} else if (callee_type == GDScriptParser::Node::IDENTIFIER) {3563base_type = parser->current_class->get_datatype();3564base_type.is_meta_type = false;3565is_self = true;3566} else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {3567GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);3568if (subscript->base == nullptr) {3569// Invalid syntax, error already set on parser.3570p_call->set_datatype(call_type);3571mark_node_unsafe(p_call);3572return;3573}3574if (!subscript->is_attribute) {3575// Invalid call. Error already sent in parser.3576// TODO: Could check if Callable here.3577p_call->set_datatype(call_type);3578mark_node_unsafe(p_call);3579return;3580}3581if (subscript->attribute == nullptr) {3582// Invalid call. Error already sent in parser.3583p_call->set_datatype(call_type);3584mark_node_unsafe(p_call);3585return;3586}35873588GDScriptParser::IdentifierNode *base_id = nullptr;3589if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {3590base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);3591}3592if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {3593base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));3594} else {3595reduce_expression(subscript->base);3596base_type = subscript->base->get_datatype();3597is_self = subscript->base->type == GDScriptParser::Node::SELF;3598}3599} else {3600// Invalid call. Error already sent in parser.3601// TODO: Could check if Callable here too.3602p_call->set_datatype(call_type);3603mark_node_unsafe(p_call);3604return;3605}36063607int default_arg_count = 0;3608BitField<MethodFlags> method_flags = {};3609GDScriptParser::DataType return_type;3610List<GDScriptParser::DataType> par_types;36113612bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");36133614if (is_constructor) {3615if (Engine::get_singleton()->has_singleton(base_type.native_type)) {3616push_error(vformat(R"(Cannot construct native class "%s" because it is an engine singleton.)", base_type.native_type), p_call);3617p_call->set_datatype(call_type);3618return;3619}3620if ((base_type.kind == GDScriptParser::DataType::CLASS && base_type.class_type->is_abstract) || (base_type.kind == GDScriptParser::DataType::SCRIPT && base_type.script_type.is_valid() && base_type.script_type->is_abstract())) {3621push_error(vformat(R"(Cannot construct abstract class "%s".)", base_type.to_string()), p_call);3622}3623}36243625if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, method_flags)) {3626p_call->is_static = method_flags.has_flag(METHOD_FLAG_STATIC);3627// If the method is implemented in the class hierarchy, the virtual/abstract flag will not be set for that `MethodInfo` and the search stops there.3628// Virtual/abstract check only possible for super calls because class hierarchy is known. Objects may have scripts attached we don't know of at compile-time.3629if (p_call->is_super) {3630if (method_flags.has_flag(METHOD_FLAG_VIRTUAL)) {3631push_error(vformat(R"*(Cannot call the parent class' virtual function "%s()" because it hasn't been defined.)*", p_call->function_name), p_call);3632} else if (method_flags.has_flag(METHOD_FLAG_VIRTUAL_REQUIRED)) {3633push_error(vformat(R"*(Cannot call the parent class' abstract function "%s()" because it hasn't been defined.)*", p_call->function_name), p_call);3634}3635}36363637// If the function requires typed arrays we must make literals be typed.3638for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {3639int index = E.key;3640if (index < par_types.size() && par_types.get(index).is_hard_type() && par_types.get(index).has_container_element_type(0)) {3641update_array_literal_element_type(E.value, par_types.get(index).get_container_element_type(0));3642}3643}3644for (const KeyValue<int, GDScriptParser::DictionaryNode *> &E : dictionaries) {3645int index = E.key;3646if (index < par_types.size() && par_types.get(index).is_hard_type() && par_types.get(index).has_container_element_types()) {3647GDScriptParser::DataType key = par_types.get(index).get_container_element_type_or_variant(0);3648GDScriptParser::DataType value = par_types.get(index).get_container_element_type_or_variant(1);3649update_dictionary_literal_element_type(E.value, key, value);3650}3651}3652validate_call_arg(par_types, default_arg_count, method_flags.has_flag(METHOD_FLAG_VARARG), p_call);36533654if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {3655// Enum type is treated as a dictionary value for function calls.3656base_type.is_meta_type = false;3657}36583659if (is_self && static_context && !p_call->is_static) {3660// Get the parent function above any lambda.3661GDScriptParser::FunctionNode *parent_function = parser->current_function;3662while (parent_function && parent_function->source_lambda) {3663parent_function = parent_function->source_lambda->parent_function;3664}36653666if (parent_function) {3667push_error(vformat(R"*(Cannot call non-static function "%s()" from the static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);3668} else {3669push_error(vformat(R"*(Cannot call non-static function "%s()" from a static variable initializer.)*", p_call->function_name), p_call);3670}3671} else if (!is_self && base_type.is_meta_type && !p_call->is_static) {3672base_type.is_meta_type = false; // For `to_string()`.3673push_error(vformat(R"*(Cannot call non-static function "%s()" on the class "%s" directly. Make an instance instead.)*", p_call->function_name, base_type.to_string()), p_call);3674} else if (is_self && !p_call->is_static) {3675mark_lambda_use_self();3676}36773678if (!p_is_root && !p_is_await && return_type.is_hard_type() && return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {3679push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", p_call->function_name), p_call);3680}36813682#ifdef DEBUG_ENABLED3683// FIXME: No warning for built-in constructors and utilities due to early return.3684if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL &&3685!(p_call->is_super && p_call->function_name == GDScriptLanguage::get_singleton()->strings._init)) {3686parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);3687}36883689if (method_flags.has_flag(METHOD_FLAG_STATIC) && !is_constructor && !base_type.is_meta_type && !is_self) {3690String caller_type = base_type.to_string();36913692parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, caller_type);3693}36943695// Consider `emit_signal()`, `connect()`, and `disconnect()` as implicit uses of the signal.3696if (is_self && (p_call->function_name == SNAME("emit_signal") || p_call->function_name == SNAME("connect") || p_call->function_name == SNAME("disconnect")) && !p_call->arguments.is_empty()) {3697const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[0];3698if (signal_arg && signal_arg->is_constant) {3699const StringName &signal_name = signal_arg->reduced_value;3700if (parser->current_class->has_member(signal_name)) {3701const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);3702if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {3703member.signal->usages++;3704}3705}3706}3707}3708#endif // DEBUG_ENABLED37093710call_type = return_type;3711} else {3712bool found = false;37133714// Enums do not have functions other than the built-in dictionary ones.3715if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {3716if (base_type.builtin_type == Variant::DICTIONARY) {3717push_error(vformat(R"*(Enums only have Dictionary built-in methods. Function "%s()" does not exist for enum "%s".)*", p_call->function_name, base_type.enum_type), p_call->callee);3718} else {3719push_error(vformat(R"*(The native enum "%s" does not behave like Dictionary and does not have methods of its own.)*", base_type.enum_type), p_call->callee);3720}3721} else if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { // Check if the name exists as something else.3722GDScriptParser::IdentifierNode *callee_id;3723if (callee_type == GDScriptParser::Node::IDENTIFIER) {3724callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);3725} else {3726// Can only be attribute.3727callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;3728}3729if (callee_id) {3730reduce_identifier_from_base(callee_id, &base_type);3731GDScriptParser::DataType callee_datatype = callee_id->get_datatype();3732if (callee_datatype.is_set() && !callee_datatype.is_variant()) {3733found = true;3734if (callee_datatype.builtin_type == Variant::CALLABLE) {3735push_error(vformat(R"*(Name "%s" is a Callable. You can call it with "%s.call()" instead.)*", p_call->function_name, p_call->function_name), p_call->callee);3736} else {3737push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);3738}3739#ifdef DEBUG_ENABLED3740} else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {3741parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());3742mark_node_unsafe(p_call);3743#endif // DEBUG_ENABLED3744}3745}3746}3747if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {3748String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();3749#ifdef SUGGEST_GODOT4_RENAMES3750String rename_hint;3751if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {3752const char *renamed_function_name = check_for_renamed_identifier(p_call->function_name, p_call->type);3753if (renamed_function_name) {3754rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", String(renamed_function_name) + "()");3755}3756}3757push_error(vformat(R"*(Function "%s()" not found in base %s.%s)*", p_call->function_name, base_name, rename_hint), p_call->is_super ? p_call : p_call->callee);3758#else3759push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);3760#endif // SUGGEST_GODOT4_RENAMES3761} else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.is_meta_type)) {3762push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.to_string()), p_call);3763}3764}37653766if (call_type.is_coroutine && !p_is_await) {3767if (p_is_root) {3768#ifdef DEBUG_ENABLED3769parser->push_warning(p_call, GDScriptWarning::MISSING_AWAIT);3770#endif // DEBUG_ENABLED3771} else {3772push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call);3773}3774}37753776p_call->set_datatype(call_type);3777}37783779void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {3780reduce_expression(p_cast->operand);37813782GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type));37833784if (!cast_type.is_set()) {3785mark_node_unsafe(p_cast);3786return;3787}37883789p_cast->set_datatype(cast_type);3790if (p_cast->operand->is_constant) {3791update_const_expression_builtin_type(p_cast->operand, cast_type, "cast", true);3792if (cast_type.is_variant() || p_cast->operand->get_datatype() == cast_type) {3793p_cast->is_constant = true;3794p_cast->reduced_value = p_cast->operand->reduced_value;3795}3796}37973798if (p_cast->operand->type == GDScriptParser::Node::ARRAY && cast_type.has_container_element_type(0)) {3799update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_cast->operand), cast_type.get_container_element_type(0));3800}38013802if (p_cast->operand->type == GDScriptParser::Node::DICTIONARY && cast_type.has_container_element_types()) {3803update_dictionary_literal_element_type(static_cast<GDScriptParser::DictionaryNode *>(p_cast->operand),3804cast_type.get_container_element_type_or_variant(0), cast_type.get_container_element_type_or_variant(1));3805}38063807if (!cast_type.is_variant()) {3808GDScriptParser::DataType op_type = p_cast->operand->get_datatype();3809if (op_type.is_variant() || !op_type.is_hard_type()) {3810mark_node_unsafe(p_cast);3811#ifdef DEBUG_ENABLED3812parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());3813#endif // DEBUG_ENABLED3814} else {3815bool valid = false;3816if (op_type.builtin_type == Variant::INT && cast_type.kind == GDScriptParser::DataType::ENUM) {3817mark_node_unsafe(p_cast);3818valid = true;3819} else if (op_type.kind == GDScriptParser::DataType::ENUM && cast_type.builtin_type == Variant::INT) {3820valid = true;3821} else if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {3822valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);3823} else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {3824valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);3825}38263827if (!valid) {3828push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);3829}3830}3831}3832}38333834void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {3835HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, StringLikeVariantComparator> elements;38363837for (int i = 0; i < p_dictionary->elements.size(); i++) {3838const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];3839if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {3840reduce_expression(element.key);3841}3842reduce_expression(element.value);38433844if (element.key->is_constant) {3845if (elements.has(element.key->reduced_value)) {3846push_error(vformat(R"(Key "%s" was already used in this dictionary (at line %d).)", element.key->reduced_value, elements[element.key->reduced_value]->start_line), element.key);3847} else {3848elements[element.key->reduced_value] = element.value;3849}3850}3851}38523853// It's dictionary in any case.3854GDScriptParser::DataType dict_type;3855dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3856dict_type.kind = GDScriptParser::DataType::BUILTIN;3857dict_type.builtin_type = Variant::DICTIONARY;3858dict_type.is_constant = true;38593860p_dictionary->set_datatype(dict_type);3861}38623863void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {3864GDScriptParser::DataType result;3865result.kind = GDScriptParser::DataType::VARIANT;38663867if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, SNAME("Node"))) {3868push_error(vformat(R"*(Cannot use shorthand "get_node()" notation ("%c") on a class that isn't a node.)*", p_get_node->use_dollar ? '$' : '%'), p_get_node);3869p_get_node->set_datatype(result);3870return;3871}38723873if (static_context) {3874push_error(vformat(R"*(Cannot use shorthand "get_node()" notation ("%c") in a static function.)*", p_get_node->use_dollar ? '$' : '%'), p_get_node);3875p_get_node->set_datatype(result);3876return;3877}38783879mark_lambda_use_self();38803881result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3882result.kind = GDScriptParser::DataType::NATIVE;3883result.builtin_type = Variant::OBJECT;3884result.native_type = SNAME("Node");3885p_get_node->set_datatype(result);3886}38873888GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {3889GDScriptParser::DataType type;38903891String path = ScriptServer::get_global_class_path(p_class_name);3892String ext = path.get_extension();3893if (ext == GDScriptLanguage::get_singleton()->get_extension()) {3894Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(path);3895if (ref.is_null()) {3896push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source);3897type.type_source = GDScriptParser::DataType::UNDETECTED;3898type.kind = GDScriptParser::DataType::VARIANT;3899return type;3900}39013902Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);3903if (err) {3904push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);3905type.type_source = GDScriptParser::DataType::UNDETECTED;3906type.kind = GDScriptParser::DataType::VARIANT;3907return type;3908}39093910return ref->get_parser()->head->get_datatype();3911} else {3912return make_script_meta_type(ResourceLoader::load(path, "Script"));3913}3914}39153916Ref<GDScriptParserRef> GDScriptAnalyzer::ensure_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, const GDScriptParser::ClassNode *p_from_class, const char *p_context, const GDScriptParser::Node *p_source) {3917// Delicate piece of code that intentionally doesn't use the GDScript cache or `get_depended_parser_for`.3918// Search dependencies for the parser that owns `p_class` and make a cache entry for it.3919// Required for how we store pointers to classes owned by other parser trees and need to call `resolve_class_member` and such on the same parser tree.3920// Since https://github.com/godotengine/godot/pull/94871 there can technically be multiple parsers for the same script in the same parser tree.3921// Even if unlikely, getting the wrong parser could lead to strange undefined behavior without errors.39223923if (p_class == nullptr) {3924return nullptr;3925}39263927if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(p_class)) {3928return E->value;3929}39303931if (parser->has_class(p_class)) {3932return nullptr;3933}39343935if (p_from_class == nullptr) {3936p_from_class = parser->head;3937}39383939Ref<GDScriptParserRef> parser_ref;3940for (const GDScriptParser::ClassNode *look_class = p_from_class; look_class != nullptr; look_class = look_class->base_type.class_type) {3941if (parser->has_class(look_class)) {3942parser_ref = find_cached_external_parser_for_class(p_class, parser);3943if (parser_ref.is_valid()) {3944break;3945}3946}39473948if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(look_class)) {3949parser_ref = find_cached_external_parser_for_class(p_class, E->value);3950if (parser_ref.is_valid()) {3951break;3952}3953}39543955String look_class_script_path = look_class->get_datatype().script_path;3956if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = parser->depended_parsers.find(look_class_script_path)) {3957parser_ref = find_cached_external_parser_for_class(p_class, E->value);3958if (parser_ref.is_valid()) {3959break;3960}3961}3962}39633964if (parser_ref.is_null()) {3965push_error(vformat(R"(Parser bug (please report): Could not find external parser for class "%s". (%s))", p_class->fqcn, p_context), p_source);3966// A null parser will be inserted into the cache, so this error won't spam for the same class.3967// This is ok, the values of external_class_parser_cache are not assumed to be valid references.3968}39693970external_class_parser_cache.insert(p_class, parser_ref);3971return parser_ref;3972}39733974Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, const Ref<GDScriptParserRef> &p_dependant_parser) {3975if (p_dependant_parser.is_null()) {3976return nullptr;3977}39783979if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->get_analyzer()->external_class_parser_cache.find(p_class)) {3980if (E->value.is_valid()) {3981// Silently ensure it's parsed.3982E->value->raise_status(GDScriptParserRef::PARSED);3983if (E->value->get_parser()->has_class(p_class)) {3984return E->value;3985}3986}3987}39883989if (p_dependant_parser->get_parser()->has_class(p_class)) {3990return p_dependant_parser;3991}39923993// Silently ensure it's parsed.3994p_dependant_parser->raise_status(GDScriptParserRef::PARSED);3995return find_cached_external_parser_for_class(p_class, p_dependant_parser->get_parser());3996}39973998Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, GDScriptParser *p_dependant_parser) {3999if (p_dependant_parser == nullptr) {4000return nullptr;4001}40024003String script_path = p_class->get_datatype().script_path;4004if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->depended_parsers.find(script_path)) {4005if (E->value.is_valid()) {4006// Silently ensure it's parsed.4007E->value->raise_status(GDScriptParserRef::PARSED);4008if (E->value->get_parser()->has_class(p_class)) {4009return E->value;4010}4011}4012}40134014return nullptr;4015}40164017Ref<GDScript> GDScriptAnalyzer::get_depended_shallow_script(const String &p_path, Error &r_error) {4018// To keep a local cache of the parser for resolving external nodes later.4019const String path = ResourceUID::ensure_path(p_path);4020parser->get_depended_parser_for(path);4021Ref<GDScript> scr = GDScriptCache::get_shallow_script(path, r_error, parser->script_path);4022return scr;4023}40244025void GDScriptAnalyzer::reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype) {4026ERR_FAIL_NULL(p_identifier);40274028p_identifier->set_datatype(p_identifier_datatype);4029Error err = OK;4030Ref<GDScript> scr = get_depended_shallow_script(p_identifier_datatype.script_path, err);4031if (err) {4032push_error(vformat(R"(Error while getting cache for script "%s".)", p_identifier_datatype.script_path), p_identifier);4033return;4034}4035p_identifier->reduced_value = scr->find_class(p_identifier_datatype.class_type->fqcn);4036p_identifier->is_constant = true;4037}40384039void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {4040if (!p_identifier->get_datatype().has_no_type()) {4041return;4042}40434044GDScriptParser::DataType base;4045if (p_base == nullptr) {4046base = type_from_metatype(parser->current_class->get_datatype());4047} else {4048base = *p_base;4049}40504051StringName name = p_identifier->name;40524053if (base.kind == GDScriptParser::DataType::ENUM) {4054if (base.is_meta_type) {4055if (base.enum_values.has(name)) {4056p_identifier->set_datatype(type_from_metatype(base));4057p_identifier->is_constant = true;4058p_identifier->reduced_value = base.enum_values[name];4059return;4060}40614062// Enum does not have this value, return.4063return;4064} else {4065push_error(R"(Cannot get property from enum value.)", p_identifier);4066return;4067}4068}40694070if (base.kind == GDScriptParser::DataType::BUILTIN) {4071if (base.is_meta_type) {4072bool valid = false;40734074if (Variant::has_constant(base.builtin_type, name)) {4075valid = true;40764077const Variant constant_value = Variant::get_constant_value(base.builtin_type, name);40784079p_identifier->is_constant = true;4080p_identifier->reduced_value = constant_value;4081p_identifier->set_datatype(type_from_variant(constant_value, p_identifier));4082}40834084if (!valid) {4085const StringName enum_name = Variant::get_enum_for_enumeration(base.builtin_type, name);4086if (enum_name != StringName()) {4087valid = true;40884089p_identifier->is_constant = true;4090p_identifier->reduced_value = Variant::get_enum_value(base.builtin_type, enum_name, name);4091p_identifier->set_datatype(make_builtin_enum_type(enum_name, base.builtin_type, false));4092}4093}40944095if (!valid && Variant::has_enum(base.builtin_type, name)) {4096valid = true;40974098p_identifier->set_datatype(make_builtin_enum_type(name, base.builtin_type, true));4099}41004101if (!valid && base.is_hard_type()) {4102#ifdef SUGGEST_GODOT4_RENAMES4103String rename_hint;4104if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4105const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4106if (renamed_identifier_name) {4107rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4108}4109}4110push_error(vformat(R"(Cannot find member "%s" in base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);4111#else4112push_error(vformat(R"(Cannot find member "%s" in base "%s".)", name, base.to_string()), p_identifier);4113#endif // SUGGEST_GODOT4_RENAMES4114}4115} else {4116switch (base.builtin_type) {4117case Variant::NIL: {4118if (base.is_hard_type()) {4119push_error(vformat(R"(Cannot get property "%s" on a null object.)", name), p_identifier);4120}4121return;4122}4123case Variant::DICTIONARY: {4124GDScriptParser::DataType dummy;4125dummy.kind = GDScriptParser::DataType::VARIANT;4126p_identifier->set_datatype(dummy);4127return;4128}4129default: {4130Callable::CallError temp;4131Variant dummy;4132Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);4133List<PropertyInfo> properties;4134dummy.get_property_list(&properties);4135for (const PropertyInfo &prop : properties) {4136if (prop.name == name) {4137p_identifier->set_datatype(type_from_property(prop));4138return;4139}4140}4141if (Variant::has_builtin_method(base.builtin_type, name)) {4142p_identifier->set_datatype(make_callable_type(Variant::get_builtin_method_info(base.builtin_type, name)));4143return;4144}4145if (base.is_hard_type()) {4146#ifdef SUGGEST_GODOT4_RENAMES4147String rename_hint;4148if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4149const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4150if (renamed_identifier_name) {4151rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4152}4153}4154push_error(vformat(R"(Cannot find member "%s" in base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);4155#else4156push_error(vformat(R"(Cannot find member "%s" in base "%s".)", name, base.to_string()), p_identifier);4157#endif // SUGGEST_GODOT4_RENAMES4158}4159}4160}4161}4162return;4163}41644165GDScriptParser::ClassNode *base_class = base.class_type;4166List<GDScriptParser::ClassNode *> script_classes;4167bool is_base = true;41684169if (base_class != nullptr) {4170get_class_node_current_scope_classes(base_class, &script_classes, p_identifier);4171}41724173bool is_constructor = base.is_meta_type && p_identifier->name == SNAME("new");41744175for (GDScriptParser::ClassNode *script_class : script_classes) {4176if (p_base == nullptr && script_class->identifier && script_class->identifier->name == name) {4177reduce_identifier_from_base_set_class(p_identifier, script_class->get_datatype());4178if (script_class->outer != nullptr) {4179p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;4180}4181return;4182}41834184if (is_constructor) {4185name = "_init";4186}41874188if (script_class->has_member(name)) {4189resolve_class_member(script_class, name, p_identifier);41904191GDScriptParser::ClassNode::Member member = script_class->get_member(name);4192switch (member.type) {4193case GDScriptParser::ClassNode::Member::CONSTANT: {4194p_identifier->set_datatype(member.get_datatype());4195p_identifier->is_constant = true;4196p_identifier->reduced_value = member.constant->initializer->reduced_value;4197p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4198p_identifier->constant_source = member.constant;4199return;4200}42014202case GDScriptParser::ClassNode::Member::ENUM_VALUE: {4203p_identifier->set_datatype(member.get_datatype());4204p_identifier->is_constant = true;4205p_identifier->reduced_value = member.enum_value.value;4206p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4207return;4208}42094210case GDScriptParser::ClassNode::Member::ENUM: {4211p_identifier->set_datatype(member.get_datatype());4212p_identifier->is_constant = true;4213p_identifier->reduced_value = member.m_enum->dictionary;4214p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4215return;4216}42174218case GDScriptParser::ClassNode::Member::VARIABLE: {4219if (is_base && (!base.is_meta_type || member.variable->is_static)) {4220p_identifier->set_datatype(member.get_datatype());4221p_identifier->source = member.variable->is_static ? GDScriptParser::IdentifierNode::STATIC_VARIABLE : GDScriptParser::IdentifierNode::MEMBER_VARIABLE;4222p_identifier->variable_source = member.variable;4223member.variable->usages += 1;4224return;4225}4226} break;42274228case GDScriptParser::ClassNode::Member::SIGNAL: {4229if (is_base && !base.is_meta_type) {4230p_identifier->set_datatype(member.get_datatype());4231p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;4232p_identifier->signal_source = member.signal;4233member.signal->usages += 1;4234return;4235}4236} break;42374238case GDScriptParser::ClassNode::Member::FUNCTION: {4239if (is_base && (!base.is_meta_type || member.function->is_static || is_constructor)) {4240p_identifier->set_datatype(make_callable_type(member.function->info));4241p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;4242p_identifier->function_source = member.function;4243p_identifier->function_source_is_static = member.function->is_static;4244return;4245}4246} break;42474248case GDScriptParser::ClassNode::Member::CLASS: {4249reduce_identifier_from_base_set_class(p_identifier, member.get_datatype());4250p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;4251return;4252}42534254default: {4255// Do nothing4256}4257}4258}42594260if (is_base) {4261is_base = script_class->base_type.class_type != nullptr;4262if (!is_base && p_base != nullptr) {4263break;4264}4265}4266}42674268// Check non-GDScript scripts.4269Ref<Script> script_type = base.script_type;42704271if (base_class == nullptr && script_type.is_valid()) {4272List<PropertyInfo> property_list;4273script_type->get_script_property_list(&property_list);42744275for (const PropertyInfo &property_info : property_list) {4276if (property_info.name != p_identifier->name) {4277continue;4278}42794280const GDScriptParser::DataType property_type = GDScriptAnalyzer::type_from_property(property_info, false, false);42814282p_identifier->set_datatype(property_type);4283p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;4284return;4285}42864287MethodInfo method_info = script_type->get_method_info(p_identifier->name);42884289if (method_info.name == p_identifier->name) {4290p_identifier->set_datatype(make_callable_type(method_info));4291p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;4292p_identifier->function_source_is_static = method_info.flags & METHOD_FLAG_STATIC;4293return;4294}42954296List<MethodInfo> signal_list;4297script_type->get_script_signal_list(&signal_list);42984299for (const MethodInfo &signal_info : signal_list) {4300if (signal_info.name != p_identifier->name) {4301continue;4302}43034304const GDScriptParser::DataType signal_type = make_signal_type(signal_info);43054306p_identifier->set_datatype(signal_type);4307p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;4308return;4309}43104311HashMap<StringName, Variant> constant_map;4312script_type->get_constants(&constant_map);43134314if (constant_map.has(p_identifier->name)) {4315Variant constant = constant_map.get(p_identifier->name);43164317p_identifier->set_datatype(make_builtin_meta_type(constant.get_type()));4318p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4319return;4320}4321}43224323// Check native members. No need for native class recursion because Node exposes all Object's properties.4324const StringName &native = base.native_type;43254326if (class_exists(native)) {4327if (is_constructor) {4328name = "_init";4329}43304331MethodInfo method_info;4332if (ClassDB::has_property(native, name)) {4333StringName getter_name = ClassDB::get_property_getter(native, name);4334MethodBind *getter = ClassDB::get_method(native, getter_name);4335if (getter != nullptr) {4336bool has_setter = ClassDB::get_property_setter(native, name) != StringName();4337p_identifier->set_datatype(type_from_property(getter->get_return_info(), false, !has_setter));4338p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4339}4340return;4341}4342if (ClassDB::get_method_info(native, name, &method_info)) {4343// Method is callable.4344p_identifier->set_datatype(make_callable_type(method_info));4345p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4346return;4347}4348if (ClassDB::get_signal(native, name, &method_info)) {4349// Signal is a type too.4350p_identifier->set_datatype(make_signal_type(method_info));4351p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4352return;4353}4354if (ClassDB::has_enum(native, name)) {4355p_identifier->set_datatype(make_native_enum_type(name, native));4356p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4357return;4358}4359bool valid = false;43604361int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);4362if (valid) {4363p_identifier->is_constant = true;4364p_identifier->reduced_value = int_constant;4365p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;43664367// Check whether this constant, which exists, belongs to an enum4368StringName enum_name = ClassDB::get_integer_constant_enum(native, name);4369if (enum_name != StringName()) {4370p_identifier->set_datatype(make_native_enum_type(enum_name, native, false));4371} else {4372p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));4373}4374}4375}4376}43774378void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {4379// TODO: This is an opportunity to further infer types.43804381// Check if we are inside an enum. This allows enum values to access other elements of the same enum.4382if (current_enum) {4383for (int i = 0; i < current_enum->values.size(); i++) {4384const GDScriptParser::EnumNode::Value &element = current_enum->values[i];4385if (element.identifier->name == p_identifier->name) {4386StringName enum_name = current_enum->identifier ? current_enum->identifier->name : UNNAMED_ENUM;4387GDScriptParser::DataType type = make_class_enum_type(enum_name, parser->current_class, parser->script_path, false);4388if (element.parent_enum->identifier) {4389type.enum_type = element.parent_enum->identifier->name;4390}4391p_identifier->set_datatype(type);43924393if (element.resolved) {4394p_identifier->is_constant = true;4395p_identifier->reduced_value = element.value;4396} else {4397push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);4398}4399return; // Found anyway.4400}4401}4402}44034404bool found_source = false;4405// Check if identifier is local.4406// If that's the case, the declaration already was solved before.4407switch (p_identifier->source) {4408case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:4409p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());4410found_source = true;4411break;4412case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:4413case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:4414p_identifier->set_datatype(p_identifier->constant_source->get_datatype());4415p_identifier->is_constant = true;4416// TODO: Constant should have a value on the node itself.4417p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;4418found_source = true;4419break;4420case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:4421p_identifier->signal_source->usages++;4422[[fallthrough]];4423case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:4424mark_lambda_use_self();4425break;4426case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:4427mark_lambda_use_self();4428p_identifier->variable_source->usages++;4429[[fallthrough]];4430case GDScriptParser::IdentifierNode::STATIC_VARIABLE:4431case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:4432p_identifier->set_datatype(p_identifier->variable_source->get_datatype());4433found_source = true;4434#ifdef DEBUG_ENABLED4435if (p_identifier->variable_source && p_identifier->variable_source->assignments == 0 && !(p_identifier->get_datatype().is_hard_type() && p_identifier->get_datatype().kind == GDScriptParser::DataType::BUILTIN)) {4436parser->push_warning(p_identifier, GDScriptWarning::UNASSIGNED_VARIABLE, p_identifier->name);4437}4438#endif // DEBUG_ENABLED4439break;4440case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:4441p_identifier->set_datatype(p_identifier->bind_source->get_datatype());4442found_source = true;4443break;4444case GDScriptParser::IdentifierNode::LOCAL_BIND: {4445GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();4446result.is_constant = true;4447p_identifier->set_datatype(result);4448found_source = true;4449} break;4450case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:4451case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:4452case GDScriptParser::IdentifierNode::MEMBER_CLASS:4453case GDScriptParser::IdentifierNode::NATIVE_CLASS:4454break;4455}44564457#ifdef DEBUG_ENABLED4458if (!found_source && p_identifier->suite != nullptr && p_identifier->suite->has_local(p_identifier->name)) {4459parser->push_warning(p_identifier, GDScriptWarning::CONFUSABLE_LOCAL_USAGE, p_identifier->name);4460}4461#endif // DEBUG_ENABLED44624463// Not a local, so check members.44644465if (!found_source) {4466reduce_identifier_from_base(p_identifier);4467if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {4468// Found.4469found_source = true;4470}4471}44724473if (found_source) {4474const bool source_is_instance_variable = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4475const bool source_is_instance_function = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_FUNCTION && !p_identifier->function_source_is_static;4476const bool source_is_signal = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_SIGNAL;44774478if (static_context && (source_is_instance_variable || source_is_instance_function || source_is_signal)) {4479// Get the parent function above any lambda.4480GDScriptParser::FunctionNode *parent_function = parser->current_function;4481while (parent_function && parent_function->source_lambda) {4482parent_function = parent_function->source_lambda->parent_function;4483}44844485String source_type;4486if (source_is_instance_variable) {4487source_type = "non-static variable";4488} else if (source_is_instance_function) {4489source_type = "non-static function";4490} else { // source_is_signal4491source_type = "signal";4492}44934494if (parent_function) {4495push_error(vformat(R"*(Cannot access %s "%s" from the static function "%s()".)*", source_type, p_identifier->name, parent_function->identifier->name), p_identifier);4496} else {4497push_error(vformat(R"*(Cannot access %s "%s" from a static variable initializer.)*", source_type, p_identifier->name), p_identifier);4498}4499}45004501if (current_lambda != nullptr) {4502// If the identifier is a member variable (including the native class properties), member function, or a signal,4503// we consider the lambda to be using `self`, so we keep a reference to the current instance.4504if (source_is_instance_variable || source_is_instance_function || source_is_signal) {4505mark_lambda_use_self();4506return; // No need to capture.4507}45084509switch (p_identifier->source) {4510case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:4511case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:4512case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:4513case GDScriptParser::IdentifierNode::LOCAL_BIND:4514break; // Need to capture.4515case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE: // A global.4516case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:4517case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:4518case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:4519case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:4520case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:4521case GDScriptParser::IdentifierNode::MEMBER_CLASS:4522case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:4523case GDScriptParser::IdentifierNode::STATIC_VARIABLE:4524case GDScriptParser::IdentifierNode::NATIVE_CLASS:4525return; // No need to capture.4526}45274528GDScriptParser::FunctionNode *function_test = current_lambda->function;4529// Make sure we aren't capturing variable in the same lambda.4530// This also add captures for nested lambdas.4531while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {4532function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();4533function_test->source_lambda->captures.push_back(p_identifier);4534function_test = function_test->source_lambda->parent_function;4535}4536}45374538return;4539}45404541StringName name = p_identifier->name;4542p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;45434544// Not a local or a member, so check globals.45454546Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);4547if (builtin_type < Variant::VARIANT_MAX) {4548if (can_be_builtin) {4549p_identifier->set_datatype(make_builtin_meta_type(builtin_type));4550return;4551} else {4552push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);4553}4554}45554556if (class_exists(name)) {4557p_identifier->source = GDScriptParser::IdentifierNode::NATIVE_CLASS;4558p_identifier->set_datatype(make_native_meta_type(name));4559return;4560}45614562if (ScriptServer::is_global_class(name)) {4563p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));4564return;4565}45664567// Try singletons.4568// Do this before globals because this might be a singleton loading another one before it's compiled.4569if (ProjectSettings::get_singleton()->has_autoload(name)) {4570const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);4571if (autoload.is_singleton) {4572// Singleton exists, so it's at least a Node.4573GDScriptParser::DataType result;4574result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;4575result.kind = GDScriptParser::DataType::NATIVE;4576result.builtin_type = Variant::OBJECT;4577result.native_type = SNAME("Node");4578if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {4579Ref<GDScriptParserRef> single_parser = parser->get_depended_parser_for(autoload.path);4580if (single_parser.is_valid()) {4581Error err = single_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);4582if (err == OK) {4583result = type_from_metatype(single_parser->get_parser()->head->get_datatype());4584}4585}4586} else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {4587if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {4588Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);4589Node *node = Object::cast_to<Node>(constant);4590if (node != nullptr) {4591Ref<GDScript> scr = node->get_script();4592if (scr.is_valid()) {4593Ref<GDScriptParserRef> single_parser = parser->get_depended_parser_for(scr->get_script_path());4594if (single_parser.is_valid()) {4595Error err = single_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);4596if (err == OK) {4597result = type_from_metatype(single_parser->get_parser()->head->get_datatype());4598}4599}4600}4601}4602}4603}4604result.is_constant = true;4605p_identifier->set_datatype(result);4606return;4607}4608}46094610if (CoreConstants::is_global_constant(name)) {4611int index = CoreConstants::get_global_constant_index(name);4612StringName enum_name = CoreConstants::get_global_constant_enum(index);4613int64_t value = CoreConstants::get_global_constant_value(index);4614if (enum_name != StringName()) {4615p_identifier->set_datatype(make_global_enum_type(enum_name, StringName(), false));4616} else {4617p_identifier->set_datatype(type_from_variant(value, p_identifier));4618}4619p_identifier->is_constant = true;4620p_identifier->reduced_value = value;4621return;4622}46234624if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {4625Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);4626p_identifier->set_datatype(type_from_variant(constant, p_identifier));4627p_identifier->is_constant = true;4628p_identifier->reduced_value = constant;4629return;4630}46314632if (CoreConstants::is_global_enum(name)) {4633p_identifier->set_datatype(make_global_enum_type(name, StringName(), true));4634if (!can_be_builtin) {4635push_error(vformat(R"(Global enum "%s" cannot be used on its own.)", name), p_identifier);4636}4637return;4638}46394640if (Variant::has_utility_function(name) || GDScriptUtilityFunctions::function_exists(name)) {4641p_identifier->is_constant = true;4642p_identifier->reduced_value = Callable(memnew(GDScriptUtilityCallable(name)));4643MethodInfo method_info;4644if (GDScriptUtilityFunctions::function_exists(name)) {4645method_info = GDScriptUtilityFunctions::get_function_info(name);4646} else {4647method_info = Variant::get_utility_function_info(name);4648}4649p_identifier->set_datatype(make_callable_type(method_info));4650return;4651}46524653// Allow "Variant" here since it might be used for nested enums.4654if (can_be_builtin && name == SNAME("Variant")) {4655GDScriptParser::DataType variant;4656variant.kind = GDScriptParser::DataType::VARIANT;4657variant.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;4658variant.is_meta_type = true;4659variant.is_pseudo_type = true;4660p_identifier->set_datatype(variant);4661return;4662}46634664// Not found.4665#ifdef SUGGEST_GODOT4_RENAMES4666String rename_hint;4667if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4668const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4669if (renamed_identifier_name) {4670rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4671}4672}4673push_error(vformat(R"(Identifier "%s" not declared in the current scope.%s)", name, rename_hint), p_identifier);4674#else4675push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);4676#endif // SUGGEST_GODOT4_RENAMES4677GDScriptParser::DataType dummy;4678dummy.kind = GDScriptParser::DataType::VARIANT;4679p_identifier->set_datatype(dummy); // Just so type is set to something.4680}46814682void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {4683// Lambda is always a Callable.4684GDScriptParser::DataType lambda_type;4685lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;4686lambda_type.kind = GDScriptParser::DataType::BUILTIN;4687lambda_type.builtin_type = Variant::CALLABLE;4688p_lambda->set_datatype(lambda_type);46894690if (p_lambda->function == nullptr) {4691return;4692}46934694GDScriptParser::LambdaNode *previous_lambda = current_lambda;4695current_lambda = p_lambda;4696resolve_function_signature(p_lambda->function, p_lambda, true);4697current_lambda = previous_lambda;46984699pending_body_resolution_lambdas.push_back(p_lambda);4700}47014702void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {4703p_literal->reduced_value = p_literal->value;4704p_literal->is_constant = true;47054706p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));4707}47084709void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {4710if (!p_preload->path) {4711return;4712}47134714reduce_expression(p_preload->path);47154716if (!p_preload->path->is_constant) {4717push_error("Preloaded path must be a constant string.", p_preload->path);4718return;4719}47204721if (p_preload->path->reduced_value.get_type() != Variant::STRING) {4722push_error("Preloaded path must be a constant string.", p_preload->path);4723} else {4724p_preload->resolved_path = p_preload->path->reduced_value;4725// TODO: Save this as script dependency.4726if (p_preload->resolved_path.is_relative_path()) {4727p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);4728}4729p_preload->resolved_path = p_preload->resolved_path.simplify_path();4730if (!ResourceLoader::exists(p_preload->resolved_path)) {4731Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);47324733if (file_check->file_exists(p_preload->resolved_path)) {4734push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);4735} else {4736push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);4737}4738} else {4739// TODO: Don't load if validating: use completion cache.47404741// Must load GDScript separately to permit cyclic references4742// as ResourceLoader::load() detects and rejects those.4743const String &res_type = ResourceLoader::get_resource_type(p_preload->resolved_path);4744if (res_type == "GDScript") {4745Error err = OK;4746Ref<GDScript> res = get_depended_shallow_script(p_preload->resolved_path, err);4747p_preload->resource = res;4748if (err != OK) {4749push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);4750}4751} else {4752Error err = OK;4753p_preload->resource = ResourceLoader::load(p_preload->resolved_path, res_type, ResourceFormatLoader::CACHE_MODE_REUSE, &err);4754if (err == ERR_BUSY) {4755p_preload->resource = ResourceLoader::ensure_resource_ref_override_for_outer_load(p_preload->resolved_path, res_type);4756}4757if (p_preload->resource.is_null()) {4758push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);4759}4760}4761}4762}47634764p_preload->is_constant = true;4765p_preload->reduced_value = p_preload->resource;4766p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));47674768// TODO: Not sure if this is necessary anymore.4769// 'type_from_variant()' should call 'resolve_class_inheritance()' which would call 'ensure_cached_external_parser_for_class()'4770// Better safe than sorry.4771ensure_cached_external_parser_for_class(p_preload->get_datatype().class_type, nullptr, "Trying to resolve preload", p_preload);4772}47734774void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {4775p_self->is_constant = false;4776p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));4777mark_lambda_use_self();4778}47794780void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript, bool p_can_be_pseudo_type) {4781if (p_subscript->base == nullptr) {4782return;4783}4784if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {4785reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);4786} else if (p_subscript->base->type == GDScriptParser::Node::SUBSCRIPT) {4787reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_subscript->base), true);4788} else {4789reduce_expression(p_subscript->base);4790}47914792GDScriptParser::DataType result_type;47934794if (p_subscript->is_attribute) {4795if (p_subscript->attribute == nullptr) {4796return;4797}47984799GDScriptParser::DataType base_type = p_subscript->base->get_datatype();4800bool valid = false;48014802// If the base is a metatype, use the analyzer instead.4803if (p_subscript->base->is_constant && !base_type.is_meta_type) {4804// GH-92534. If the base is a GDScript, use the analyzer instead.4805bool base_is_gdscript = false;4806if (p_subscript->base->reduced_value.get_type() == Variant::OBJECT) {4807Ref<GDScript> gdscript = Object::cast_to<GDScript>(p_subscript->base->reduced_value.get_validated_object());4808if (gdscript.is_valid()) {4809base_is_gdscript = true;4810// Makes a metatype from a constant GDScript, since `base_type` is not a metatype.4811GDScriptParser::DataType base_type_meta = type_from_variant(gdscript, p_subscript);4812// First try to reduce the attribute from the metatype.4813reduce_identifier_from_base(p_subscript->attribute, &base_type_meta);4814GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4815if (attr_type.is_set()) {4816valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;4817result_type = attr_type;4818p_subscript->is_constant = p_subscript->attribute->is_constant;4819p_subscript->reduced_value = p_subscript->attribute->reduced_value;4820}4821if (!valid) {4822// If unsuccessful, reset and return to the normal route.4823p_subscript->attribute->set_datatype(GDScriptParser::DataType());4824}4825}4826}4827if (!base_is_gdscript) {4828// Just try to get it.4829Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);4830if (valid) {4831p_subscript->is_constant = true;4832p_subscript->reduced_value = value;4833result_type = type_from_variant(value, p_subscript);4834}4835}4836}48374838if (valid) {4839// Do nothing.4840} else if (base_type.is_variant() || !base_type.is_hard_type()) {4841valid = !base_type.is_pseudo_type || p_can_be_pseudo_type;4842result_type.kind = GDScriptParser::DataType::VARIANT;4843if (base_type.is_variant() && base_type.is_hard_type() && base_type.is_meta_type && base_type.is_pseudo_type) {4844// Special case: it may be a global enum with pseudo base (e.g. Variant.Type).4845String enum_name;4846if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {4847enum_name = String(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base)->name) + ENUM_SEPARATOR + String(p_subscript->attribute->name);4848}4849if (CoreConstants::is_global_enum(enum_name)) {4850result_type = make_global_enum_type(enum_name, StringName());4851} else {4852valid = false;4853mark_node_unsafe(p_subscript);4854}4855} else {4856mark_node_unsafe(p_subscript);4857}4858} else {4859reduce_identifier_from_base(p_subscript->attribute, &base_type);4860GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4861if (attr_type.is_set()) {4862if (base_type.builtin_type == Variant::DICTIONARY && base_type.has_container_element_types()) {4863Variant::Type key_type = base_type.get_container_element_type_or_variant(0).builtin_type;4864valid = key_type == Variant::NIL || key_type == Variant::STRING || key_type == Variant::STRING_NAME;4865if (base_type.has_container_element_type(1)) {4866result_type = base_type.get_container_element_type(1);4867result_type.type_source = base_type.type_source;4868} else {4869result_type.builtin_type = Variant::NIL;4870result_type.kind = GDScriptParser::DataType::VARIANT;4871result_type.type_source = GDScriptParser::DataType::UNDETECTED;4872}4873} else {4874valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;4875result_type = attr_type;4876p_subscript->is_constant = p_subscript->attribute->is_constant;4877p_subscript->reduced_value = p_subscript->attribute->reduced_value;4878}4879} else if (!base_type.is_meta_type || !base_type.is_constant) {4880valid = base_type.kind != GDScriptParser::DataType::BUILTIN;4881#ifdef DEBUG_ENABLED4882if (valid) {4883parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());4884}4885#endif // DEBUG_ENABLED4886result_type.kind = GDScriptParser::DataType::VARIANT;4887mark_node_unsafe(p_subscript);4888}4889}48904891if (!valid) {4892GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4893if (!p_can_be_pseudo_type && (attr_type.is_pseudo_type || result_type.is_pseudo_type)) {4894push_error(vformat(R"(Type "%s" in base "%s" cannot be used on its own.)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);4895} else {4896push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);4897}4898result_type.kind = GDScriptParser::DataType::VARIANT;4899}4900} else {4901if (p_subscript->index == nullptr) {4902return;4903}4904reduce_expression(p_subscript->index);49054906if (p_subscript->base->is_constant && p_subscript->index->is_constant) {4907// Just try to get it.4908bool valid = false;4909// TODO: Check if `p_subscript->base->reduced_value` is GDScript.4910Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);4911if (!valid) {4912push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);4913result_type.kind = GDScriptParser::DataType::VARIANT;4914} else {4915p_subscript->is_constant = true;4916p_subscript->reduced_value = value;4917result_type = type_from_variant(value, p_subscript);4918}4919} else {4920GDScriptParser::DataType base_type = p_subscript->base->get_datatype();4921GDScriptParser::DataType index_type = p_subscript->index->get_datatype();49224923if (base_type.is_variant()) {4924result_type.kind = GDScriptParser::DataType::VARIANT;4925mark_node_unsafe(p_subscript);4926} else {4927if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {4928// Check if indexing is valid.4929bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;4930if (!error) {4931switch (base_type.builtin_type) {4932// Expect int or real as index.4933case Variant::PACKED_BYTE_ARRAY:4934case Variant::PACKED_FLOAT32_ARRAY:4935case Variant::PACKED_FLOAT64_ARRAY:4936case Variant::PACKED_INT32_ARRAY:4937case Variant::PACKED_INT64_ARRAY:4938case Variant::PACKED_STRING_ARRAY:4939case Variant::PACKED_VECTOR2_ARRAY:4940case Variant::PACKED_VECTOR3_ARRAY:4941case Variant::PACKED_COLOR_ARRAY:4942case Variant::PACKED_VECTOR4_ARRAY:4943case Variant::ARRAY:4944case Variant::STRING:4945error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;4946break;4947// Expect String only.4948case Variant::RECT2:4949case Variant::RECT2I:4950case Variant::PLANE:4951case Variant::QUATERNION:4952case Variant::AABB:4953case Variant::OBJECT:4954error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4955break;4956// Expect String or number.4957case Variant::BASIS:4958case Variant::VECTOR2:4959case Variant::VECTOR2I:4960case Variant::VECTOR3:4961case Variant::VECTOR3I:4962case Variant::VECTOR4:4963case Variant::VECTOR4I:4964case Variant::TRANSFORM2D:4965case Variant::TRANSFORM3D:4966case Variant::PROJECTION:4967error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&4968index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4969break;4970// Expect String or int.4971case Variant::COLOR:4972error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4973break;4974// Don't support indexing, but we will check it later.4975case Variant::RID:4976case Variant::BOOL:4977case Variant::CALLABLE:4978case Variant::FLOAT:4979case Variant::INT:4980case Variant::NIL:4981case Variant::NODE_PATH:4982case Variant::SIGNAL:4983case Variant::STRING_NAME:4984break;4985// Support depends on if the dictionary has a typed key, otherwise anything is valid.4986case Variant::DICTIONARY:4987if (base_type.has_container_element_type(0)) {4988GDScriptParser::DataType key_type = base_type.get_container_element_type(0);4989switch (index_type.builtin_type) {4990// Null value will be treated as an empty object, allow.4991case Variant::NIL:4992error = key_type.builtin_type != Variant::OBJECT;4993break;4994// Objects are parsed for validity in a similar manner to container types.4995case Variant::OBJECT:4996if (key_type.builtin_type == Variant::OBJECT) {4997error = !key_type.can_reference(index_type);4998} else {4999error = key_type.builtin_type != Variant::NIL;5000}5001break;5002// String and StringName interchangeable in this context.5003case Variant::STRING:5004case Variant::STRING_NAME:5005error = key_type.builtin_type != Variant::STRING_NAME && key_type.builtin_type != Variant::STRING;5006break;5007// Ints are valid indices for floats, but not the other way around.5008case Variant::INT:5009error = key_type.builtin_type != Variant::INT && key_type.builtin_type != Variant::FLOAT;5010break;5011// All other cases require the types to match exactly.5012default:5013error = key_type.builtin_type != index_type.builtin_type;5014break;5015}5016}5017break;5018// Here for completeness.5019case Variant::VARIANT_MAX:5020break;5021}50225023if (error) {5024push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);5025}5026}5027} else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {5028if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {5029push_error(vformat(R"(Only "String" or "StringName" can be used as index for type "%s", but received "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);5030}5031}50325033// Check resulting type if possible.5034result_type.builtin_type = Variant::NIL;5035result_type.kind = GDScriptParser::DataType::BUILTIN;5036result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;50375038if (base_type.kind != GDScriptParser::DataType::BUILTIN) {5039base_type.builtin_type = Variant::OBJECT;5040}5041switch (base_type.builtin_type) {5042// Can't index at all.5043case Variant::RID:5044case Variant::BOOL:5045case Variant::CALLABLE:5046case Variant::FLOAT:5047case Variant::INT:5048case Variant::NIL:5049case Variant::NODE_PATH:5050case Variant::SIGNAL:5051case Variant::STRING_NAME:5052result_type.kind = GDScriptParser::DataType::VARIANT;5053push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);5054break;5055// Return int.5056case Variant::PACKED_BYTE_ARRAY:5057case Variant::PACKED_INT32_ARRAY:5058case Variant::PACKED_INT64_ARRAY:5059case Variant::VECTOR2I:5060case Variant::VECTOR3I:5061case Variant::VECTOR4I:5062result_type.builtin_type = Variant::INT;5063break;5064// Return float.5065case Variant::PACKED_FLOAT32_ARRAY:5066case Variant::PACKED_FLOAT64_ARRAY:5067case Variant::VECTOR2:5068case Variant::VECTOR3:5069case Variant::VECTOR4:5070case Variant::QUATERNION:5071result_type.builtin_type = Variant::FLOAT;5072break;5073// Return String.5074case Variant::PACKED_STRING_ARRAY:5075case Variant::STRING:5076result_type.builtin_type = Variant::STRING;5077break;5078// Return Vector2.5079case Variant::PACKED_VECTOR2_ARRAY:5080case Variant::TRANSFORM2D:5081case Variant::RECT2:5082result_type.builtin_type = Variant::VECTOR2;5083break;5084// Return Vector2I.5085case Variant::RECT2I:5086result_type.builtin_type = Variant::VECTOR2I;5087break;5088// Return Vector3.5089case Variant::PACKED_VECTOR3_ARRAY:5090case Variant::AABB:5091case Variant::BASIS:5092result_type.builtin_type = Variant::VECTOR3;5093break;5094// Return Color.5095case Variant::PACKED_COLOR_ARRAY:5096result_type.builtin_type = Variant::COLOR;5097break;5098// Return Vector4.5099case Variant::PACKED_VECTOR4_ARRAY:5100result_type.builtin_type = Variant::VECTOR4;5101break;5102// Depends on the index.5103case Variant::TRANSFORM3D:5104case Variant::PROJECTION:5105case Variant::PLANE:5106case Variant::COLOR:5107case Variant::OBJECT:5108result_type.kind = GDScriptParser::DataType::VARIANT;5109result_type.type_source = GDScriptParser::DataType::UNDETECTED;5110break;5111// Can have an element type.5112case Variant::ARRAY:5113if (base_type.has_container_element_type(0)) {5114result_type = base_type.get_container_element_type(0);5115result_type.type_source = base_type.type_source;5116} else {5117result_type.kind = GDScriptParser::DataType::VARIANT;5118result_type.type_source = GDScriptParser::DataType::UNDETECTED;5119}5120break;5121// Can have two element types, but we only care about the value.5122case Variant::DICTIONARY:5123if (base_type.has_container_element_type(1)) {5124result_type = base_type.get_container_element_type(1);5125result_type.type_source = base_type.type_source;5126} else {5127result_type.kind = GDScriptParser::DataType::VARIANT;5128result_type.type_source = GDScriptParser::DataType::UNDETECTED;5129}5130break;5131// Here for completeness.5132case Variant::VARIANT_MAX:5133break;5134}5135}5136}5137}51385139p_subscript->set_datatype(result_type);5140}51415142void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op, bool p_is_root) {5143reduce_expression(p_ternary_op->condition);5144reduce_expression(p_ternary_op->true_expr, p_is_root);5145reduce_expression(p_ternary_op->false_expr, p_is_root);51465147GDScriptParser::DataType result;51485149if (p_ternary_op->condition && p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr && p_ternary_op->false_expr->is_constant) {5150p_ternary_op->is_constant = true;5151if (p_ternary_op->condition->reduced_value.booleanize()) {5152p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;5153} else {5154p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;5155}5156}51575158GDScriptParser::DataType true_type;5159if (p_ternary_op->true_expr) {5160true_type = p_ternary_op->true_expr->get_datatype();5161} else {5162true_type.kind = GDScriptParser::DataType::VARIANT;5163}5164GDScriptParser::DataType false_type;5165if (p_ternary_op->false_expr) {5166false_type = p_ternary_op->false_expr->get_datatype();5167} else {5168false_type.kind = GDScriptParser::DataType::VARIANT;5169}51705171if (true_type.is_variant() || false_type.is_variant()) {5172result.kind = GDScriptParser::DataType::VARIANT;5173} else {5174result = true_type;5175if (!is_type_compatible(true_type, false_type)) {5176result = false_type;5177if (!is_type_compatible(false_type, true_type)) {5178result.kind = GDScriptParser::DataType::VARIANT;5179#ifdef DEBUG_ENABLED5180parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);5181#endif // DEBUG_ENABLED5182}5183}5184}5185result.type_source = true_type.is_hard_type() && false_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;51865187p_ternary_op->set_datatype(result);5188}51895190void GDScriptAnalyzer::reduce_type_test(GDScriptParser::TypeTestNode *p_type_test) {5191GDScriptParser::DataType result;5192result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5193result.kind = GDScriptParser::DataType::BUILTIN;5194result.builtin_type = Variant::BOOL;5195p_type_test->set_datatype(result);51965197if (!p_type_test->operand || !p_type_test->test_type) {5198return;5199}52005201reduce_expression(p_type_test->operand);5202GDScriptParser::DataType operand_type = p_type_test->operand->get_datatype();5203GDScriptParser::DataType test_type = type_from_metatype(resolve_datatype(p_type_test->test_type));5204p_type_test->test_datatype = test_type;52055206if (!operand_type.is_set() || !test_type.is_set()) {5207return;5208}52095210if (p_type_test->operand->is_constant) {5211p_type_test->is_constant = true;5212p_type_test->reduced_value = false;52135214if (!is_type_compatible(test_type, operand_type)) {5215push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);5216} else if (is_type_compatible(test_type, type_from_variant(p_type_test->operand->reduced_value, p_type_test->operand))) {5217p_type_test->reduced_value = test_type.builtin_type != Variant::OBJECT || !p_type_test->operand->reduced_value.is_null();5218}52195220return;5221}52225223if (!is_type_compatible(test_type, operand_type) && !is_type_compatible(operand_type, test_type)) {5224if (operand_type.is_hard_type()) {5225push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);5226} else {5227downgrade_node_type_source(p_type_test->operand);5228}5229}5230}52315232void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {5233reduce_expression(p_unary_op->operand);52345235GDScriptParser::DataType result;52365237if (p_unary_op->operand == nullptr) {5238result.kind = GDScriptParser::DataType::VARIANT;5239p_unary_op->set_datatype(result);5240return;5241}52425243GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();52445245if (p_unary_op->operand->is_constant) {5246p_unary_op->is_constant = true;5247p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());5248result = type_from_variant(p_unary_op->reduced_value, p_unary_op);5249}52505251if (operand_type.is_variant()) {5252result.kind = GDScriptParser::DataType::VARIANT;5253mark_node_unsafe(p_unary_op);5254} else {5255bool valid = false;5256result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);52575258if (!valid) {5259push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", operand_type.to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op);5260}5261}52625263p_unary_op->set_datatype(result);5264}52655266Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {5267if (p_expression == nullptr) {5268return Variant();5269}52705271if (p_expression->is_constant) {5272is_reduced = true;5273return p_expression->reduced_value;5274}52755276switch (p_expression->type) {5277case GDScriptParser::Node::ARRAY:5278return make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);5279case GDScriptParser::Node::DICTIONARY:5280return make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);5281case GDScriptParser::Node::SUBSCRIPT:5282return make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);5283case GDScriptParser::Node::CALL:5284return make_call_reduced_value(static_cast<GDScriptParser::CallNode *>(p_expression), is_reduced);5285default:5286break;5287}52885289return Variant();5290}52915292Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {5293Array array = p_array->get_datatype().has_container_element_type(0) ? make_array_from_element_datatype(p_array->get_datatype().get_container_element_type(0)) : Array();52945295array.resize(p_array->elements.size());5296for (int i = 0; i < p_array->elements.size(); i++) {5297GDScriptParser::ExpressionNode *element = p_array->elements[i];52985299bool is_element_value_reduced = false;5300Variant element_value = make_expression_reduced_value(element, is_element_value_reduced);5301if (!is_element_value_reduced) {5302return Variant();5303}53045305array[i] = element_value;5306}53075308array.make_read_only();53095310is_reduced = true;5311return array;5312}53135314Variant GDScriptAnalyzer::make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced) {5315Dictionary dictionary = p_dictionary->get_datatype().has_container_element_types()5316? make_dictionary_from_element_datatype(p_dictionary->get_datatype().get_container_element_type_or_variant(0), p_dictionary->get_datatype().get_container_element_type_or_variant(1))5317: Dictionary();53185319for (int i = 0; i < p_dictionary->elements.size(); i++) {5320const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];53215322bool is_element_key_reduced = false;5323Variant element_key = make_expression_reduced_value(element.key, is_element_key_reduced);5324if (!is_element_key_reduced) {5325return Variant();5326}53275328bool is_element_value_reduced = false;5329Variant element_value = make_expression_reduced_value(element.value, is_element_value_reduced);5330if (!is_element_value_reduced) {5331return Variant();5332}53335334dictionary[element_key] = element_value;5335}53365337dictionary.make_read_only();53385339is_reduced = true;5340return dictionary;5341}53425343Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced) {5344if (p_subscript->base == nullptr || p_subscript->index == nullptr) {5345return Variant();5346}53475348bool is_base_value_reduced = false;5349Variant base_value = make_expression_reduced_value(p_subscript->base, is_base_value_reduced);5350if (!is_base_value_reduced) {5351return Variant();5352}53535354if (p_subscript->is_attribute) {5355bool is_valid = false;5356Variant value = base_value.get_named(p_subscript->attribute->name, is_valid);5357if (is_valid) {5358is_reduced = true;5359return value;5360} else {5361return Variant();5362}5363} else {5364bool is_index_value_reduced = false;5365Variant index_value = make_expression_reduced_value(p_subscript->index, is_index_value_reduced);5366if (!is_index_value_reduced) {5367return Variant();5368}53695370bool is_valid = false;5371Variant value = base_value.get(index_value, &is_valid);5372if (is_valid) {5373is_reduced = true;5374return value;5375} else {5376return Variant();5377}5378}5379}53805381Variant GDScriptAnalyzer::make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced) {5382if (p_call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {5383Variant::Type type = Variant::NIL;5384if (p_call->function_name == SNAME("Array")) {5385type = Variant::ARRAY;5386} else if (p_call->function_name == SNAME("Dictionary")) {5387type = Variant::DICTIONARY;5388} else {5389return Variant();5390}53915392Vector<Variant> args;5393args.resize(p_call->arguments.size());5394const Variant **argptrs = (const Variant **)alloca(sizeof(const Variant *) * args.size());5395for (int i = 0; i < p_call->arguments.size(); i++) {5396bool is_arg_value_reduced = false;5397Variant arg_value = make_expression_reduced_value(p_call->arguments[i], is_arg_value_reduced);5398if (!is_arg_value_reduced) {5399return Variant();5400}5401args.write[i] = arg_value;5402argptrs[i] = &args[i];5403}54045405Variant result;5406Callable::CallError ce;5407Variant::construct(type, result, argptrs, args.size(), ce);5408if (ce.error) {5409push_error(vformat(R"(Failed to construct "%s".)", Variant::get_type_name(type)), p_call);5410return Variant();5411}54125413if (type == Variant::ARRAY) {5414Array array = result;5415array.make_read_only();5416} else if (type == Variant::DICTIONARY) {5417Dictionary dictionary = result;5418dictionary.make_read_only();5419}54205421is_reduced = true;5422return result;5423}54245425return Variant();5426}54275428Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {5429Array array;54305431if (p_element_datatype.builtin_type == Variant::OBJECT) {5432Ref<Script> script_type = p_element_datatype.script_type;5433if (p_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5434Error err = OK;5435Ref<GDScript> scr = get_depended_shallow_script(p_element_datatype.script_path, err);5436if (err) {5437push_error(vformat(R"(Error while getting cache for script "%s".)", p_element_datatype.script_path), p_source_node);5438return array;5439}5440script_type.reference_ptr(scr->find_class(p_element_datatype.class_type->fqcn));5441}54425443array.set_typed(p_element_datatype.builtin_type, p_element_datatype.native_type, script_type);5444} else {5445array.set_typed(p_element_datatype.builtin_type, StringName(), Variant());5446}54475448return array;5449}54505451Dictionary GDScriptAnalyzer::make_dictionary_from_element_datatype(const GDScriptParser::DataType &p_key_element_datatype, const GDScriptParser::DataType &p_value_element_datatype, const GDScriptParser::Node *p_source_node) {5452Dictionary dictionary;5453StringName key_name;5454Variant key_script;5455StringName value_name;5456Variant value_script;54575458if (p_key_element_datatype.builtin_type == Variant::OBJECT) {5459Ref<Script> script_type = p_key_element_datatype.script_type;5460if (p_key_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5461Error err = OK;5462Ref<GDScript> scr = get_depended_shallow_script(p_key_element_datatype.script_path, err);5463if (err) {5464push_error(vformat(R"(Error while getting cache for script "%s".)", p_key_element_datatype.script_path), p_source_node);5465return dictionary;5466}5467script_type.reference_ptr(scr->find_class(p_key_element_datatype.class_type->fqcn));5468}54695470key_name = p_key_element_datatype.native_type;5471key_script = script_type;5472}54735474if (p_value_element_datatype.builtin_type == Variant::OBJECT) {5475Ref<Script> script_type = p_value_element_datatype.script_type;5476if (p_value_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5477Error err = OK;5478Ref<GDScript> scr = get_depended_shallow_script(p_value_element_datatype.script_path, err);5479if (err) {5480push_error(vformat(R"(Error while getting cache for script "%s".)", p_value_element_datatype.script_path), p_source_node);5481return dictionary;5482}5483script_type.reference_ptr(scr->find_class(p_value_element_datatype.class_type->fqcn));5484}54855486value_name = p_value_element_datatype.native_type;5487value_script = script_type;5488}54895490dictionary.set_typed(p_key_element_datatype.builtin_type, key_name, key_script, p_value_element_datatype.builtin_type, value_name, value_script);5491return dictionary;5492}54935494Variant GDScriptAnalyzer::make_variable_default_value(GDScriptParser::VariableNode *p_variable) {5495Variant result = Variant();54965497if (p_variable->initializer) {5498bool is_initializer_value_reduced = false;5499Variant initializer_value = make_expression_reduced_value(p_variable->initializer, is_initializer_value_reduced);5500if (is_initializer_value_reduced) {5501result = initializer_value;5502}5503} else {5504GDScriptParser::DataType datatype = p_variable->get_datatype();5505if (datatype.is_hard_type()) {5506if (datatype.kind == GDScriptParser::DataType::BUILTIN && datatype.builtin_type != Variant::OBJECT) {5507if (datatype.builtin_type == Variant::ARRAY && datatype.has_container_element_type(0)) {5508result = make_array_from_element_datatype(datatype.get_container_element_type(0));5509} else if (datatype.builtin_type == Variant::DICTIONARY && datatype.has_container_element_types()) {5510GDScriptParser::DataType key = datatype.get_container_element_type_or_variant(0);5511GDScriptParser::DataType value = datatype.get_container_element_type_or_variant(1);5512result = make_dictionary_from_element_datatype(key, value);5513} else {5514VariantInternal::initialize(&result, datatype.builtin_type);5515}5516} else if (datatype.kind == GDScriptParser::DataType::ENUM) {5517result = 0;5518}5519}5520}55215522return result;5523}55245525GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {5526GDScriptParser::DataType result;5527result.is_constant = true;5528result.kind = GDScriptParser::DataType::BUILTIN;5529result.builtin_type = p_value.get_type();5530result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.55315532if (p_value.get_type() == Variant::ARRAY) {5533const Array &array = p_value;5534if (array.get_typed_script()) {5535result.set_container_element_type(0, type_from_metatype(make_script_meta_type(array.get_typed_script())));5536} else if (array.get_typed_class_name()) {5537result.set_container_element_type(0, type_from_metatype(make_native_meta_type(array.get_typed_class_name())));5538} else if (array.get_typed_builtin() != Variant::NIL) {5539result.set_container_element_type(0, type_from_metatype(make_builtin_meta_type((Variant::Type)array.get_typed_builtin())));5540}5541} else if (p_value.get_type() == Variant::DICTIONARY) {5542const Dictionary &dict = p_value;5543if (dict.get_typed_key_script()) {5544result.set_container_element_type(0, type_from_metatype(make_script_meta_type(dict.get_typed_key_script())));5545} else if (dict.get_typed_key_class_name()) {5546result.set_container_element_type(0, type_from_metatype(make_native_meta_type(dict.get_typed_key_class_name())));5547} else if (dict.get_typed_key_builtin() != Variant::NIL) {5548result.set_container_element_type(0, type_from_metatype(make_builtin_meta_type((Variant::Type)dict.get_typed_key_builtin())));5549}5550if (dict.get_typed_value_script()) {5551result.set_container_element_type(1, type_from_metatype(make_script_meta_type(dict.get_typed_value_script())));5552} else if (dict.get_typed_value_class_name()) {5553result.set_container_element_type(1, type_from_metatype(make_native_meta_type(dict.get_typed_value_class_name())));5554} else if (dict.get_typed_value_builtin() != Variant::NIL) {5555result.set_container_element_type(1, type_from_metatype(make_builtin_meta_type((Variant::Type)dict.get_typed_value_builtin())));5556}5557} else if (p_value.get_type() == Variant::OBJECT) {5558// Object is treated as a native type, not a builtin type.5559result.kind = GDScriptParser::DataType::NATIVE;55605561Object *obj = p_value;5562if (!obj) {5563return GDScriptParser::DataType();5564}5565result.native_type = obj->get_class_name();55665567Ref<Script> scr = p_value; // Check if value is a script itself.5568if (scr.is_valid()) {5569result.is_meta_type = true;5570} else {5571result.is_meta_type = false;5572scr = obj->get_script();5573}5574if (scr.is_valid()) {5575Ref<GDScript> gds = scr;5576if (gds.is_valid()) {5577// This might be an inner class, so we want to get the parser for the root.5578// But still get the inner class from that tree.5579String script_path = gds->get_script_path();5580Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(script_path);5581if (ref.is_null()) {5582push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);5583GDScriptParser::DataType error_type;5584error_type.kind = GDScriptParser::DataType::VARIANT;5585return error_type;5586}5587Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);5588GDScriptParser::ClassNode *found = nullptr;5589if (err == OK) {5590found = ref->get_parser()->find_class(gds->fully_qualified_name);5591if (found != nullptr) {5592err = resolve_class_inheritance(found, p_source);5593}5594}5595if (err || found == nullptr) {5596push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);5597GDScriptParser::DataType error_type;5598error_type.kind = GDScriptParser::DataType::VARIANT;5599return error_type;5600}56015602result.kind = GDScriptParser::DataType::CLASS;5603result.native_type = found->get_datatype().native_type;5604result.class_type = found;5605result.script_path = ref->get_parser()->script_path;5606} else {5607result.kind = GDScriptParser::DataType::SCRIPT;5608result.native_type = scr->get_instance_base_type();5609result.script_path = scr->get_path();5610}5611result.script_type = scr;5612} else {5613result.kind = GDScriptParser::DataType::NATIVE;5614if (result.native_type == GDScriptNativeClass::get_class_static()) {5615result.is_meta_type = true;5616}5617}5618}56195620return result;5621}56225623GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) {5624GDScriptParser::DataType result = p_meta_type;5625result.is_meta_type = false;5626result.is_pseudo_type = false;5627if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {5628result.builtin_type = Variant::INT;5629} else {5630result.is_constant = false;5631}5632return result;5633}56345635GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg, bool p_is_readonly) const {5636GDScriptParser::DataType result;5637result.is_read_only = p_is_readonly;5638result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5639if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {5640// Variant5641result.kind = GDScriptParser::DataType::VARIANT;5642return result;5643}5644result.builtin_type = p_property.type;5645if (p_property.type == Variant::OBJECT) {5646if (ScriptServer::is_global_class(p_property.class_name)) {5647result.kind = GDScriptParser::DataType::SCRIPT;5648result.script_path = ScriptServer::get_global_class_path(p_property.class_name);5649result.native_type = ScriptServer::get_global_class_native_base(p_property.class_name);56505651Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_property.class_name));5652if (scr.is_valid()) {5653result.script_type = scr;5654}5655} else {5656result.kind = GDScriptParser::DataType::NATIVE;5657result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;5658}5659} else {5660result.kind = GDScriptParser::DataType::BUILTIN;5661result.builtin_type = p_property.type;5662if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {5663// Check element type.5664StringName elem_type_name = p_property.hint_string;5665GDScriptParser::DataType elem_type;5666elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;56675668Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);5669if (elem_builtin_type < Variant::VARIANT_MAX) {5670// Builtin type.5671elem_type.kind = GDScriptParser::DataType::BUILTIN;5672elem_type.builtin_type = elem_builtin_type;5673} else if (class_exists(elem_type_name)) {5674elem_type.kind = GDScriptParser::DataType::NATIVE;5675elem_type.builtin_type = Variant::OBJECT;5676elem_type.native_type = elem_type_name;5677} else if (ScriptServer::is_global_class(elem_type_name)) {5678// Just load this as it shouldn't be a GDScript.5679Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));5680elem_type.kind = GDScriptParser::DataType::SCRIPT;5681elem_type.builtin_type = Variant::OBJECT;5682elem_type.native_type = script->get_instance_base_type();5683elem_type.script_type = script;5684} else {5685ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");5686}5687elem_type.is_constant = false;5688result.set_container_element_type(0, elem_type);5689} else if (p_property.type == Variant::DICTIONARY && p_property.hint == PROPERTY_HINT_DICTIONARY_TYPE) {5690// Check element type.5691StringName key_elem_type_name = p_property.hint_string.get_slicec(';', 0);5692GDScriptParser::DataType key_elem_type;5693key_elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;56945695Variant::Type key_elem_builtin_type = GDScriptParser::get_builtin_type(key_elem_type_name);5696if (key_elem_builtin_type < Variant::VARIANT_MAX) {5697// Builtin type.5698key_elem_type.kind = GDScriptParser::DataType::BUILTIN;5699key_elem_type.builtin_type = key_elem_builtin_type;5700} else if (class_exists(key_elem_type_name)) {5701key_elem_type.kind = GDScriptParser::DataType::NATIVE;5702key_elem_type.builtin_type = Variant::OBJECT;5703key_elem_type.native_type = key_elem_type_name;5704} else if (ScriptServer::is_global_class(key_elem_type_name)) {5705// Just load this as it shouldn't be a GDScript.5706Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(key_elem_type_name));5707key_elem_type.kind = GDScriptParser::DataType::SCRIPT;5708key_elem_type.builtin_type = Variant::OBJECT;5709key_elem_type.native_type = script->get_instance_base_type();5710key_elem_type.script_type = script;5711} else {5712ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed dictionary.");5713}5714key_elem_type.is_constant = false;57155716StringName value_elem_type_name = p_property.hint_string.get_slicec(';', 1);5717GDScriptParser::DataType value_elem_type;5718value_elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;57195720Variant::Type value_elem_builtin_type = GDScriptParser::get_builtin_type(value_elem_type_name);5721if (value_elem_builtin_type < Variant::VARIANT_MAX) {5722// Builtin type.5723value_elem_type.kind = GDScriptParser::DataType::BUILTIN;5724value_elem_type.builtin_type = value_elem_builtin_type;5725} else if (class_exists(value_elem_type_name)) {5726value_elem_type.kind = GDScriptParser::DataType::NATIVE;5727value_elem_type.builtin_type = Variant::OBJECT;5728value_elem_type.native_type = value_elem_type_name;5729} else if (ScriptServer::is_global_class(value_elem_type_name)) {5730// Just load this as it shouldn't be a GDScript.5731Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(value_elem_type_name));5732value_elem_type.kind = GDScriptParser::DataType::SCRIPT;5733value_elem_type.builtin_type = Variant::OBJECT;5734value_elem_type.native_type = script->get_instance_base_type();5735value_elem_type.script_type = script;5736} else {5737ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed dictionary.");5738}5739value_elem_type.is_constant = false;57405741result.set_container_element_type(0, key_elem_type);5742result.set_container_element_type(1, value_elem_type);5743} else if (p_property.type == Variant::INT) {5744// Check if it's enum.5745if ((p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) && p_property.class_name != StringName()) {5746if (CoreConstants::is_global_enum(p_property.class_name)) {5747result = make_global_enum_type(p_property.class_name, StringName(), false);5748result.is_constant = false;5749} else {5750Vector<String> names = String(p_property.class_name).split(ENUM_SEPARATOR);5751if (names.size() == 2) {5752result = make_enum_type(names[1], names[0], false);5753result.is_constant = false;5754}5755}5756}5757// PROPERTY_USAGE_CLASS_IS_BITFIELD: BitField[T] isn't supported (yet?), use plain int.5758}5759}5760return result;5761}57625763bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, BitField<MethodFlags> &r_method_flags, StringName *r_native_class) {5764r_method_flags = METHOD_FLAGS_DEFAULT;5765r_default_arg_count = 0;5766if (r_native_class) {5767*r_native_class = StringName();5768}5769StringName function_name = p_function;57705771bool was_enum = false;5772if (p_base_type.kind == GDScriptParser::DataType::ENUM) {5773was_enum = true;5774if (p_base_type.is_meta_type) {5775// Enum type can be treated as a dictionary value.5776p_base_type.kind = GDScriptParser::DataType::BUILTIN;5777p_base_type.is_meta_type = false;5778} else {5779push_error("Cannot call function on enum value.", p_source);5780return false;5781}5782}57835784if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {5785// Construct a base type to get methods.5786Callable::CallError err;5787Variant dummy;5788Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);5789if (err.error != Callable::CallError::CALL_OK) {5790ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");5791}5792List<MethodInfo> methods;5793dummy.get_method_list(&methods);57945795for (const MethodInfo &E : methods) {5796if (E.name == p_function) {5797function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5798// Cannot use non-const methods on enums.5799if (!r_method_flags.has_flag(METHOD_FLAG_STATIC) && was_enum && !(E.flags & METHOD_FLAG_CONST)) {5800push_error(vformat(R"*(Cannot call non-const Dictionary function "%s()" on enum "%s".)*", p_function, p_base_type.enum_type), p_source);5801}5802return true;5803}5804}58055806return false;5807}58085809StringName base_native = p_base_type.native_type;5810if (base_native != StringName()) {5811// Empty native class might happen in some Script implementations.5812// Just ignore it.5813if (!class_exists(base_native)) {5814push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source);5815return false;5816} else if (p_is_constructor && ClassDB::is_abstract(base_native)) {5817if (p_base_type.kind == GDScriptParser::DataType::CLASS) {5818push_error(vformat(R"(Class "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.class_type->fqcn.get_file(), base_native), p_source);5819} else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) {5820push_error(vformat(R"(Script "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.script_path.get_file(), base_native), p_source);5821} else {5822push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source);5823}5824return false;5825}5826}58275828if (p_is_constructor) {5829function_name = GDScriptLanguage::get_singleton()->strings._init;5830r_method_flags.set_flag(METHOD_FLAG_STATIC);5831}58325833GDScriptParser::ClassNode *base_class = p_base_type.class_type;5834GDScriptParser::FunctionNode *found_function = nullptr;58355836while (found_function == nullptr && base_class != nullptr) {5837if (base_class->has_member(function_name)) {5838if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {5839// TODO: If this is Callable it can have a better error message.5840push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);5841return false;5842}58435844resolve_class_member(base_class, function_name, p_source);5845found_function = base_class->get_member(function_name).function;5846}58475848resolve_class_inheritance(base_class, p_source);5849base_class = base_class->base_type.class_type;5850}58515852if (found_function != nullptr) {5853if (found_function->is_abstract) {5854r_method_flags.set_flag(METHOD_FLAG_VIRTUAL_REQUIRED);5855}5856if (p_is_constructor || found_function->is_static) {5857r_method_flags.set_flag(METHOD_FLAG_STATIC);5858}5859for (int i = 0; i < found_function->parameters.size(); i++) {5860r_par_types.push_back(found_function->parameters[i]->get_datatype());5861if (found_function->parameters[i]->initializer != nullptr) {5862r_default_arg_count++;5863}5864}5865if (found_function->is_vararg()) {5866r_method_flags.set_flag(METHOD_FLAG_VARARG);5867}5868r_return_type = p_is_constructor ? p_base_type : found_function->get_datatype();5869r_return_type.is_meta_type = false;5870r_return_type.is_coroutine = found_function->is_coroutine;58715872return true;5873}58745875Ref<Script> base_script = p_base_type.script_type;58765877while (base_script.is_valid() && base_script->has_method(function_name)) {5878MethodInfo info = base_script->get_method_info(function_name);58795880if (!(info == MethodInfo())) {5881return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5882}5883base_script = base_script->get_base_script();5884}58855886// If the base is a script, it might be trying to access members of the Script class itself.5887if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {5888MethodInfo info;5889StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());58905891if (ClassDB::get_method_info(script_class, function_name, &info)) {5892return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5893}5894}58955896if (p_is_constructor) {5897// Native types always have a default constructor.5898r_return_type = p_base_type;5899r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5900r_return_type.is_meta_type = false;5901return true;5902}59035904MethodInfo info;5905if (ClassDB::get_method_info(base_native, function_name, &info)) {5906bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5907if (valid && Engine::get_singleton()->has_singleton(base_native)) {5908r_method_flags.set_flag(METHOD_FLAG_STATIC);5909}5910#ifdef DEBUG_ENABLED5911MethodBind *native_method = ClassDB::get_method(base_native, function_name);5912if (native_method && r_native_class) {5913*r_native_class = native_method->get_instance_class();5914}5915#endif // DEBUG_ENABLED5916return valid;5917}59185919return false;5920}59215922bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, BitField<MethodFlags> &r_method_flags) {5923r_return_type = type_from_property(p_info.return_val);5924r_default_arg_count = p_info.default_arguments.size();5925r_method_flags = p_info.flags;59265927for (const PropertyInfo &E : p_info.arguments) {5928r_par_types.push_back(type_from_property(E, true));5929}5930return true;5931}59325933void GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {5934List<GDScriptParser::DataType> arg_types;59355936for (const PropertyInfo &E : p_method.arguments) {5937arg_types.push_back(type_from_property(E, true));5938}59395940validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);5941}59425943void GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {5944if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {5945push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", p_call->function_name, p_par_types.size() - p_default_args_count, p_call->arguments.size()), p_call);5946}5947if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {5948push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", p_call->function_name, p_par_types.size(), p_call->arguments.size()), p_call->arguments[p_par_types.size()]);5949}59505951List<GDScriptParser::DataType>::ConstIterator par_itr = p_par_types.begin();5952for (int i = 0; i < p_call->arguments.size(); ++par_itr, ++i) {5953if (i >= p_par_types.size()) {5954// Already on vararg place.5955break;5956}5957GDScriptParser::DataType par_type = *par_itr;59585959if (par_type.is_hard_type() && p_call->arguments[i]->is_constant) {5960update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");5961}5962GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();59635964if (arg_type.is_variant() || !arg_type.is_hard_type()) {5965#ifdef DEBUG_ENABLED5966// Argument can be anything, so this is unsafe (unless the parameter is a hard variant).5967if (!(par_type.is_hard_type() && par_type.is_variant())) {5968mark_node_unsafe(p_call->arguments[i]);5969parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "function", p_call->function_name, par_type.to_string(), arg_type.to_string_strict());5970}5971#endif // DEBUG_ENABLED5972} else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {5973if (!is_type_compatible(arg_type, par_type)) {5974push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*",5975p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),5976p_call->arguments[i]);5977#ifdef DEBUG_ENABLED5978} else {5979// Supertypes are acceptable for dynamic compliance, but it's unsafe.5980mark_node_unsafe(p_call);5981parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "function", p_call->function_name, par_type.to_string(), arg_type.to_string_strict());5982#endif // DEBUG_ENABLED5983}5984#ifdef DEBUG_ENABLED5985} else if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {5986parser->push_warning(p_call->arguments[i], GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);5987#endif // DEBUG_ENABLED5988}5989}5990}59915992#ifdef DEBUG_ENABLED5993void GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_identifier, const String &p_context, const bool p_in_local_scope) {5994const StringName &name = p_identifier->name;59955996{5997List<MethodInfo> gdscript_funcs;5998GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);59996000for (MethodInfo &info : gdscript_funcs) {6001if (info.name == name) {6002parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");6003return;6004}6005}6006if (Variant::has_utility_function(name)) {6007parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");6008return;6009} else if (class_exists(name)) {6010parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "native class");6011return;6012} else if (ScriptServer::is_global_class(name)) {6013String class_path = ScriptServer::get_global_class_path(name).get_file();6014parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, vformat(R"(global class defined in "%s")", class_path));6015return;6016} else if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {6017parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in type");6018return;6019}6020}60216022const GDScriptParser::DataType current_class_type = parser->current_class->get_datatype();6023if (p_in_local_scope) {6024GDScriptParser::ClassNode *base_class = current_class_type.class_type;60256026if (base_class != nullptr) {6027if (base_class->has_member(name)) {6028parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_identifier->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));6029return;6030}6031base_class = base_class->base_type.class_type;6032}60336034while (base_class != nullptr) {6035if (base_class->has_member(name)) {6036String base_class_name = base_class->get_global_name();6037if (base_class_name.is_empty()) {6038base_class_name = base_class->fqcn;6039}60406041parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()), base_class_name);6042return;6043}6044base_class = base_class->base_type.class_type;6045}6046}60476048StringName native_base_class = current_class_type.native_type;6049while (native_base_class != StringName()) {6050ERR_FAIL_COND_MSG(!class_exists(native_base_class), "Non-existent native base class.");60516052if (ClassDB::has_method(native_base_class, name, true)) {6053parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "method", native_base_class);6054return;6055} else if (ClassDB::has_signal(native_base_class, name, true)) {6056parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "signal", native_base_class);6057return;6058} else if (ClassDB::has_property(native_base_class, name, true)) {6059parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "property", native_base_class);6060return;6061} else if (ClassDB::has_integer_constant(native_base_class, name, true)) {6062parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "constant", native_base_class);6063return;6064} else if (ClassDB::has_enum(native_base_class, name, true)) {6065parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "enum", native_base_class);6066return;6067}6068native_base_class = ClassDB::get_parent_class(native_base_class);6069}6070}6071#endif // DEBUG_ENABLED60726073GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {6074// Unary version.6075GDScriptParser::DataType nil_type;6076nil_type.builtin_type = Variant::NIL;6077nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;6078return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);6079}60806081GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) {6082if (p_operation == Variant::OP_AND || p_operation == Variant::OP_OR) {6083// Those work for any type of argument and always return a boolean.6084// They don't use the Variant operator since they have short-circuit semantics.6085r_valid = true;6086GDScriptParser::DataType result;6087result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;6088result.kind = GDScriptParser::DataType::BUILTIN;6089result.builtin_type = Variant::BOOL;6090return result;6091}60926093Variant::Type a_type = p_a.builtin_type;6094Variant::Type b_type = p_b.builtin_type;60956096if (p_a.kind == GDScriptParser::DataType::ENUM) {6097if (p_a.is_meta_type) {6098a_type = Variant::DICTIONARY;6099} else {6100a_type = Variant::INT;6101}6102}6103if (p_b.kind == GDScriptParser::DataType::ENUM) {6104if (p_b.is_meta_type) {6105b_type = Variant::DICTIONARY;6106} else {6107b_type = Variant::INT;6108}6109}61106111GDScriptParser::DataType result;6112bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();61136114if (p_operation == Variant::OP_ADD && a_type == Variant::ARRAY && b_type == Variant::ARRAY) {6115if (p_a.has_container_element_type(0) && p_b.has_container_element_type(0) && p_a.get_container_element_type(0) == p_b.get_container_element_type(0)) {6116r_valid = true;6117result = p_a;6118result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;6119return result;6120}6121}61226123Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);6124bool validated = op_eval != nullptr;61256126if (validated) {6127r_valid = true;6128result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;6129result.kind = GDScriptParser::DataType::BUILTIN;6130result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);6131} else {6132r_valid = !hard_operation;6133result.kind = GDScriptParser::DataType::VARIANT;6134}61356136return result;6137}61386139bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion, const GDScriptParser::Node *p_source_node) {6140#ifdef DEBUG_ENABLED6141if (p_source_node) {6142if (p_target.kind == GDScriptParser::DataType::ENUM) {6143if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {6144parser->push_warning(p_source_node, GDScriptWarning::INT_AS_ENUM_WITHOUT_CAST);6145}6146}6147}6148#endif // DEBUG_ENABLED6149return check_type_compatibility(p_target, p_source, p_allow_implicit_conversion, p_source_node);6150}61516152// TODO: Add safe/unsafe return variable (for variant cases)6153bool GDScriptAnalyzer::check_type_compatibility(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion, const GDScriptParser::Node *p_source_node) {6154// These return "true" so it doesn't affect users negatively.6155ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");6156ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");61576158if (p_target.kind == GDScriptParser::DataType::VARIANT) {6159// Variant can receive anything.6160return true;6161}61626163if (p_source.kind == GDScriptParser::DataType::VARIANT) {6164// TODO: This is acceptable but unsafe. Make sure unsafe line is set.6165return true;6166}61676168if (p_target.kind == GDScriptParser::DataType::BUILTIN) {6169bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;6170if (!valid && p_allow_implicit_conversion) {6171valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);6172}6173if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {6174// Enum value is also integer.6175valid = true;6176}6177if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {6178// Check the element type.6179if (p_target.has_container_element_type(0) && p_source.has_container_element_type(0)) {6180valid = p_target.get_container_element_type(0) == p_source.get_container_element_type(0);6181}6182}6183if (valid && p_target.builtin_type == Variant::DICTIONARY && p_source.builtin_type == Variant::DICTIONARY) {6184// Check the element types.6185if (p_target.has_container_element_type(0) && p_source.has_container_element_type(0)) {6186valid = p_target.get_container_element_type(0) == p_source.get_container_element_type(0);6187}6188if (valid && p_target.has_container_element_type(1) && p_source.has_container_element_type(1)) {6189valid = p_target.get_container_element_type(1) == p_source.get_container_element_type(1);6190}6191}6192return valid;6193}61946195if (p_target.kind == GDScriptParser::DataType::ENUM) {6196if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {6197return true;6198}6199if (p_source.kind == GDScriptParser::DataType::ENUM) {6200if (p_source.native_type == p_target.native_type) {6201return true;6202}6203}6204return false;6205}62066207// From here on the target type is an object, so we have to test polymorphism.62086209if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {6210// null is acceptable in object.6211return true;6212}62136214StringName src_native;6215Ref<Script> src_script;6216const GDScriptParser::ClassNode *src_class = nullptr;62176218switch (p_source.kind) {6219case GDScriptParser::DataType::NATIVE:6220if (p_target.kind != GDScriptParser::DataType::NATIVE) {6221// Non-native class cannot be supertype of native.6222return false;6223}6224if (p_source.is_meta_type) {6225src_native = GDScriptNativeClass::get_class_static();6226} else {6227src_native = p_source.native_type;6228}6229break;6230case GDScriptParser::DataType::SCRIPT:6231if (p_target.kind == GDScriptParser::DataType::CLASS) {6232// A script type cannot be a subtype of a GDScript class.6233return false;6234}6235if (p_source.script_type.is_null()) {6236return false;6237}6238if (p_source.is_meta_type) {6239src_native = p_source.script_type->get_class_name();6240} else {6241src_script = p_source.script_type;6242src_native = src_script->get_instance_base_type();6243}6244break;6245case GDScriptParser::DataType::CLASS:6246if (p_source.is_meta_type) {6247src_native = GDScript::get_class_static();6248} else {6249src_class = p_source.class_type;6250const GDScriptParser::ClassNode *base = src_class;6251while (base->base_type.kind == GDScriptParser::DataType::CLASS) {6252base = base->base_type.class_type;6253}6254src_native = base->base_type.native_type;6255src_script = base->base_type.script_type;6256}6257break;6258case GDScriptParser::DataType::VARIANT:6259case GDScriptParser::DataType::BUILTIN:6260case GDScriptParser::DataType::ENUM:6261case GDScriptParser::DataType::RESOLVING:6262case GDScriptParser::DataType::UNRESOLVED:6263break; // Already solved before.6264}62656266switch (p_target.kind) {6267case GDScriptParser::DataType::NATIVE: {6268if (p_target.is_meta_type) {6269return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());6270}6271return ClassDB::is_parent_class(src_native, p_target.native_type);6272}6273case GDScriptParser::DataType::SCRIPT:6274if (p_target.is_meta_type) {6275return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());6276}6277while (src_script.is_valid()) {6278if (src_script == p_target.script_type) {6279return true;6280}6281src_script = src_script->get_base_script();6282}6283return false;6284case GDScriptParser::DataType::CLASS:6285if (p_target.is_meta_type) {6286return ClassDB::is_parent_class(src_native, GDScript::get_class_static());6287}6288while (src_class != nullptr) {6289if (src_class == p_target.class_type || src_class->fqcn == p_target.class_type->fqcn) {6290return true;6291}6292src_class = src_class->base_type.class_type;6293}6294return false;6295case GDScriptParser::DataType::VARIANT:6296case GDScriptParser::DataType::BUILTIN:6297case GDScriptParser::DataType::ENUM:6298case GDScriptParser::DataType::RESOLVING:6299case GDScriptParser::DataType::UNRESOLVED:6300break; // Already solved before.6301}63026303return false;6304}63056306void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {6307mark_node_unsafe(p_origin);6308parser->push_error(p_message, p_origin);6309}63106311void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {6312#ifdef DEBUG_ENABLED6313if (p_node == nullptr) {6314return;6315}63166317for (int i = p_node->start_line; i <= p_node->end_line; i++) {6318parser->unsafe_lines.insert(i);6319}6320#endif // DEBUG_ENABLED6321}63226323void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) {6324GDScriptParser::IdentifierNode *identifier = nullptr;6325if (p_node->type == GDScriptParser::Node::IDENTIFIER) {6326identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node);6327} else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) {6328GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node);6329if (subscript->is_attribute) {6330identifier = subscript->attribute;6331}6332}6333if (identifier == nullptr) {6334return;6335}63366337GDScriptParser::Node *source = nullptr;6338switch (identifier->source) {6339case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {6340source = identifier->variable_source;6341} break;6342case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {6343source = identifier->parameter_source;6344} break;6345case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {6346source = identifier->variable_source;6347} break;6348case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {6349source = identifier->bind_source;6350} break;6351default:6352break;6353}6354if (source == nullptr) {6355return;6356}63576358GDScriptParser::DataType datatype;6359datatype.kind = GDScriptParser::DataType::VARIANT;6360source->set_datatype(datatype);6361}63626363void GDScriptAnalyzer::mark_lambda_use_self() {6364GDScriptParser::LambdaNode *lambda = current_lambda;6365while (lambda != nullptr) {6366lambda->use_self = true;6367lambda = lambda->parent_lambda;6368}6369}63706371void GDScriptAnalyzer::resolve_pending_lambda_bodies() {6372if (pending_body_resolution_lambdas.is_empty()) {6373return;6374}63756376GDScriptParser::LambdaNode *previous_lambda = current_lambda;6377bool previous_static_context = static_context;63786379List<GDScriptParser::LambdaNode *> lambdas = pending_body_resolution_lambdas;6380pending_body_resolution_lambdas.clear();63816382for (GDScriptParser::LambdaNode *lambda : lambdas) {6383current_lambda = lambda;6384static_context = lambda->function->is_static;63856386resolve_function_body(lambda->function, true);63876388int captures_amount = lambda->captures.size();6389if (captures_amount > 0) {6390// Create space for lambda parameters.6391// At the beginning to not mess with optional parameters.6392int param_count = lambda->function->parameters.size();6393lambda->function->parameters.resize(param_count + captures_amount);6394for (int i = param_count - 1; i >= 0; i--) {6395lambda->function->parameters.write[i + captures_amount] = lambda->function->parameters[i];6396lambda->function->parameters_indices[lambda->function->parameters[i]->identifier->name] = i + captures_amount;6397}63986399// Add captures as extra parameters at the beginning.6400for (int i = 0; i < lambda->captures.size(); i++) {6401GDScriptParser::IdentifierNode *capture = lambda->captures[i];6402GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();6403capture_param->identifier = capture;6404capture_param->usages = capture->usages;6405capture_param->set_datatype(capture->get_datatype());64066407lambda->function->parameters.write[i] = capture_param;6408lambda->function->parameters_indices[capture->name] = i;6409}6410}6411}64126413current_lambda = previous_lambda;6414static_context = previous_static_context;6415}64166417bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {6418return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);6419}64206421Error GDScriptAnalyzer::resolve_inheritance() {6422return resolve_class_inheritance(parser->head, true);6423}64246425Error GDScriptAnalyzer::resolve_interface() {6426resolve_class_interface(parser->head, true);6427return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6428}64296430Error GDScriptAnalyzer::resolve_body() {6431resolve_class_body(parser->head, true);64326433#ifdef DEBUG_ENABLED6434// Apply here, after all `@warning_ignore`s have been resolved and applied.6435parser->apply_pending_warnings();6436#endif // DEBUG_ENABLED64376438return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6439}64406441Error GDScriptAnalyzer::resolve_dependencies() {6442for (KeyValue<String, Ref<GDScriptParserRef>> &K : parser->depended_parsers) {6443if (K.value.is_null()) {6444return ERR_PARSE_ERROR;6445}6446K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);6447}64486449return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6450}64516452Error GDScriptAnalyzer::analyze() {6453parser->errors.clear();64546455Error err = resolve_inheritance();6456if (err) {6457return err;6458}64596460resolve_interface();6461err = resolve_body();6462if (err) {6463return err;6464}64656466return resolve_dependencies();6467}64686469GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {6470parser = p_parser;6471}647264736474