Path: blob/master/modules/gdscript/gdscript_analyzer.cpp
10277 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 && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {3105parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);3106}3107#endif // DEBUG_ENABLED31083109if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {3110p_binary_op->is_constant = true;3111if (p_binary_op->variant_op < Variant::OP_MAX) {3112bool valid = false;3113Variant::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);3114if (!valid) {3115if (p_binary_op->reduced_value.get_type() == Variant::STRING) {3116push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);3117} else {3118push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",3119Variant::get_operator_name(p_binary_op->variant_op),3120Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),3121Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),3122p_binary_op);3123}3124}3125} else {3126ERR_PRINT("Parser bug: unknown binary operation.");3127}3128p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));31293130return;3131}31323133GDScriptParser::DataType result;31343135if ((p_binary_op->variant_op == Variant::OP_EQUAL || p_binary_op->variant_op == Variant::OP_NOT_EQUAL) &&3136((left_type.kind == GDScriptParser::DataType::BUILTIN && left_type.builtin_type == Variant::NIL) || (right_type.kind == GDScriptParser::DataType::BUILTIN && right_type.builtin_type == Variant::NIL))) {3137// "==" and "!=" operators always return a boolean when comparing to null.3138result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3139result.kind = GDScriptParser::DataType::BUILTIN;3140result.builtin_type = Variant::BOOL;3141} else if (p_binary_op->variant_op == Variant::OP_MODULE && left_type.builtin_type == Variant::STRING) {3142// The modulo operator (%) on string acts as formatting and will always return a string.3143result.type_source = left_type.type_source;3144result.kind = GDScriptParser::DataType::BUILTIN;3145result.builtin_type = Variant::STRING;3146} else if (left_type.is_variant() || right_type.is_variant()) {3147// Cannot infer type because one operand can be anything.3148result.kind = GDScriptParser::DataType::VARIANT;3149mark_node_unsafe(p_binary_op);3150} else if (p_binary_op->variant_op < Variant::OP_MAX) {3151bool valid = false;3152result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);3153if (!valid) {3154push_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);3155} else if (!result.is_hard_type()) {3156mark_node_unsafe(p_binary_op);3157}3158} else {3159ERR_PRINT("Parser bug: unknown binary operation.");3160}31613162p_binary_op->set_datatype(result);3163}31643165#ifdef SUGGEST_GODOT4_RENAMES3166const char *get_rename_from_map(const char *map[][2], String key) {3167for (int index = 0; map[index][0]; index++) {3168if (map[index][0] == key) {3169return map[index][1];3170}3171}3172return nullptr;3173}31743175// Checks if an identifier/function name has been renamed in Godot 4, uses ProjectConverter3To4 for rename map.3176// Returns the new name if found, nullptr otherwise.3177const char *check_for_renamed_identifier(String identifier, GDScriptParser::Node::Type type) {3178switch (type) {3179case GDScriptParser::Node::IDENTIFIER: {3180// Check properties3181const char *result = get_rename_from_map(RenamesMap3To4::gdscript_properties_renames, identifier);3182if (result) {3183return result;3184}3185// Check enum values3186result = get_rename_from_map(RenamesMap3To4::enum_renames, identifier);3187if (result) {3188return result;3189}3190// Check color constants3191result = get_rename_from_map(RenamesMap3To4::color_renames, identifier);3192if (result) {3193return result;3194}3195// Check type names3196result = get_rename_from_map(RenamesMap3To4::class_renames, identifier);3197if (result) {3198return result;3199}3200return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);3201}3202case GDScriptParser::Node::CALL: {3203const char *result = get_rename_from_map(RenamesMap3To4::gdscript_function_renames, identifier);3204if (result) {3205return result;3206}3207// Built-in Types are mistaken for function calls when the built-in type is not found.3208// Check built-in types if function rename not found3209return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);3210}3211// Signal references don't get parsed through the GDScriptAnalyzer. No support for signal rename hints.3212default:3213// No rename found, return null3214return nullptr;3215}3216}3217#endif // SUGGEST_GODOT4_RENAMES32183219void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {3220bool all_is_constant = true;3221HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.3222HashMap<int, GDScriptParser::DictionaryNode *> dictionaries; // Same, but for dictionaries.3223for (int i = 0; i < p_call->arguments.size(); i++) {3224reduce_expression(p_call->arguments[i]);3225if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {3226arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);3227} else if (p_call->arguments[i]->type == GDScriptParser::Node::DICTIONARY) {3228dictionaries[i] = static_cast<GDScriptParser::DictionaryNode *>(p_call->arguments[i]);3229}3230all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;3231}32323233GDScriptParser::Node::Type callee_type = p_call->get_callee_type();3234GDScriptParser::DataType call_type;32353236if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {3237// Call to name directly.3238StringName function_name = p_call->function_name;32393240if (function_name == SNAME("Object")) {3241push_error(R"*(Invalid constructor "Object()", use "Object.new()" instead.)*", p_call);3242p_call->set_datatype(call_type);3243return;3244}32453246Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);3247if (builtin_type < Variant::VARIANT_MAX) {3248// Is a builtin constructor.3249call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3250call_type.kind = GDScriptParser::DataType::BUILTIN;3251call_type.builtin_type = builtin_type;32523253bool safe_to_fold = true;3254switch (builtin_type) {3255// Those are stored by reference so not suited for compile-time construction.3256// Because in this case they would be the same reference in all constructed values.3257case Variant::OBJECT:3258case Variant::DICTIONARY:3259case Variant::ARRAY:3260case Variant::PACKED_BYTE_ARRAY:3261case Variant::PACKED_INT32_ARRAY:3262case Variant::PACKED_INT64_ARRAY:3263case Variant::PACKED_FLOAT32_ARRAY:3264case Variant::PACKED_FLOAT64_ARRAY:3265case Variant::PACKED_STRING_ARRAY:3266case Variant::PACKED_VECTOR2_ARRAY:3267case Variant::PACKED_VECTOR3_ARRAY:3268case Variant::PACKED_COLOR_ARRAY:3269case Variant::PACKED_VECTOR4_ARRAY:3270safe_to_fold = false;3271break;3272default:3273break;3274}32753276if (all_is_constant && safe_to_fold) {3277// Construct here.3278Vector<const Variant *> args;3279for (int i = 0; i < p_call->arguments.size(); i++) {3280args.push_back(&(p_call->arguments[i]->reduced_value));3281}32823283Callable::CallError err;3284Variant value;3285Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);32863287switch (err.error) {3288case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3289push_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,3290Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),3291p_call->arguments[err.argument]);3292break;3293case Callable::CallError::CALL_ERROR_INVALID_METHOD: {3294String signature = Variant::get_type_name(builtin_type) + "(";3295for (int i = 0; i < p_call->arguments.size(); i++) {3296if (i > 0) {3297signature += ", ";3298}3299signature += p_call->arguments[i]->get_datatype().to_string();3300}3301signature += ")";3302push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);3303} break;3304case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3305push_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);3306break;3307case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3308push_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);3309break;3310case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3311case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3312break; // Can't happen in a builtin constructor.3313case Callable::CallError::CALL_OK:3314p_call->is_constant = true;3315p_call->reduced_value = value;3316break;3317}3318} else {3319// If there's one argument, try to use copy constructor (those aren't explicitly defined).3320if (p_call->arguments.size() == 1) {3321GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();3322if (arg_type.is_hard_type() && !arg_type.is_variant()) {3323if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {3324// Okay.3325p_call->set_datatype(call_type);3326return;3327}3328} else {3329#ifdef DEBUG_ENABLED3330mark_node_unsafe(p_call);3331// Constructors support overloads.3332Vector<String> types;3333for (int i = 0; i < Variant::VARIANT_MAX; i++) {3334if (i != builtin_type && Variant::can_convert_strict((Variant::Type)i, builtin_type)) {3335types.push_back(Variant::get_type_name((Variant::Type)i));3336}3337}3338String expected_types = function_name;3339if (types.size() == 1) {3340expected_types += "\" or \"" + types[0];3341} else if (types.size() >= 2) {3342for (int i = 0; i < types.size() - 1; i++) {3343expected_types += "\", \"" + types[i];3344}3345expected_types += "\", or \"" + types[types.size() - 1];3346}3347parser->push_warning(p_call->arguments[0], GDScriptWarning::UNSAFE_CALL_ARGUMENT, "1", "constructor", function_name, expected_types, "Variant");3348#endif // DEBUG_ENABLED3349p_call->set_datatype(call_type);3350return;3351}3352}33533354List<MethodInfo> constructors;3355Variant::get_constructor_list(builtin_type, &constructors);3356bool match = false;33573358for (const MethodInfo &info : constructors) {3359if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {3360continue;3361}3362if (p_call->arguments.size() > info.arguments.size()) {3363continue;3364}33653366bool types_match = true;33673368for (int64_t i = 0; i < p_call->arguments.size(); ++i) {3369GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);3370GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();3371if (!is_type_compatible(par_type, arg_type, true)) {3372types_match = false;3373break;3374#ifdef DEBUG_ENABLED3375} else {3376if (par_type.builtin_type == Variant::INT && arg_type.builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {3377parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, function_name);3378}3379#endif // DEBUG_ENABLED3380}3381}33823383if (types_match) {3384for (int64_t i = 0; i < p_call->arguments.size(); ++i) {3385GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);3386if (p_call->arguments[i]->is_constant) {3387update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");3388}3389#ifdef DEBUG_ENABLED3390if (!(par_type.is_variant() && par_type.is_hard_type())) {3391GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();3392if (arg_type.is_variant() || !arg_type.is_hard_type()) {3393mark_node_unsafe(p_call);3394parser->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());3395}3396}3397#endif // DEBUG_ENABLED3398}3399match = true;3400call_type = type_from_property(info.return_val);3401break;3402}3403}34043405if (!match) {3406String signature = Variant::get_type_name(builtin_type) + "(";3407for (int i = 0; i < p_call->arguments.size(); i++) {3408if (i > 0) {3409signature += ", ";3410}3411signature += p_call->arguments[i]->get_datatype().to_string();3412}3413signature += ")";3414push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);3415}3416}34173418#ifdef DEBUG_ENABLED3419// Consider `Signal(self, "my_signal")` as an implicit use of the signal.3420if (builtin_type == Variant::SIGNAL && p_call->arguments.size() >= 2) {3421const GDScriptParser::ExpressionNode *object_arg = p_call->arguments[0];3422if (object_arg && object_arg->type == GDScriptParser::Node::SELF) {3423const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[1];3424if (signal_arg && signal_arg->is_constant) {3425const StringName &signal_name = signal_arg->reduced_value;3426if (parser->current_class->has_member(signal_name)) {3427const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);3428if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {3429member.signal->usages++;3430}3431}3432}3433}3434}3435#endif // DEBUG_ENABLED34363437p_call->set_datatype(call_type);3438return;3439} else if (GDScriptUtilityFunctions::function_exists(function_name)) {3440MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);34413442if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {3443push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);3444}34453446if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {3447// Can call on compilation.3448Vector<const Variant *> args;3449for (int i = 0; i < p_call->arguments.size(); i++) {3450args.push_back(&(p_call->arguments[i]->reduced_value));3451}34523453Variant value;3454Callable::CallError err;3455GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);34563457switch (err.error) {3458case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3459if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {3460push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);3461} else {3462// Do not use `type_from_property()` for expected type, since utility functions use their own checks.3463push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,3464Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),3465p_call->arguments[err.argument]);3466}3467break;3468case Callable::CallError::CALL_ERROR_INVALID_METHOD:3469push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);3470break;3471case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3472push_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);3473break;3474case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3475push_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);3476break;3477case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3478case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3479break; // Can't happen in a builtin constructor.3480case Callable::CallError::CALL_OK:3481p_call->is_constant = true;3482p_call->reduced_value = value;3483break;3484}3485} else {3486validate_call_arg(function_info, p_call);3487}3488p_call->set_datatype(type_from_property(function_info.return_val));3489return;3490} else if (Variant::has_utility_function(function_name)) {3491MethodInfo function_info = info_from_utility_func(function_name);34923493if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {3494push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);3495}34963497if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {3498// Can call on compilation.3499Vector<const Variant *> args;3500for (int i = 0; i < p_call->arguments.size(); i++) {3501args.push_back(&(p_call->arguments[i]->reduced_value));3502}35033504Variant value;3505Callable::CallError err;3506Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);35073508switch (err.error) {3509case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:3510if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {3511push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);3512} else {3513// Do not use `type_from_property()` for expected type, since utility functions use their own checks.3514push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,3515Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),3516p_call->arguments[err.argument]);3517}3518break;3519case Callable::CallError::CALL_ERROR_INVALID_METHOD:3520push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);3521break;3522case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:3523push_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);3524break;3525case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:3526push_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);3527break;3528case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:3529case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:3530break; // Can't happen in a builtin constructor.3531case Callable::CallError::CALL_OK:3532p_call->is_constant = true;3533p_call->reduced_value = value;3534break;3535}3536} else {3537validate_call_arg(function_info, p_call);3538}3539p_call->set_datatype(type_from_property(function_info.return_val));3540return;3541}3542}35433544GDScriptParser::DataType base_type;3545call_type.kind = GDScriptParser::DataType::VARIANT;3546bool is_self = false;35473548if (p_call->is_super) {3549base_type = parser->current_class->base_type;3550base_type.is_meta_type = false;3551is_self = true;35523553if (p_call->callee == nullptr && current_lambda != nullptr) {3554push_error("Cannot use `super()` inside a lambda.", p_call);3555}3556} else if (callee_type == GDScriptParser::Node::IDENTIFIER) {3557base_type = parser->current_class->get_datatype();3558base_type.is_meta_type = false;3559is_self = true;3560} else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {3561GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);3562if (subscript->base == nullptr) {3563// Invalid syntax, error already set on parser.3564p_call->set_datatype(call_type);3565mark_node_unsafe(p_call);3566return;3567}3568if (!subscript->is_attribute) {3569// Invalid call. Error already sent in parser.3570// TODO: Could check if Callable here.3571p_call->set_datatype(call_type);3572mark_node_unsafe(p_call);3573return;3574}3575if (subscript->attribute == nullptr) {3576// Invalid call. Error already sent in parser.3577p_call->set_datatype(call_type);3578mark_node_unsafe(p_call);3579return;3580}35813582GDScriptParser::IdentifierNode *base_id = nullptr;3583if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {3584base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);3585}3586if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {3587base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));3588} else {3589reduce_expression(subscript->base);3590base_type = subscript->base->get_datatype();3591is_self = subscript->base->type == GDScriptParser::Node::SELF;3592}3593} else {3594// Invalid call. Error already sent in parser.3595// TODO: Could check if Callable here too.3596p_call->set_datatype(call_type);3597mark_node_unsafe(p_call);3598return;3599}36003601int default_arg_count = 0;3602BitField<MethodFlags> method_flags = {};3603GDScriptParser::DataType return_type;3604List<GDScriptParser::DataType> par_types;36053606bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");36073608if (is_constructor) {3609if (Engine::get_singleton()->has_singleton(base_type.native_type)) {3610push_error(vformat(R"(Cannot construct native class "%s" because it is an engine singleton.)", base_type.native_type), p_call);3611p_call->set_datatype(call_type);3612return;3613}3614if ((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())) {3615push_error(vformat(R"(Cannot construct abstract class "%s".)", base_type.to_string()), p_call);3616}3617}36183619if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, method_flags)) {3620p_call->is_static = method_flags.has_flag(METHOD_FLAG_STATIC);3621// 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.3622// 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.3623if (p_call->is_super) {3624if (method_flags.has_flag(METHOD_FLAG_VIRTUAL)) {3625push_error(vformat(R"*(Cannot call the parent class' virtual function "%s()" because it hasn't been defined.)*", p_call->function_name), p_call);3626} else if (method_flags.has_flag(METHOD_FLAG_VIRTUAL_REQUIRED)) {3627push_error(vformat(R"*(Cannot call the parent class' abstract function "%s()" because it hasn't been defined.)*", p_call->function_name), p_call);3628}3629}36303631// If the function requires typed arrays we must make literals be typed.3632for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {3633int index = E.key;3634if (index < par_types.size() && par_types.get(index).is_hard_type() && par_types.get(index).has_container_element_type(0)) {3635update_array_literal_element_type(E.value, par_types.get(index).get_container_element_type(0));3636}3637}3638for (const KeyValue<int, GDScriptParser::DictionaryNode *> &E : dictionaries) {3639int index = E.key;3640if (index < par_types.size() && par_types.get(index).is_hard_type() && par_types.get(index).has_container_element_types()) {3641GDScriptParser::DataType key = par_types.get(index).get_container_element_type_or_variant(0);3642GDScriptParser::DataType value = par_types.get(index).get_container_element_type_or_variant(1);3643update_dictionary_literal_element_type(E.value, key, value);3644}3645}3646validate_call_arg(par_types, default_arg_count, method_flags.has_flag(METHOD_FLAG_VARARG), p_call);36473648if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {3649// Enum type is treated as a dictionary value for function calls.3650base_type.is_meta_type = false;3651}36523653if (is_self && static_context && !p_call->is_static) {3654// Get the parent function above any lambda.3655GDScriptParser::FunctionNode *parent_function = parser->current_function;3656while (parent_function && parent_function->source_lambda) {3657parent_function = parent_function->source_lambda->parent_function;3658}36593660if (parent_function) {3661push_error(vformat(R"*(Cannot call non-static function "%s()" from the static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);3662} else {3663push_error(vformat(R"*(Cannot call non-static function "%s()" from a static variable initializer.)*", p_call->function_name), p_call);3664}3665} else if (!is_self && base_type.is_meta_type && !p_call->is_static) {3666base_type.is_meta_type = false; // For `to_string()`.3667push_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);3668} else if (is_self && !p_call->is_static) {3669mark_lambda_use_self();3670}36713672if (!p_is_root && !p_is_await && return_type.is_hard_type() && return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {3673push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", p_call->function_name), p_call);3674}36753676#ifdef DEBUG_ENABLED3677// FIXME: No warning for built-in constructors and utilities due to early return.3678if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL &&3679!(p_call->is_super && p_call->function_name == GDScriptLanguage::get_singleton()->strings._init)) {3680parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);3681}36823683if (method_flags.has_flag(METHOD_FLAG_STATIC) && !is_constructor && !base_type.is_meta_type && !is_self) {3684String caller_type = base_type.to_string();36853686parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, caller_type);3687}36883689// Consider `emit_signal()`, `connect()`, and `disconnect()` as implicit uses of the signal.3690if (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()) {3691const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[0];3692if (signal_arg && signal_arg->is_constant) {3693const StringName &signal_name = signal_arg->reduced_value;3694if (parser->current_class->has_member(signal_name)) {3695const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);3696if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {3697member.signal->usages++;3698}3699}3700}3701}3702#endif // DEBUG_ENABLED37033704call_type = return_type;3705} else {3706bool found = false;37073708// Enums do not have functions other than the built-in dictionary ones.3709if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {3710if (base_type.builtin_type == Variant::DICTIONARY) {3711push_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);3712} else {3713push_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);3714}3715} else if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { // Check if the name exists as something else.3716GDScriptParser::IdentifierNode *callee_id;3717if (callee_type == GDScriptParser::Node::IDENTIFIER) {3718callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);3719} else {3720// Can only be attribute.3721callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;3722}3723if (callee_id) {3724reduce_identifier_from_base(callee_id, &base_type);3725GDScriptParser::DataType callee_datatype = callee_id->get_datatype();3726if (callee_datatype.is_set() && !callee_datatype.is_variant()) {3727found = true;3728if (callee_datatype.builtin_type == Variant::CALLABLE) {3729push_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);3730} else {3731push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);3732}3733#ifdef DEBUG_ENABLED3734} else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {3735parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());3736mark_node_unsafe(p_call);3737#endif // DEBUG_ENABLED3738}3739}3740}3741if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {3742String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();3743#ifdef SUGGEST_GODOT4_RENAMES3744String rename_hint;3745if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {3746const char *renamed_function_name = check_for_renamed_identifier(p_call->function_name, p_call->type);3747if (renamed_function_name) {3748rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", String(renamed_function_name) + "()");3749}3750}3751push_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);3752#else3753push_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);3754#endif // SUGGEST_GODOT4_RENAMES3755} else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.is_meta_type)) {3756push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.to_string()), p_call);3757}3758}37593760if (call_type.is_coroutine && !p_is_await && !p_is_root) {3761push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call);3762}37633764p_call->set_datatype(call_type);3765}37663767void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {3768reduce_expression(p_cast->operand);37693770GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type));37713772if (!cast_type.is_set()) {3773mark_node_unsafe(p_cast);3774return;3775}37763777p_cast->set_datatype(cast_type);3778if (p_cast->operand->is_constant) {3779update_const_expression_builtin_type(p_cast->operand, cast_type, "cast", true);3780if (cast_type.is_variant() || p_cast->operand->get_datatype() == cast_type) {3781p_cast->is_constant = true;3782p_cast->reduced_value = p_cast->operand->reduced_value;3783}3784}37853786if (p_cast->operand->type == GDScriptParser::Node::ARRAY && cast_type.has_container_element_type(0)) {3787update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_cast->operand), cast_type.get_container_element_type(0));3788}37893790if (p_cast->operand->type == GDScriptParser::Node::DICTIONARY && cast_type.has_container_element_types()) {3791update_dictionary_literal_element_type(static_cast<GDScriptParser::DictionaryNode *>(p_cast->operand),3792cast_type.get_container_element_type_or_variant(0), cast_type.get_container_element_type_or_variant(1));3793}37943795if (!cast_type.is_variant()) {3796GDScriptParser::DataType op_type = p_cast->operand->get_datatype();3797if (op_type.is_variant() || !op_type.is_hard_type()) {3798mark_node_unsafe(p_cast);3799#ifdef DEBUG_ENABLED3800parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());3801#endif // DEBUG_ENABLED3802} else {3803bool valid = false;3804if (op_type.builtin_type == Variant::INT && cast_type.kind == GDScriptParser::DataType::ENUM) {3805mark_node_unsafe(p_cast);3806valid = true;3807} else if (op_type.kind == GDScriptParser::DataType::ENUM && cast_type.builtin_type == Variant::INT) {3808valid = true;3809} else if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {3810valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);3811} else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {3812valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);3813}38143815if (!valid) {3816push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);3817}3818}3819}3820}38213822void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {3823HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, StringLikeVariantComparator> elements;38243825for (int i = 0; i < p_dictionary->elements.size(); i++) {3826const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];3827if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {3828reduce_expression(element.key);3829}3830reduce_expression(element.value);38313832if (element.key->is_constant) {3833if (elements.has(element.key->reduced_value)) {3834push_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);3835} else {3836elements[element.key->reduced_value] = element.value;3837}3838}3839}38403841// It's dictionary in any case.3842GDScriptParser::DataType dict_type;3843dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3844dict_type.kind = GDScriptParser::DataType::BUILTIN;3845dict_type.builtin_type = Variant::DICTIONARY;3846dict_type.is_constant = true;38473848p_dictionary->set_datatype(dict_type);3849}38503851void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {3852GDScriptParser::DataType result;3853result.kind = GDScriptParser::DataType::VARIANT;38543855if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, SNAME("Node"))) {3856push_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);3857p_get_node->set_datatype(result);3858return;3859}38603861if (static_context) {3862push_error(vformat(R"*(Cannot use shorthand "get_node()" notation ("%c") in a static function.)*", p_get_node->use_dollar ? '$' : '%'), p_get_node);3863p_get_node->set_datatype(result);3864return;3865}38663867mark_lambda_use_self();38683869result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;3870result.kind = GDScriptParser::DataType::NATIVE;3871result.builtin_type = Variant::OBJECT;3872result.native_type = SNAME("Node");3873p_get_node->set_datatype(result);3874}38753876GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {3877GDScriptParser::DataType type;38783879String path = ScriptServer::get_global_class_path(p_class_name);3880String ext = path.get_extension();3881if (ext == GDScriptLanguage::get_singleton()->get_extension()) {3882Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(path);3883if (ref.is_null()) {3884push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source);3885type.type_source = GDScriptParser::DataType::UNDETECTED;3886type.kind = GDScriptParser::DataType::VARIANT;3887return type;3888}38893890Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);3891if (err) {3892push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);3893type.type_source = GDScriptParser::DataType::UNDETECTED;3894type.kind = GDScriptParser::DataType::VARIANT;3895return type;3896}38973898return ref->get_parser()->head->get_datatype();3899} else {3900return make_script_meta_type(ResourceLoader::load(path, "Script"));3901}3902}39033904Ref<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) {3905// Delicate piece of code that intentionally doesn't use the GDScript cache or `get_depended_parser_for`.3906// Search dependencies for the parser that owns `p_class` and make a cache entry for it.3907// 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.3908// Since https://github.com/godotengine/godot/pull/94871 there can technically be multiple parsers for the same script in the same parser tree.3909// Even if unlikely, getting the wrong parser could lead to strange undefined behavior without errors.39103911if (p_class == nullptr) {3912return nullptr;3913}39143915if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(p_class)) {3916return E->value;3917}39183919if (parser->has_class(p_class)) {3920return nullptr;3921}39223923if (p_from_class == nullptr) {3924p_from_class = parser->head;3925}39263927Ref<GDScriptParserRef> parser_ref;3928for (const GDScriptParser::ClassNode *look_class = p_from_class; look_class != nullptr; look_class = look_class->base_type.class_type) {3929if (parser->has_class(look_class)) {3930parser_ref = find_cached_external_parser_for_class(p_class, parser);3931if (parser_ref.is_valid()) {3932break;3933}3934}39353936if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(look_class)) {3937parser_ref = find_cached_external_parser_for_class(p_class, E->value);3938if (parser_ref.is_valid()) {3939break;3940}3941}39423943String look_class_script_path = look_class->get_datatype().script_path;3944if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = parser->depended_parsers.find(look_class_script_path)) {3945parser_ref = find_cached_external_parser_for_class(p_class, E->value);3946if (parser_ref.is_valid()) {3947break;3948}3949}3950}39513952if (parser_ref.is_null()) {3953push_error(vformat(R"(Parser bug (please report): Could not find external parser for class "%s". (%s))", p_class->fqcn, p_context), p_source);3954// A null parser will be inserted into the cache, so this error won't spam for the same class.3955// This is ok, the values of external_class_parser_cache are not assumed to be valid references.3956}39573958external_class_parser_cache.insert(p_class, parser_ref);3959return parser_ref;3960}39613962Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, const Ref<GDScriptParserRef> &p_dependant_parser) {3963if (p_dependant_parser.is_null()) {3964return nullptr;3965}39663967if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->get_analyzer()->external_class_parser_cache.find(p_class)) {3968if (E->value.is_valid()) {3969// Silently ensure it's parsed.3970E->value->raise_status(GDScriptParserRef::PARSED);3971if (E->value->get_parser()->has_class(p_class)) {3972return E->value;3973}3974}3975}39763977if (p_dependant_parser->get_parser()->has_class(p_class)) {3978return p_dependant_parser;3979}39803981// Silently ensure it's parsed.3982p_dependant_parser->raise_status(GDScriptParserRef::PARSED);3983return find_cached_external_parser_for_class(p_class, p_dependant_parser->get_parser());3984}39853986Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, GDScriptParser *p_dependant_parser) {3987if (p_dependant_parser == nullptr) {3988return nullptr;3989}39903991String script_path = p_class->get_datatype().script_path;3992if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->depended_parsers.find(script_path)) {3993if (E->value.is_valid()) {3994// Silently ensure it's parsed.3995E->value->raise_status(GDScriptParserRef::PARSED);3996if (E->value->get_parser()->has_class(p_class)) {3997return E->value;3998}3999}4000}40014002return nullptr;4003}40044005Ref<GDScript> GDScriptAnalyzer::get_depended_shallow_script(const String &p_path, Error &r_error) {4006// To keep a local cache of the parser for resolving external nodes later.4007const String path = ResourceUID::ensure_path(p_path);4008parser->get_depended_parser_for(path);4009Ref<GDScript> scr = GDScriptCache::get_shallow_script(path, r_error, parser->script_path);4010return scr;4011}40124013void GDScriptAnalyzer::reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype) {4014ERR_FAIL_NULL(p_identifier);40154016p_identifier->set_datatype(p_identifier_datatype);4017Error err = OK;4018Ref<GDScript> scr = get_depended_shallow_script(p_identifier_datatype.script_path, err);4019if (err) {4020push_error(vformat(R"(Error while getting cache for script "%s".)", p_identifier_datatype.script_path), p_identifier);4021return;4022}4023p_identifier->reduced_value = scr->find_class(p_identifier_datatype.class_type->fqcn);4024p_identifier->is_constant = true;4025}40264027void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {4028if (!p_identifier->get_datatype().has_no_type()) {4029return;4030}40314032GDScriptParser::DataType base;4033if (p_base == nullptr) {4034base = type_from_metatype(parser->current_class->get_datatype());4035} else {4036base = *p_base;4037}40384039StringName name = p_identifier->name;40404041if (base.kind == GDScriptParser::DataType::ENUM) {4042if (base.is_meta_type) {4043if (base.enum_values.has(name)) {4044p_identifier->set_datatype(type_from_metatype(base));4045p_identifier->is_constant = true;4046p_identifier->reduced_value = base.enum_values[name];4047return;4048}40494050// Enum does not have this value, return.4051return;4052} else {4053push_error(R"(Cannot get property from enum value.)", p_identifier);4054return;4055}4056}40574058if (base.kind == GDScriptParser::DataType::BUILTIN) {4059if (base.is_meta_type) {4060bool valid = false;40614062if (Variant::has_constant(base.builtin_type, name)) {4063valid = true;40644065const Variant constant_value = Variant::get_constant_value(base.builtin_type, name);40664067p_identifier->is_constant = true;4068p_identifier->reduced_value = constant_value;4069p_identifier->set_datatype(type_from_variant(constant_value, p_identifier));4070}40714072if (!valid) {4073const StringName enum_name = Variant::get_enum_for_enumeration(base.builtin_type, name);4074if (enum_name != StringName()) {4075valid = true;40764077p_identifier->is_constant = true;4078p_identifier->reduced_value = Variant::get_enum_value(base.builtin_type, enum_name, name);4079p_identifier->set_datatype(make_builtin_enum_type(enum_name, base.builtin_type, false));4080}4081}40824083if (!valid && Variant::has_enum(base.builtin_type, name)) {4084valid = true;40854086p_identifier->set_datatype(make_builtin_enum_type(name, base.builtin_type, true));4087}40884089if (!valid && base.is_hard_type()) {4090#ifdef SUGGEST_GODOT4_RENAMES4091String rename_hint;4092if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4093const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4094if (renamed_identifier_name) {4095rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4096}4097}4098push_error(vformat(R"(Cannot find member "%s" in base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);4099#else4100push_error(vformat(R"(Cannot find member "%s" in base "%s".)", name, base.to_string()), p_identifier);4101#endif // SUGGEST_GODOT4_RENAMES4102}4103} else {4104switch (base.builtin_type) {4105case Variant::NIL: {4106if (base.is_hard_type()) {4107push_error(vformat(R"(Cannot get property "%s" on a null object.)", name), p_identifier);4108}4109return;4110}4111case Variant::DICTIONARY: {4112GDScriptParser::DataType dummy;4113dummy.kind = GDScriptParser::DataType::VARIANT;4114p_identifier->set_datatype(dummy);4115return;4116}4117default: {4118Callable::CallError temp;4119Variant dummy;4120Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);4121List<PropertyInfo> properties;4122dummy.get_property_list(&properties);4123for (const PropertyInfo &prop : properties) {4124if (prop.name == name) {4125p_identifier->set_datatype(type_from_property(prop));4126return;4127}4128}4129if (Variant::has_builtin_method(base.builtin_type, name)) {4130p_identifier->set_datatype(make_callable_type(Variant::get_builtin_method_info(base.builtin_type, name)));4131return;4132}4133if (base.is_hard_type()) {4134#ifdef SUGGEST_GODOT4_RENAMES4135String rename_hint;4136if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4137const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4138if (renamed_identifier_name) {4139rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4140}4141}4142push_error(vformat(R"(Cannot find member "%s" in base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);4143#else4144push_error(vformat(R"(Cannot find member "%s" in base "%s".)", name, base.to_string()), p_identifier);4145#endif // SUGGEST_GODOT4_RENAMES4146}4147}4148}4149}4150return;4151}41524153GDScriptParser::ClassNode *base_class = base.class_type;4154List<GDScriptParser::ClassNode *> script_classes;4155bool is_base = true;41564157if (base_class != nullptr) {4158get_class_node_current_scope_classes(base_class, &script_classes, p_identifier);4159}41604161bool is_constructor = base.is_meta_type && p_identifier->name == SNAME("new");41624163for (GDScriptParser::ClassNode *script_class : script_classes) {4164if (p_base == nullptr && script_class->identifier && script_class->identifier->name == name) {4165reduce_identifier_from_base_set_class(p_identifier, script_class->get_datatype());4166if (script_class->outer != nullptr) {4167p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;4168}4169return;4170}41714172if (is_constructor) {4173name = "_init";4174}41754176if (script_class->has_member(name)) {4177resolve_class_member(script_class, name, p_identifier);41784179GDScriptParser::ClassNode::Member member = script_class->get_member(name);4180switch (member.type) {4181case GDScriptParser::ClassNode::Member::CONSTANT: {4182p_identifier->set_datatype(member.get_datatype());4183p_identifier->is_constant = true;4184p_identifier->reduced_value = member.constant->initializer->reduced_value;4185p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4186p_identifier->constant_source = member.constant;4187return;4188}41894190case GDScriptParser::ClassNode::Member::ENUM_VALUE: {4191p_identifier->set_datatype(member.get_datatype());4192p_identifier->is_constant = true;4193p_identifier->reduced_value = member.enum_value.value;4194p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4195return;4196}41974198case GDScriptParser::ClassNode::Member::ENUM: {4199p_identifier->set_datatype(member.get_datatype());4200p_identifier->is_constant = true;4201p_identifier->reduced_value = member.m_enum->dictionary;4202p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4203return;4204}42054206case GDScriptParser::ClassNode::Member::VARIABLE: {4207if (is_base && (!base.is_meta_type || member.variable->is_static)) {4208p_identifier->set_datatype(member.get_datatype());4209p_identifier->source = member.variable->is_static ? GDScriptParser::IdentifierNode::STATIC_VARIABLE : GDScriptParser::IdentifierNode::MEMBER_VARIABLE;4210p_identifier->variable_source = member.variable;4211member.variable->usages += 1;4212return;4213}4214} break;42154216case GDScriptParser::ClassNode::Member::SIGNAL: {4217if (is_base && !base.is_meta_type) {4218p_identifier->set_datatype(member.get_datatype());4219p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;4220p_identifier->signal_source = member.signal;4221member.signal->usages += 1;4222return;4223}4224} break;42254226case GDScriptParser::ClassNode::Member::FUNCTION: {4227if (is_base && (!base.is_meta_type || member.function->is_static || is_constructor)) {4228p_identifier->set_datatype(make_callable_type(member.function->info));4229p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;4230p_identifier->function_source = member.function;4231p_identifier->function_source_is_static = member.function->is_static;4232return;4233}4234} break;42354236case GDScriptParser::ClassNode::Member::CLASS: {4237reduce_identifier_from_base_set_class(p_identifier, member.get_datatype());4238p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;4239return;4240}42414242default: {4243// Do nothing4244}4245}4246}42474248if (is_base) {4249is_base = script_class->base_type.class_type != nullptr;4250if (!is_base && p_base != nullptr) {4251break;4252}4253}4254}42554256// Check non-GDScript scripts.4257Ref<Script> script_type = base.script_type;42584259if (base_class == nullptr && script_type.is_valid()) {4260List<PropertyInfo> property_list;4261script_type->get_script_property_list(&property_list);42624263for (const PropertyInfo &property_info : property_list) {4264if (property_info.name != p_identifier->name) {4265continue;4266}42674268const GDScriptParser::DataType property_type = GDScriptAnalyzer::type_from_property(property_info, false, false);42694270p_identifier->set_datatype(property_type);4271p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;4272return;4273}42744275MethodInfo method_info = script_type->get_method_info(p_identifier->name);42764277if (method_info.name == p_identifier->name) {4278p_identifier->set_datatype(make_callable_type(method_info));4279p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;4280p_identifier->function_source_is_static = method_info.flags & METHOD_FLAG_STATIC;4281return;4282}42834284List<MethodInfo> signal_list;4285script_type->get_script_signal_list(&signal_list);42864287for (const MethodInfo &signal_info : signal_list) {4288if (signal_info.name != p_identifier->name) {4289continue;4290}42914292const GDScriptParser::DataType signal_type = make_signal_type(signal_info);42934294p_identifier->set_datatype(signal_type);4295p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;4296return;4297}42984299HashMap<StringName, Variant> constant_map;4300script_type->get_constants(&constant_map);43014302if (constant_map.has(p_identifier->name)) {4303Variant constant = constant_map.get(p_identifier->name);43044305p_identifier->set_datatype(make_builtin_meta_type(constant.get_type()));4306p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4307return;4308}4309}43104311// Check native members. No need for native class recursion because Node exposes all Object's properties.4312const StringName &native = base.native_type;43134314if (class_exists(native)) {4315if (is_constructor) {4316name = "_init";4317}43184319MethodInfo method_info;4320if (ClassDB::has_property(native, name)) {4321StringName getter_name = ClassDB::get_property_getter(native, name);4322MethodBind *getter = ClassDB::get_method(native, getter_name);4323if (getter != nullptr) {4324bool has_setter = ClassDB::get_property_setter(native, name) != StringName();4325p_identifier->set_datatype(type_from_property(getter->get_return_info(), false, !has_setter));4326p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4327}4328return;4329}4330if (ClassDB::get_method_info(native, name, &method_info)) {4331// Method is callable.4332p_identifier->set_datatype(make_callable_type(method_info));4333p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4334return;4335}4336if (ClassDB::get_signal(native, name, &method_info)) {4337// Signal is a type too.4338p_identifier->set_datatype(make_signal_type(method_info));4339p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4340return;4341}4342if (ClassDB::has_enum(native, name)) {4343p_identifier->set_datatype(make_native_enum_type(name, native));4344p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;4345return;4346}4347bool valid = false;43484349int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);4350if (valid) {4351p_identifier->is_constant = true;4352p_identifier->reduced_value = int_constant;4353p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;43544355// Check whether this constant, which exists, belongs to an enum4356StringName enum_name = ClassDB::get_integer_constant_enum(native, name);4357if (enum_name != StringName()) {4358p_identifier->set_datatype(make_native_enum_type(enum_name, native, false));4359} else {4360p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));4361}4362}4363}4364}43654366void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {4367// TODO: This is an opportunity to further infer types.43684369// Check if we are inside an enum. This allows enum values to access other elements of the same enum.4370if (current_enum) {4371for (int i = 0; i < current_enum->values.size(); i++) {4372const GDScriptParser::EnumNode::Value &element = current_enum->values[i];4373if (element.identifier->name == p_identifier->name) {4374StringName enum_name = current_enum->identifier ? current_enum->identifier->name : UNNAMED_ENUM;4375GDScriptParser::DataType type = make_class_enum_type(enum_name, parser->current_class, parser->script_path, false);4376if (element.parent_enum->identifier) {4377type.enum_type = element.parent_enum->identifier->name;4378}4379p_identifier->set_datatype(type);43804381if (element.resolved) {4382p_identifier->is_constant = true;4383p_identifier->reduced_value = element.value;4384} else {4385push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);4386}4387return; // Found anyway.4388}4389}4390}43914392bool found_source = false;4393// Check if identifier is local.4394// If that's the case, the declaration already was solved before.4395switch (p_identifier->source) {4396case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:4397p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());4398found_source = true;4399break;4400case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:4401case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:4402p_identifier->set_datatype(p_identifier->constant_source->get_datatype());4403p_identifier->is_constant = true;4404// TODO: Constant should have a value on the node itself.4405p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;4406found_source = true;4407break;4408case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:4409p_identifier->signal_source->usages++;4410[[fallthrough]];4411case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:4412mark_lambda_use_self();4413break;4414case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:4415mark_lambda_use_self();4416p_identifier->variable_source->usages++;4417[[fallthrough]];4418case GDScriptParser::IdentifierNode::STATIC_VARIABLE:4419case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:4420p_identifier->set_datatype(p_identifier->variable_source->get_datatype());4421found_source = true;4422#ifdef DEBUG_ENABLED4423if (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)) {4424parser->push_warning(p_identifier, GDScriptWarning::UNASSIGNED_VARIABLE, p_identifier->name);4425}4426#endif // DEBUG_ENABLED4427break;4428case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:4429p_identifier->set_datatype(p_identifier->bind_source->get_datatype());4430found_source = true;4431break;4432case GDScriptParser::IdentifierNode::LOCAL_BIND: {4433GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();4434result.is_constant = true;4435p_identifier->set_datatype(result);4436found_source = true;4437} break;4438case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:4439case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:4440case GDScriptParser::IdentifierNode::MEMBER_CLASS:4441case GDScriptParser::IdentifierNode::NATIVE_CLASS:4442break;4443}44444445#ifdef DEBUG_ENABLED4446if (!found_source && p_identifier->suite != nullptr && p_identifier->suite->has_local(p_identifier->name)) {4447parser->push_warning(p_identifier, GDScriptWarning::CONFUSABLE_LOCAL_USAGE, p_identifier->name);4448}4449#endif // DEBUG_ENABLED44504451// Not a local, so check members.44524453if (!found_source) {4454reduce_identifier_from_base(p_identifier);4455if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {4456// Found.4457found_source = true;4458}4459}44604461if (found_source) {4462const bool source_is_instance_variable = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE;4463const bool source_is_instance_function = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_FUNCTION && !p_identifier->function_source_is_static;4464const bool source_is_signal = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_SIGNAL;44654466if (static_context && (source_is_instance_variable || source_is_instance_function || source_is_signal)) {4467// Get the parent function above any lambda.4468GDScriptParser::FunctionNode *parent_function = parser->current_function;4469while (parent_function && parent_function->source_lambda) {4470parent_function = parent_function->source_lambda->parent_function;4471}44724473String source_type;4474if (source_is_instance_variable) {4475source_type = "non-static variable";4476} else if (source_is_instance_function) {4477source_type = "non-static function";4478} else { // source_is_signal4479source_type = "signal";4480}44814482if (parent_function) {4483push_error(vformat(R"*(Cannot access %s "%s" from the static function "%s()".)*", source_type, p_identifier->name, parent_function->identifier->name), p_identifier);4484} else {4485push_error(vformat(R"*(Cannot access %s "%s" from a static variable initializer.)*", source_type, p_identifier->name), p_identifier);4486}4487}44884489if (current_lambda != nullptr) {4490// If the identifier is a member variable (including the native class properties), member function, or a signal,4491// we consider the lambda to be using `self`, so we keep a reference to the current instance.4492if (source_is_instance_variable || source_is_instance_function || source_is_signal) {4493mark_lambda_use_self();4494return; // No need to capture.4495}44964497switch (p_identifier->source) {4498case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:4499case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:4500case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:4501case GDScriptParser::IdentifierNode::LOCAL_BIND:4502break; // Need to capture.4503case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE: // A global.4504case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:4505case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:4506case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:4507case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:4508case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:4509case GDScriptParser::IdentifierNode::MEMBER_CLASS:4510case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:4511case GDScriptParser::IdentifierNode::STATIC_VARIABLE:4512case GDScriptParser::IdentifierNode::NATIVE_CLASS:4513return; // No need to capture.4514}45154516GDScriptParser::FunctionNode *function_test = current_lambda->function;4517// Make sure we aren't capturing variable in the same lambda.4518// This also add captures for nested lambdas.4519while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {4520function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();4521function_test->source_lambda->captures.push_back(p_identifier);4522function_test = function_test->source_lambda->parent_function;4523}4524}45254526return;4527}45284529StringName name = p_identifier->name;4530p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;45314532// Not a local or a member, so check globals.45334534Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);4535if (builtin_type < Variant::VARIANT_MAX) {4536if (can_be_builtin) {4537p_identifier->set_datatype(make_builtin_meta_type(builtin_type));4538return;4539} else {4540push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);4541}4542}45434544if (class_exists(name)) {4545p_identifier->source = GDScriptParser::IdentifierNode::NATIVE_CLASS;4546p_identifier->set_datatype(make_native_meta_type(name));4547return;4548}45494550if (ScriptServer::is_global_class(name)) {4551p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));4552return;4553}45544555// Try singletons.4556// Do this before globals because this might be a singleton loading another one before it's compiled.4557if (ProjectSettings::get_singleton()->has_autoload(name)) {4558const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);4559if (autoload.is_singleton) {4560// Singleton exists, so it's at least a Node.4561GDScriptParser::DataType result;4562result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;4563result.kind = GDScriptParser::DataType::NATIVE;4564result.builtin_type = Variant::OBJECT;4565result.native_type = SNAME("Node");4566if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {4567Ref<GDScriptParserRef> single_parser = parser->get_depended_parser_for(autoload.path);4568if (single_parser.is_valid()) {4569Error err = single_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);4570if (err == OK) {4571result = type_from_metatype(single_parser->get_parser()->head->get_datatype());4572}4573}4574} else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {4575if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {4576Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);4577Node *node = Object::cast_to<Node>(constant);4578if (node != nullptr) {4579Ref<GDScript> scr = node->get_script();4580if (scr.is_valid()) {4581Ref<GDScriptParserRef> single_parser = parser->get_depended_parser_for(scr->get_script_path());4582if (single_parser.is_valid()) {4583Error err = single_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);4584if (err == OK) {4585result = type_from_metatype(single_parser->get_parser()->head->get_datatype());4586}4587}4588}4589}4590}4591}4592result.is_constant = true;4593p_identifier->set_datatype(result);4594return;4595}4596}45974598if (CoreConstants::is_global_constant(name)) {4599int index = CoreConstants::get_global_constant_index(name);4600StringName enum_name = CoreConstants::get_global_constant_enum(index);4601int64_t value = CoreConstants::get_global_constant_value(index);4602if (enum_name != StringName()) {4603p_identifier->set_datatype(make_global_enum_type(enum_name, StringName(), false));4604} else {4605p_identifier->set_datatype(type_from_variant(value, p_identifier));4606}4607p_identifier->is_constant = true;4608p_identifier->reduced_value = value;4609return;4610}46114612if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {4613Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);4614p_identifier->set_datatype(type_from_variant(constant, p_identifier));4615p_identifier->is_constant = true;4616p_identifier->reduced_value = constant;4617return;4618}46194620if (CoreConstants::is_global_enum(name)) {4621p_identifier->set_datatype(make_global_enum_type(name, StringName(), true));4622if (!can_be_builtin) {4623push_error(vformat(R"(Global enum "%s" cannot be used on its own.)", name), p_identifier);4624}4625return;4626}46274628if (Variant::has_utility_function(name) || GDScriptUtilityFunctions::function_exists(name)) {4629p_identifier->is_constant = true;4630p_identifier->reduced_value = Callable(memnew(GDScriptUtilityCallable(name)));4631MethodInfo method_info;4632if (GDScriptUtilityFunctions::function_exists(name)) {4633method_info = GDScriptUtilityFunctions::get_function_info(name);4634} else {4635method_info = Variant::get_utility_function_info(name);4636}4637p_identifier->set_datatype(make_callable_type(method_info));4638return;4639}46404641// Allow "Variant" here since it might be used for nested enums.4642if (can_be_builtin && name == SNAME("Variant")) {4643GDScriptParser::DataType variant;4644variant.kind = GDScriptParser::DataType::VARIANT;4645variant.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;4646variant.is_meta_type = true;4647variant.is_pseudo_type = true;4648p_identifier->set_datatype(variant);4649return;4650}46514652// Not found.4653#ifdef SUGGEST_GODOT4_RENAMES4654String rename_hint;4655if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/renamed_in_godot_4_hint")) {4656const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);4657if (renamed_identifier_name) {4658rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);4659}4660}4661push_error(vformat(R"(Identifier "%s" not declared in the current scope.%s)", name, rename_hint), p_identifier);4662#else4663push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);4664#endif // SUGGEST_GODOT4_RENAMES4665GDScriptParser::DataType dummy;4666dummy.kind = GDScriptParser::DataType::VARIANT;4667p_identifier->set_datatype(dummy); // Just so type is set to something.4668}46694670void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {4671// Lambda is always a Callable.4672GDScriptParser::DataType lambda_type;4673lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;4674lambda_type.kind = GDScriptParser::DataType::BUILTIN;4675lambda_type.builtin_type = Variant::CALLABLE;4676p_lambda->set_datatype(lambda_type);46774678if (p_lambda->function == nullptr) {4679return;4680}46814682GDScriptParser::LambdaNode *previous_lambda = current_lambda;4683current_lambda = p_lambda;4684resolve_function_signature(p_lambda->function, p_lambda, true);4685current_lambda = previous_lambda;46864687pending_body_resolution_lambdas.push_back(p_lambda);4688}46894690void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {4691p_literal->reduced_value = p_literal->value;4692p_literal->is_constant = true;46934694p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));4695}46964697void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {4698if (!p_preload->path) {4699return;4700}47014702reduce_expression(p_preload->path);47034704if (!p_preload->path->is_constant) {4705push_error("Preloaded path must be a constant string.", p_preload->path);4706return;4707}47084709if (p_preload->path->reduced_value.get_type() != Variant::STRING) {4710push_error("Preloaded path must be a constant string.", p_preload->path);4711} else {4712p_preload->resolved_path = p_preload->path->reduced_value;4713// TODO: Save this as script dependency.4714if (p_preload->resolved_path.is_relative_path()) {4715p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);4716}4717p_preload->resolved_path = p_preload->resolved_path.simplify_path();4718if (!ResourceLoader::exists(p_preload->resolved_path)) {4719Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);47204721if (file_check->file_exists(p_preload->resolved_path)) {4722push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);4723} else {4724push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);4725}4726} else {4727// TODO: Don't load if validating: use completion cache.47284729// Must load GDScript separately to permit cyclic references4730// as ResourceLoader::load() detects and rejects those.4731const String &res_type = ResourceLoader::get_resource_type(p_preload->resolved_path);4732if (res_type == "GDScript") {4733Error err = OK;4734Ref<GDScript> res = get_depended_shallow_script(p_preload->resolved_path, err);4735p_preload->resource = res;4736if (err != OK) {4737push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);4738}4739} else {4740Error err = OK;4741p_preload->resource = ResourceLoader::load(p_preload->resolved_path, res_type, ResourceFormatLoader::CACHE_MODE_REUSE, &err);4742if (err == ERR_BUSY) {4743p_preload->resource = ResourceLoader::ensure_resource_ref_override_for_outer_load(p_preload->resolved_path, res_type);4744}4745if (p_preload->resource.is_null()) {4746push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);4747}4748}4749}4750}47514752p_preload->is_constant = true;4753p_preload->reduced_value = p_preload->resource;4754p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));47554756// TODO: Not sure if this is necessary anymore.4757// 'type_from_variant()' should call 'resolve_class_inheritance()' which would call 'ensure_cached_external_parser_for_class()'4758// Better safe than sorry.4759ensure_cached_external_parser_for_class(p_preload->get_datatype().class_type, nullptr, "Trying to resolve preload", p_preload);4760}47614762void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {4763p_self->is_constant = false;4764p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));4765mark_lambda_use_self();4766}47674768void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript, bool p_can_be_pseudo_type) {4769if (p_subscript->base == nullptr) {4770return;4771}4772if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {4773reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);4774} else if (p_subscript->base->type == GDScriptParser::Node::SUBSCRIPT) {4775reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_subscript->base), true);4776} else {4777reduce_expression(p_subscript->base);4778}47794780GDScriptParser::DataType result_type;47814782if (p_subscript->is_attribute) {4783if (p_subscript->attribute == nullptr) {4784return;4785}47864787GDScriptParser::DataType base_type = p_subscript->base->get_datatype();4788bool valid = false;47894790// If the base is a metatype, use the analyzer instead.4791if (p_subscript->base->is_constant && !base_type.is_meta_type) {4792// GH-92534. If the base is a GDScript, use the analyzer instead.4793bool base_is_gdscript = false;4794if (p_subscript->base->reduced_value.get_type() == Variant::OBJECT) {4795Ref<GDScript> gdscript = Object::cast_to<GDScript>(p_subscript->base->reduced_value.get_validated_object());4796if (gdscript.is_valid()) {4797base_is_gdscript = true;4798// Makes a metatype from a constant GDScript, since `base_type` is not a metatype.4799GDScriptParser::DataType base_type_meta = type_from_variant(gdscript, p_subscript);4800// First try to reduce the attribute from the metatype.4801reduce_identifier_from_base(p_subscript->attribute, &base_type_meta);4802GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4803if (attr_type.is_set()) {4804valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;4805result_type = attr_type;4806p_subscript->is_constant = p_subscript->attribute->is_constant;4807p_subscript->reduced_value = p_subscript->attribute->reduced_value;4808}4809if (!valid) {4810// If unsuccessful, reset and return to the normal route.4811p_subscript->attribute->set_datatype(GDScriptParser::DataType());4812}4813}4814}4815if (!base_is_gdscript) {4816// Just try to get it.4817Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);4818if (valid) {4819p_subscript->is_constant = true;4820p_subscript->reduced_value = value;4821result_type = type_from_variant(value, p_subscript);4822}4823}4824}48254826if (valid) {4827// Do nothing.4828} else if (base_type.is_variant() || !base_type.is_hard_type()) {4829valid = !base_type.is_pseudo_type || p_can_be_pseudo_type;4830result_type.kind = GDScriptParser::DataType::VARIANT;4831if (base_type.is_variant() && base_type.is_hard_type() && base_type.is_meta_type && base_type.is_pseudo_type) {4832// Special case: it may be a global enum with pseudo base (e.g. Variant.Type).4833String enum_name;4834if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {4835enum_name = String(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base)->name) + ENUM_SEPARATOR + String(p_subscript->attribute->name);4836}4837if (CoreConstants::is_global_enum(enum_name)) {4838result_type = make_global_enum_type(enum_name, StringName());4839} else {4840valid = false;4841mark_node_unsafe(p_subscript);4842}4843} else {4844mark_node_unsafe(p_subscript);4845}4846} else {4847reduce_identifier_from_base(p_subscript->attribute, &base_type);4848GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4849if (attr_type.is_set()) {4850if (base_type.builtin_type == Variant::DICTIONARY && base_type.has_container_element_types()) {4851Variant::Type key_type = base_type.get_container_element_type_or_variant(0).builtin_type;4852valid = key_type == Variant::NIL || key_type == Variant::STRING || key_type == Variant::STRING_NAME;4853if (base_type.has_container_element_type(1)) {4854result_type = base_type.get_container_element_type(1);4855result_type.type_source = base_type.type_source;4856} else {4857result_type.builtin_type = Variant::NIL;4858result_type.kind = GDScriptParser::DataType::VARIANT;4859result_type.type_source = GDScriptParser::DataType::UNDETECTED;4860}4861} else {4862valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;4863result_type = attr_type;4864p_subscript->is_constant = p_subscript->attribute->is_constant;4865p_subscript->reduced_value = p_subscript->attribute->reduced_value;4866}4867} else if (!base_type.is_meta_type || !base_type.is_constant) {4868valid = base_type.kind != GDScriptParser::DataType::BUILTIN;4869#ifdef DEBUG_ENABLED4870if (valid) {4871parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());4872}4873#endif // DEBUG_ENABLED4874result_type.kind = GDScriptParser::DataType::VARIANT;4875mark_node_unsafe(p_subscript);4876}4877}48784879if (!valid) {4880GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();4881if (!p_can_be_pseudo_type && (attr_type.is_pseudo_type || result_type.is_pseudo_type)) {4882push_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);4883} else {4884push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);4885}4886result_type.kind = GDScriptParser::DataType::VARIANT;4887}4888} else {4889if (p_subscript->index == nullptr) {4890return;4891}4892reduce_expression(p_subscript->index);48934894if (p_subscript->base->is_constant && p_subscript->index->is_constant) {4895// Just try to get it.4896bool valid = false;4897// TODO: Check if `p_subscript->base->reduced_value` is GDScript.4898Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);4899if (!valid) {4900push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);4901result_type.kind = GDScriptParser::DataType::VARIANT;4902} else {4903p_subscript->is_constant = true;4904p_subscript->reduced_value = value;4905result_type = type_from_variant(value, p_subscript);4906}4907} else {4908GDScriptParser::DataType base_type = p_subscript->base->get_datatype();4909GDScriptParser::DataType index_type = p_subscript->index->get_datatype();49104911if (base_type.is_variant()) {4912result_type.kind = GDScriptParser::DataType::VARIANT;4913mark_node_unsafe(p_subscript);4914} else {4915if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {4916// Check if indexing is valid.4917bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;4918if (!error) {4919switch (base_type.builtin_type) {4920// Expect int or real as index.4921case Variant::PACKED_BYTE_ARRAY:4922case Variant::PACKED_FLOAT32_ARRAY:4923case Variant::PACKED_FLOAT64_ARRAY:4924case Variant::PACKED_INT32_ARRAY:4925case Variant::PACKED_INT64_ARRAY:4926case Variant::PACKED_STRING_ARRAY:4927case Variant::PACKED_VECTOR2_ARRAY:4928case Variant::PACKED_VECTOR3_ARRAY:4929case Variant::PACKED_COLOR_ARRAY:4930case Variant::PACKED_VECTOR4_ARRAY:4931case Variant::ARRAY:4932case Variant::STRING:4933error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;4934break;4935// Expect String only.4936case Variant::RECT2:4937case Variant::RECT2I:4938case Variant::PLANE:4939case Variant::QUATERNION:4940case Variant::AABB:4941case Variant::OBJECT:4942error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4943break;4944// Expect String or number.4945case Variant::BASIS:4946case Variant::VECTOR2:4947case Variant::VECTOR2I:4948case Variant::VECTOR3:4949case Variant::VECTOR3I:4950case Variant::VECTOR4:4951case Variant::VECTOR4I:4952case Variant::TRANSFORM2D:4953case Variant::TRANSFORM3D:4954case Variant::PROJECTION:4955error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&4956index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4957break;4958// Expect String or int.4959case Variant::COLOR:4960error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;4961break;4962// Don't support indexing, but we will check it later.4963case Variant::RID:4964case Variant::BOOL:4965case Variant::CALLABLE:4966case Variant::FLOAT:4967case Variant::INT:4968case Variant::NIL:4969case Variant::NODE_PATH:4970case Variant::SIGNAL:4971case Variant::STRING_NAME:4972break;4973// Support depends on if the dictionary has a typed key, otherwise anything is valid.4974case Variant::DICTIONARY:4975if (base_type.has_container_element_type(0)) {4976GDScriptParser::DataType key_type = base_type.get_container_element_type(0);4977switch (index_type.builtin_type) {4978// Null value will be treated as an empty object, allow.4979case Variant::NIL:4980error = key_type.builtin_type != Variant::OBJECT;4981break;4982// Objects are parsed for validity in a similar manner to container types.4983case Variant::OBJECT:4984if (key_type.builtin_type == Variant::OBJECT) {4985error = !key_type.can_reference(index_type);4986} else {4987error = key_type.builtin_type != Variant::NIL;4988}4989break;4990// String and StringName interchangeable in this context.4991case Variant::STRING:4992case Variant::STRING_NAME:4993error = key_type.builtin_type != Variant::STRING_NAME && key_type.builtin_type != Variant::STRING;4994break;4995// Ints are valid indices for floats, but not the other way around.4996case Variant::INT:4997error = key_type.builtin_type != Variant::INT && key_type.builtin_type != Variant::FLOAT;4998break;4999// All other cases require the types to match exactly.5000default:5001error = key_type.builtin_type != index_type.builtin_type;5002break;5003}5004}5005break;5006// Here for completeness.5007case Variant::VARIANT_MAX:5008break;5009}50105011if (error) {5012push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);5013}5014}5015} else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {5016if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {5017push_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);5018}5019}50205021// Check resulting type if possible.5022result_type.builtin_type = Variant::NIL;5023result_type.kind = GDScriptParser::DataType::BUILTIN;5024result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;50255026if (base_type.kind != GDScriptParser::DataType::BUILTIN) {5027base_type.builtin_type = Variant::OBJECT;5028}5029switch (base_type.builtin_type) {5030// Can't index at all.5031case Variant::RID:5032case Variant::BOOL:5033case Variant::CALLABLE:5034case Variant::FLOAT:5035case Variant::INT:5036case Variant::NIL:5037case Variant::NODE_PATH:5038case Variant::SIGNAL:5039case Variant::STRING_NAME:5040result_type.kind = GDScriptParser::DataType::VARIANT;5041push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);5042break;5043// Return int.5044case Variant::PACKED_BYTE_ARRAY:5045case Variant::PACKED_INT32_ARRAY:5046case Variant::PACKED_INT64_ARRAY:5047case Variant::VECTOR2I:5048case Variant::VECTOR3I:5049case Variant::VECTOR4I:5050result_type.builtin_type = Variant::INT;5051break;5052// Return float.5053case Variant::PACKED_FLOAT32_ARRAY:5054case Variant::PACKED_FLOAT64_ARRAY:5055case Variant::VECTOR2:5056case Variant::VECTOR3:5057case Variant::VECTOR4:5058case Variant::QUATERNION:5059result_type.builtin_type = Variant::FLOAT;5060break;5061// Return String.5062case Variant::PACKED_STRING_ARRAY:5063case Variant::STRING:5064result_type.builtin_type = Variant::STRING;5065break;5066// Return Vector2.5067case Variant::PACKED_VECTOR2_ARRAY:5068case Variant::TRANSFORM2D:5069case Variant::RECT2:5070result_type.builtin_type = Variant::VECTOR2;5071break;5072// Return Vector2I.5073case Variant::RECT2I:5074result_type.builtin_type = Variant::VECTOR2I;5075break;5076// Return Vector3.5077case Variant::PACKED_VECTOR3_ARRAY:5078case Variant::AABB:5079case Variant::BASIS:5080result_type.builtin_type = Variant::VECTOR3;5081break;5082// Return Color.5083case Variant::PACKED_COLOR_ARRAY:5084result_type.builtin_type = Variant::COLOR;5085break;5086// Return Vector4.5087case Variant::PACKED_VECTOR4_ARRAY:5088result_type.builtin_type = Variant::VECTOR4;5089break;5090// Depends on the index.5091case Variant::TRANSFORM3D:5092case Variant::PROJECTION:5093case Variant::PLANE:5094case Variant::COLOR:5095case Variant::OBJECT:5096result_type.kind = GDScriptParser::DataType::VARIANT;5097result_type.type_source = GDScriptParser::DataType::UNDETECTED;5098break;5099// Can have an element type.5100case Variant::ARRAY:5101if (base_type.has_container_element_type(0)) {5102result_type = base_type.get_container_element_type(0);5103result_type.type_source = base_type.type_source;5104} else {5105result_type.kind = GDScriptParser::DataType::VARIANT;5106result_type.type_source = GDScriptParser::DataType::UNDETECTED;5107}5108break;5109// Can have two element types, but we only care about the value.5110case Variant::DICTIONARY:5111if (base_type.has_container_element_type(1)) {5112result_type = base_type.get_container_element_type(1);5113result_type.type_source = base_type.type_source;5114} else {5115result_type.kind = GDScriptParser::DataType::VARIANT;5116result_type.type_source = GDScriptParser::DataType::UNDETECTED;5117}5118break;5119// Here for completeness.5120case Variant::VARIANT_MAX:5121break;5122}5123}5124}5125}51265127p_subscript->set_datatype(result_type);5128}51295130void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op, bool p_is_root) {5131reduce_expression(p_ternary_op->condition);5132reduce_expression(p_ternary_op->true_expr, p_is_root);5133reduce_expression(p_ternary_op->false_expr, p_is_root);51345135GDScriptParser::DataType result;51365137if (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) {5138p_ternary_op->is_constant = true;5139if (p_ternary_op->condition->reduced_value.booleanize()) {5140p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;5141} else {5142p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;5143}5144}51455146GDScriptParser::DataType true_type;5147if (p_ternary_op->true_expr) {5148true_type = p_ternary_op->true_expr->get_datatype();5149} else {5150true_type.kind = GDScriptParser::DataType::VARIANT;5151}5152GDScriptParser::DataType false_type;5153if (p_ternary_op->false_expr) {5154false_type = p_ternary_op->false_expr->get_datatype();5155} else {5156false_type.kind = GDScriptParser::DataType::VARIANT;5157}51585159if (true_type.is_variant() || false_type.is_variant()) {5160result.kind = GDScriptParser::DataType::VARIANT;5161} else {5162result = true_type;5163if (!is_type_compatible(true_type, false_type)) {5164result = false_type;5165if (!is_type_compatible(false_type, true_type)) {5166result.kind = GDScriptParser::DataType::VARIANT;5167#ifdef DEBUG_ENABLED5168parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);5169#endif // DEBUG_ENABLED5170}5171}5172}5173result.type_source = true_type.is_hard_type() && false_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;51745175p_ternary_op->set_datatype(result);5176}51775178void GDScriptAnalyzer::reduce_type_test(GDScriptParser::TypeTestNode *p_type_test) {5179GDScriptParser::DataType result;5180result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5181result.kind = GDScriptParser::DataType::BUILTIN;5182result.builtin_type = Variant::BOOL;5183p_type_test->set_datatype(result);51845185if (!p_type_test->operand || !p_type_test->test_type) {5186return;5187}51885189reduce_expression(p_type_test->operand);5190GDScriptParser::DataType operand_type = p_type_test->operand->get_datatype();5191GDScriptParser::DataType test_type = type_from_metatype(resolve_datatype(p_type_test->test_type));5192p_type_test->test_datatype = test_type;51935194if (!operand_type.is_set() || !test_type.is_set()) {5195return;5196}51975198if (p_type_test->operand->is_constant) {5199p_type_test->is_constant = true;5200p_type_test->reduced_value = false;52015202if (!is_type_compatible(test_type, operand_type)) {5203push_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);5204} else if (is_type_compatible(test_type, type_from_variant(p_type_test->operand->reduced_value, p_type_test->operand))) {5205p_type_test->reduced_value = test_type.builtin_type != Variant::OBJECT || !p_type_test->operand->reduced_value.is_null();5206}52075208return;5209}52105211if (!is_type_compatible(test_type, operand_type) && !is_type_compatible(operand_type, test_type)) {5212if (operand_type.is_hard_type()) {5213push_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);5214} else {5215downgrade_node_type_source(p_type_test->operand);5216}5217}5218}52195220void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {5221reduce_expression(p_unary_op->operand);52225223GDScriptParser::DataType result;52245225if (p_unary_op->operand == nullptr) {5226result.kind = GDScriptParser::DataType::VARIANT;5227p_unary_op->set_datatype(result);5228return;5229}52305231GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();52325233if (p_unary_op->operand->is_constant) {5234p_unary_op->is_constant = true;5235p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());5236result = type_from_variant(p_unary_op->reduced_value, p_unary_op);5237}52385239if (operand_type.is_variant()) {5240result.kind = GDScriptParser::DataType::VARIANT;5241mark_node_unsafe(p_unary_op);5242} else {5243bool valid = false;5244result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);52455246if (!valid) {5247push_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);5248}5249}52505251p_unary_op->set_datatype(result);5252}52535254Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {5255if (p_expression == nullptr) {5256return Variant();5257}52585259if (p_expression->is_constant) {5260is_reduced = true;5261return p_expression->reduced_value;5262}52635264switch (p_expression->type) {5265case GDScriptParser::Node::ARRAY:5266return make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);5267case GDScriptParser::Node::DICTIONARY:5268return make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);5269case GDScriptParser::Node::SUBSCRIPT:5270return make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);5271case GDScriptParser::Node::CALL:5272return make_call_reduced_value(static_cast<GDScriptParser::CallNode *>(p_expression), is_reduced);5273default:5274break;5275}52765277return Variant();5278}52795280Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {5281Array 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();52825283array.resize(p_array->elements.size());5284for (int i = 0; i < p_array->elements.size(); i++) {5285GDScriptParser::ExpressionNode *element = p_array->elements[i];52865287bool is_element_value_reduced = false;5288Variant element_value = make_expression_reduced_value(element, is_element_value_reduced);5289if (!is_element_value_reduced) {5290return Variant();5291}52925293array[i] = element_value;5294}52955296array.make_read_only();52975298is_reduced = true;5299return array;5300}53015302Variant GDScriptAnalyzer::make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced) {5303Dictionary dictionary = p_dictionary->get_datatype().has_container_element_types()5304? 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))5305: Dictionary();53065307for (int i = 0; i < p_dictionary->elements.size(); i++) {5308const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];53095310bool is_element_key_reduced = false;5311Variant element_key = make_expression_reduced_value(element.key, is_element_key_reduced);5312if (!is_element_key_reduced) {5313return Variant();5314}53155316bool is_element_value_reduced = false;5317Variant element_value = make_expression_reduced_value(element.value, is_element_value_reduced);5318if (!is_element_value_reduced) {5319return Variant();5320}53215322dictionary[element_key] = element_value;5323}53245325dictionary.make_read_only();53265327is_reduced = true;5328return dictionary;5329}53305331Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced) {5332if (p_subscript->base == nullptr || p_subscript->index == nullptr) {5333return Variant();5334}53355336bool is_base_value_reduced = false;5337Variant base_value = make_expression_reduced_value(p_subscript->base, is_base_value_reduced);5338if (!is_base_value_reduced) {5339return Variant();5340}53415342if (p_subscript->is_attribute) {5343bool is_valid = false;5344Variant value = base_value.get_named(p_subscript->attribute->name, is_valid);5345if (is_valid) {5346is_reduced = true;5347return value;5348} else {5349return Variant();5350}5351} else {5352bool is_index_value_reduced = false;5353Variant index_value = make_expression_reduced_value(p_subscript->index, is_index_value_reduced);5354if (!is_index_value_reduced) {5355return Variant();5356}53575358bool is_valid = false;5359Variant value = base_value.get(index_value, &is_valid);5360if (is_valid) {5361is_reduced = true;5362return value;5363} else {5364return Variant();5365}5366}5367}53685369Variant GDScriptAnalyzer::make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced) {5370if (p_call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {5371Variant::Type type = Variant::NIL;5372if (p_call->function_name == SNAME("Array")) {5373type = Variant::ARRAY;5374} else if (p_call->function_name == SNAME("Dictionary")) {5375type = Variant::DICTIONARY;5376} else {5377return Variant();5378}53795380Vector<Variant> args;5381args.resize(p_call->arguments.size());5382const Variant **argptrs = (const Variant **)alloca(sizeof(const Variant *) * args.size());5383for (int i = 0; i < p_call->arguments.size(); i++) {5384bool is_arg_value_reduced = false;5385Variant arg_value = make_expression_reduced_value(p_call->arguments[i], is_arg_value_reduced);5386if (!is_arg_value_reduced) {5387return Variant();5388}5389args.write[i] = arg_value;5390argptrs[i] = &args[i];5391}53925393Variant result;5394Callable::CallError ce;5395Variant::construct(type, result, argptrs, args.size(), ce);5396if (ce.error) {5397push_error(vformat(R"(Failed to construct "%s".)", Variant::get_type_name(type)), p_call);5398return Variant();5399}54005401if (type == Variant::ARRAY) {5402Array array = result;5403array.make_read_only();5404} else if (type == Variant::DICTIONARY) {5405Dictionary dictionary = result;5406dictionary.make_read_only();5407}54085409is_reduced = true;5410return result;5411}54125413return Variant();5414}54155416Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {5417Array array;54185419if (p_element_datatype.builtin_type == Variant::OBJECT) {5420Ref<Script> script_type = p_element_datatype.script_type;5421if (p_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5422Error err = OK;5423Ref<GDScript> scr = get_depended_shallow_script(p_element_datatype.script_path, err);5424if (err) {5425push_error(vformat(R"(Error while getting cache for script "%s".)", p_element_datatype.script_path), p_source_node);5426return array;5427}5428script_type.reference_ptr(scr->find_class(p_element_datatype.class_type->fqcn));5429}54305431array.set_typed(p_element_datatype.builtin_type, p_element_datatype.native_type, script_type);5432} else {5433array.set_typed(p_element_datatype.builtin_type, StringName(), Variant());5434}54355436return array;5437}54385439Dictionary 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) {5440Dictionary dictionary;5441StringName key_name;5442Variant key_script;5443StringName value_name;5444Variant value_script;54455446if (p_key_element_datatype.builtin_type == Variant::OBJECT) {5447Ref<Script> script_type = p_key_element_datatype.script_type;5448if (p_key_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5449Error err = OK;5450Ref<GDScript> scr = get_depended_shallow_script(p_key_element_datatype.script_path, err);5451if (err) {5452push_error(vformat(R"(Error while getting cache for script "%s".)", p_key_element_datatype.script_path), p_source_node);5453return dictionary;5454}5455script_type.reference_ptr(scr->find_class(p_key_element_datatype.class_type->fqcn));5456}54575458key_name = p_key_element_datatype.native_type;5459key_script = script_type;5460}54615462if (p_value_element_datatype.builtin_type == Variant::OBJECT) {5463Ref<Script> script_type = p_value_element_datatype.script_type;5464if (p_value_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {5465Error err = OK;5466Ref<GDScript> scr = get_depended_shallow_script(p_value_element_datatype.script_path, err);5467if (err) {5468push_error(vformat(R"(Error while getting cache for script "%s".)", p_value_element_datatype.script_path), p_source_node);5469return dictionary;5470}5471script_type.reference_ptr(scr->find_class(p_value_element_datatype.class_type->fqcn));5472}54735474value_name = p_value_element_datatype.native_type;5475value_script = script_type;5476}54775478dictionary.set_typed(p_key_element_datatype.builtin_type, key_name, key_script, p_value_element_datatype.builtin_type, value_name, value_script);5479return dictionary;5480}54815482Variant GDScriptAnalyzer::make_variable_default_value(GDScriptParser::VariableNode *p_variable) {5483Variant result = Variant();54845485if (p_variable->initializer) {5486bool is_initializer_value_reduced = false;5487Variant initializer_value = make_expression_reduced_value(p_variable->initializer, is_initializer_value_reduced);5488if (is_initializer_value_reduced) {5489result = initializer_value;5490}5491} else {5492GDScriptParser::DataType datatype = p_variable->get_datatype();5493if (datatype.is_hard_type()) {5494if (datatype.kind == GDScriptParser::DataType::BUILTIN && datatype.builtin_type != Variant::OBJECT) {5495if (datatype.builtin_type == Variant::ARRAY && datatype.has_container_element_type(0)) {5496result = make_array_from_element_datatype(datatype.get_container_element_type(0));5497} else if (datatype.builtin_type == Variant::DICTIONARY && datatype.has_container_element_types()) {5498GDScriptParser::DataType key = datatype.get_container_element_type_or_variant(0);5499GDScriptParser::DataType value = datatype.get_container_element_type_or_variant(1);5500result = make_dictionary_from_element_datatype(key, value);5501} else {5502VariantInternal::initialize(&result, datatype.builtin_type);5503}5504} else if (datatype.kind == GDScriptParser::DataType::ENUM) {5505result = 0;5506}5507}5508}55095510return result;5511}55125513GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {5514GDScriptParser::DataType result;5515result.is_constant = true;5516result.kind = GDScriptParser::DataType::BUILTIN;5517result.builtin_type = p_value.get_type();5518result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.55195520if (p_value.get_type() == Variant::ARRAY) {5521const Array &array = p_value;5522if (array.get_typed_script()) {5523result.set_container_element_type(0, type_from_metatype(make_script_meta_type(array.get_typed_script())));5524} else if (array.get_typed_class_name()) {5525result.set_container_element_type(0, type_from_metatype(make_native_meta_type(array.get_typed_class_name())));5526} else if (array.get_typed_builtin() != Variant::NIL) {5527result.set_container_element_type(0, type_from_metatype(make_builtin_meta_type((Variant::Type)array.get_typed_builtin())));5528}5529} else if (p_value.get_type() == Variant::DICTIONARY) {5530const Dictionary &dict = p_value;5531if (dict.get_typed_key_script()) {5532result.set_container_element_type(0, type_from_metatype(make_script_meta_type(dict.get_typed_key_script())));5533} else if (dict.get_typed_key_class_name()) {5534result.set_container_element_type(0, type_from_metatype(make_native_meta_type(dict.get_typed_key_class_name())));5535} else if (dict.get_typed_key_builtin() != Variant::NIL) {5536result.set_container_element_type(0, type_from_metatype(make_builtin_meta_type((Variant::Type)dict.get_typed_key_builtin())));5537}5538if (dict.get_typed_value_script()) {5539result.set_container_element_type(1, type_from_metatype(make_script_meta_type(dict.get_typed_value_script())));5540} else if (dict.get_typed_value_class_name()) {5541result.set_container_element_type(1, type_from_metatype(make_native_meta_type(dict.get_typed_value_class_name())));5542} else if (dict.get_typed_value_builtin() != Variant::NIL) {5543result.set_container_element_type(1, type_from_metatype(make_builtin_meta_type((Variant::Type)dict.get_typed_value_builtin())));5544}5545} else if (p_value.get_type() == Variant::OBJECT) {5546// Object is treated as a native type, not a builtin type.5547result.kind = GDScriptParser::DataType::NATIVE;55485549Object *obj = p_value;5550if (!obj) {5551return GDScriptParser::DataType();5552}5553result.native_type = obj->get_class_name();55545555Ref<Script> scr = p_value; // Check if value is a script itself.5556if (scr.is_valid()) {5557result.is_meta_type = true;5558} else {5559result.is_meta_type = false;5560scr = obj->get_script();5561}5562if (scr.is_valid()) {5563Ref<GDScript> gds = scr;5564if (gds.is_valid()) {5565// This might be an inner class, so we want to get the parser for the root.5566// But still get the inner class from that tree.5567String script_path = gds->get_script_path();5568Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(script_path);5569if (ref.is_null()) {5570push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);5571GDScriptParser::DataType error_type;5572error_type.kind = GDScriptParser::DataType::VARIANT;5573return error_type;5574}5575Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);5576GDScriptParser::ClassNode *found = nullptr;5577if (err == OK) {5578found = ref->get_parser()->find_class(gds->fully_qualified_name);5579if (found != nullptr) {5580err = resolve_class_inheritance(found, p_source);5581}5582}5583if (err || found == nullptr) {5584push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);5585GDScriptParser::DataType error_type;5586error_type.kind = GDScriptParser::DataType::VARIANT;5587return error_type;5588}55895590result.kind = GDScriptParser::DataType::CLASS;5591result.native_type = found->get_datatype().native_type;5592result.class_type = found;5593result.script_path = ref->get_parser()->script_path;5594} else {5595result.kind = GDScriptParser::DataType::SCRIPT;5596result.native_type = scr->get_instance_base_type();5597result.script_path = scr->get_path();5598}5599result.script_type = scr;5600} else {5601result.kind = GDScriptParser::DataType::NATIVE;5602if (result.native_type == GDScriptNativeClass::get_class_static()) {5603result.is_meta_type = true;5604}5605}5606}56075608return result;5609}56105611GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) {5612GDScriptParser::DataType result = p_meta_type;5613result.is_meta_type = false;5614result.is_pseudo_type = false;5615if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {5616result.builtin_type = Variant::INT;5617} else {5618result.is_constant = false;5619}5620return result;5621}56225623GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg, bool p_is_readonly) const {5624GDScriptParser::DataType result;5625result.is_read_only = p_is_readonly;5626result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5627if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {5628// Variant5629result.kind = GDScriptParser::DataType::VARIANT;5630return result;5631}5632result.builtin_type = p_property.type;5633if (p_property.type == Variant::OBJECT) {5634if (ScriptServer::is_global_class(p_property.class_name)) {5635result.kind = GDScriptParser::DataType::SCRIPT;5636result.script_path = ScriptServer::get_global_class_path(p_property.class_name);5637result.native_type = ScriptServer::get_global_class_native_base(p_property.class_name);56385639Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_property.class_name));5640if (scr.is_valid()) {5641result.script_type = scr;5642}5643} else {5644result.kind = GDScriptParser::DataType::NATIVE;5645result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;5646}5647} else {5648result.kind = GDScriptParser::DataType::BUILTIN;5649result.builtin_type = p_property.type;5650if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {5651// Check element type.5652StringName elem_type_name = p_property.hint_string;5653GDScriptParser::DataType elem_type;5654elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;56555656Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);5657if (elem_builtin_type < Variant::VARIANT_MAX) {5658// Builtin type.5659elem_type.kind = GDScriptParser::DataType::BUILTIN;5660elem_type.builtin_type = elem_builtin_type;5661} else if (class_exists(elem_type_name)) {5662elem_type.kind = GDScriptParser::DataType::NATIVE;5663elem_type.builtin_type = Variant::OBJECT;5664elem_type.native_type = elem_type_name;5665} else if (ScriptServer::is_global_class(elem_type_name)) {5666// Just load this as it shouldn't be a GDScript.5667Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));5668elem_type.kind = GDScriptParser::DataType::SCRIPT;5669elem_type.builtin_type = Variant::OBJECT;5670elem_type.native_type = script->get_instance_base_type();5671elem_type.script_type = script;5672} else {5673ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");5674}5675elem_type.is_constant = false;5676result.set_container_element_type(0, elem_type);5677} else if (p_property.type == Variant::DICTIONARY && p_property.hint == PROPERTY_HINT_DICTIONARY_TYPE) {5678// Check element type.5679StringName key_elem_type_name = p_property.hint_string.get_slicec(';', 0);5680GDScriptParser::DataType key_elem_type;5681key_elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;56825683Variant::Type key_elem_builtin_type = GDScriptParser::get_builtin_type(key_elem_type_name);5684if (key_elem_builtin_type < Variant::VARIANT_MAX) {5685// Builtin type.5686key_elem_type.kind = GDScriptParser::DataType::BUILTIN;5687key_elem_type.builtin_type = key_elem_builtin_type;5688} else if (class_exists(key_elem_type_name)) {5689key_elem_type.kind = GDScriptParser::DataType::NATIVE;5690key_elem_type.builtin_type = Variant::OBJECT;5691key_elem_type.native_type = key_elem_type_name;5692} else if (ScriptServer::is_global_class(key_elem_type_name)) {5693// Just load this as it shouldn't be a GDScript.5694Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(key_elem_type_name));5695key_elem_type.kind = GDScriptParser::DataType::SCRIPT;5696key_elem_type.builtin_type = Variant::OBJECT;5697key_elem_type.native_type = script->get_instance_base_type();5698key_elem_type.script_type = script;5699} else {5700ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed dictionary.");5701}5702key_elem_type.is_constant = false;57035704StringName value_elem_type_name = p_property.hint_string.get_slicec(';', 1);5705GDScriptParser::DataType value_elem_type;5706value_elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;57075708Variant::Type value_elem_builtin_type = GDScriptParser::get_builtin_type(value_elem_type_name);5709if (value_elem_builtin_type < Variant::VARIANT_MAX) {5710// Builtin type.5711value_elem_type.kind = GDScriptParser::DataType::BUILTIN;5712value_elem_type.builtin_type = value_elem_builtin_type;5713} else if (class_exists(value_elem_type_name)) {5714value_elem_type.kind = GDScriptParser::DataType::NATIVE;5715value_elem_type.builtin_type = Variant::OBJECT;5716value_elem_type.native_type = value_elem_type_name;5717} else if (ScriptServer::is_global_class(value_elem_type_name)) {5718// Just load this as it shouldn't be a GDScript.5719Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(value_elem_type_name));5720value_elem_type.kind = GDScriptParser::DataType::SCRIPT;5721value_elem_type.builtin_type = Variant::OBJECT;5722value_elem_type.native_type = script->get_instance_base_type();5723value_elem_type.script_type = script;5724} else {5725ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed dictionary.");5726}5727value_elem_type.is_constant = false;57285729result.set_container_element_type(0, key_elem_type);5730result.set_container_element_type(1, value_elem_type);5731} else if (p_property.type == Variant::INT) {5732// Check if it's enum.5733if ((p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) && p_property.class_name != StringName()) {5734if (CoreConstants::is_global_enum(p_property.class_name)) {5735result = make_global_enum_type(p_property.class_name, StringName(), false);5736result.is_constant = false;5737} else {5738Vector<String> names = String(p_property.class_name).split(ENUM_SEPARATOR);5739if (names.size() == 2) {5740result = make_enum_type(names[1], names[0], false);5741result.is_constant = false;5742}5743}5744}5745// PROPERTY_USAGE_CLASS_IS_BITFIELD: BitField[T] isn't supported (yet?), use plain int.5746}5747}5748return result;5749}57505751bool 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) {5752r_method_flags = METHOD_FLAGS_DEFAULT;5753r_default_arg_count = 0;5754if (r_native_class) {5755*r_native_class = StringName();5756}5757StringName function_name = p_function;57585759bool was_enum = false;5760if (p_base_type.kind == GDScriptParser::DataType::ENUM) {5761was_enum = true;5762if (p_base_type.is_meta_type) {5763// Enum type can be treated as a dictionary value.5764p_base_type.kind = GDScriptParser::DataType::BUILTIN;5765p_base_type.is_meta_type = false;5766} else {5767push_error("Cannot call function on enum value.", p_source);5768return false;5769}5770}57715772if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {5773// Construct a base type to get methods.5774Callable::CallError err;5775Variant dummy;5776Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);5777if (err.error != Callable::CallError::CALL_OK) {5778ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");5779}5780List<MethodInfo> methods;5781dummy.get_method_list(&methods);57825783for (const MethodInfo &E : methods) {5784if (E.name == p_function) {5785function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5786// Cannot use non-const methods on enums.5787if (!r_method_flags.has_flag(METHOD_FLAG_STATIC) && was_enum && !(E.flags & METHOD_FLAG_CONST)) {5788push_error(vformat(R"*(Cannot call non-const Dictionary function "%s()" on enum "%s".)*", p_function, p_base_type.enum_type), p_source);5789}5790return true;5791}5792}57935794return false;5795}57965797StringName base_native = p_base_type.native_type;5798if (base_native != StringName()) {5799// Empty native class might happen in some Script implementations.5800// Just ignore it.5801if (!class_exists(base_native)) {5802push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source);5803return false;5804} else if (p_is_constructor && ClassDB::is_abstract(base_native)) {5805if (p_base_type.kind == GDScriptParser::DataType::CLASS) {5806push_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);5807} else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) {5808push_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);5809} else {5810push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source);5811}5812return false;5813}5814}58155816if (p_is_constructor) {5817function_name = GDScriptLanguage::get_singleton()->strings._init;5818r_method_flags.set_flag(METHOD_FLAG_STATIC);5819}58205821GDScriptParser::ClassNode *base_class = p_base_type.class_type;5822GDScriptParser::FunctionNode *found_function = nullptr;58235824while (found_function == nullptr && base_class != nullptr) {5825if (base_class->has_member(function_name)) {5826if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {5827// TODO: If this is Callable it can have a better error message.5828push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);5829return false;5830}58315832resolve_class_member(base_class, function_name, p_source);5833found_function = base_class->get_member(function_name).function;5834}58355836resolve_class_inheritance(base_class, p_source);5837base_class = base_class->base_type.class_type;5838}58395840if (found_function != nullptr) {5841if (found_function->is_abstract) {5842r_method_flags.set_flag(METHOD_FLAG_VIRTUAL_REQUIRED);5843}5844if (p_is_constructor || found_function->is_static) {5845r_method_flags.set_flag(METHOD_FLAG_STATIC);5846}5847for (int i = 0; i < found_function->parameters.size(); i++) {5848r_par_types.push_back(found_function->parameters[i]->get_datatype());5849if (found_function->parameters[i]->initializer != nullptr) {5850r_default_arg_count++;5851}5852}5853if (found_function->is_vararg()) {5854r_method_flags.set_flag(METHOD_FLAG_VARARG);5855}5856r_return_type = p_is_constructor ? p_base_type : found_function->get_datatype();5857r_return_type.is_meta_type = false;5858r_return_type.is_coroutine = found_function->is_coroutine;58595860return true;5861}58625863Ref<Script> base_script = p_base_type.script_type;58645865while (base_script.is_valid() && base_script->has_method(function_name)) {5866MethodInfo info = base_script->get_method_info(function_name);58675868if (!(info == MethodInfo())) {5869return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5870}5871base_script = base_script->get_base_script();5872}58735874// If the base is a script, it might be trying to access members of the Script class itself.5875if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {5876MethodInfo info;5877StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());58785879if (ClassDB::get_method_info(script_class, function_name, &info)) {5880return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5881}5882}58835884if (p_is_constructor) {5885// Native types always have a default constructor.5886r_return_type = p_base_type;5887r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;5888r_return_type.is_meta_type = false;5889return true;5890}58915892MethodInfo info;5893if (ClassDB::get_method_info(base_native, function_name, &info)) {5894bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);5895if (valid && Engine::get_singleton()->has_singleton(base_native)) {5896r_method_flags.set_flag(METHOD_FLAG_STATIC);5897}5898#ifdef DEBUG_ENABLED5899MethodBind *native_method = ClassDB::get_method(base_native, function_name);5900if (native_method && r_native_class) {5901*r_native_class = native_method->get_instance_class();5902}5903#endif // DEBUG_ENABLED5904return valid;5905}59065907return false;5908}59095910bool 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) {5911r_return_type = type_from_property(p_info.return_val);5912r_default_arg_count = p_info.default_arguments.size();5913r_method_flags = p_info.flags;59145915for (const PropertyInfo &E : p_info.arguments) {5916r_par_types.push_back(type_from_property(E, true));5917}5918return true;5919}59205921void GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {5922List<GDScriptParser::DataType> arg_types;59235924for (const PropertyInfo &E : p_method.arguments) {5925arg_types.push_back(type_from_property(E, true));5926}59275928validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);5929}59305931void 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) {5932if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {5933push_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);5934}5935if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {5936push_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()]);5937}59385939List<GDScriptParser::DataType>::ConstIterator par_itr = p_par_types.begin();5940for (int i = 0; i < p_call->arguments.size(); ++par_itr, ++i) {5941if (i >= p_par_types.size()) {5942// Already on vararg place.5943break;5944}5945GDScriptParser::DataType par_type = *par_itr;59465947if (par_type.is_hard_type() && p_call->arguments[i]->is_constant) {5948update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");5949}5950GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();59515952if (arg_type.is_variant() || !arg_type.is_hard_type()) {5953#ifdef DEBUG_ENABLED5954// Argument can be anything, so this is unsafe (unless the parameter is a hard variant).5955if (!(par_type.is_hard_type() && par_type.is_variant())) {5956mark_node_unsafe(p_call->arguments[i]);5957parser->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());5958}5959#endif // DEBUG_ENABLED5960} else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {5961if (!is_type_compatible(arg_type, par_type)) {5962push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*",5963p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),5964p_call->arguments[i]);5965#ifdef DEBUG_ENABLED5966} else {5967// Supertypes are acceptable for dynamic compliance, but it's unsafe.5968mark_node_unsafe(p_call);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#endif // DEBUG_ENABLED5971}5972#ifdef DEBUG_ENABLED5973} 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) {5974parser->push_warning(p_call->arguments[i], GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);5975#endif // DEBUG_ENABLED5976}5977}5978}59795980#ifdef DEBUG_ENABLED5981void GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_identifier, const String &p_context, const bool p_in_local_scope) {5982const StringName &name = p_identifier->name;59835984{5985List<MethodInfo> gdscript_funcs;5986GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);59875988for (MethodInfo &info : gdscript_funcs) {5989if (info.name == name) {5990parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");5991return;5992}5993}5994if (Variant::has_utility_function(name)) {5995parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");5996return;5997} else if (class_exists(name)) {5998parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "native class");5999return;6000} else if (ScriptServer::is_global_class(name)) {6001String class_path = ScriptServer::get_global_class_path(name).get_file();6002parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, vformat(R"(global class defined in "%s")", class_path));6003return;6004} else if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {6005parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in type");6006return;6007}6008}60096010const GDScriptParser::DataType current_class_type = parser->current_class->get_datatype();6011if (p_in_local_scope) {6012GDScriptParser::ClassNode *base_class = current_class_type.class_type;60136014if (base_class != nullptr) {6015if (base_class->has_member(name)) {6016parser->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()));6017return;6018}6019base_class = base_class->base_type.class_type;6020}60216022while (base_class != nullptr) {6023if (base_class->has_member(name)) {6024String base_class_name = base_class->get_global_name();6025if (base_class_name.is_empty()) {6026base_class_name = base_class->fqcn;6027}60286029parser->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);6030return;6031}6032base_class = base_class->base_type.class_type;6033}6034}60356036StringName native_base_class = current_class_type.native_type;6037while (native_base_class != StringName()) {6038ERR_FAIL_COND_MSG(!class_exists(native_base_class), "Non-existent native base class.");60396040if (ClassDB::has_method(native_base_class, name, true)) {6041parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "method", native_base_class);6042return;6043} else if (ClassDB::has_signal(native_base_class, name, true)) {6044parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "signal", native_base_class);6045return;6046} else if (ClassDB::has_property(native_base_class, name, true)) {6047parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "property", native_base_class);6048return;6049} else if (ClassDB::has_integer_constant(native_base_class, name, true)) {6050parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "constant", native_base_class);6051return;6052} else if (ClassDB::has_enum(native_base_class, name, true)) {6053parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "enum", native_base_class);6054return;6055}6056native_base_class = ClassDB::get_parent_class(native_base_class);6057}6058}6059#endif // DEBUG_ENABLED60606061GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {6062// Unary version.6063GDScriptParser::DataType nil_type;6064nil_type.builtin_type = Variant::NIL;6065nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;6066return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);6067}60686069GDScriptParser::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) {6070if (p_operation == Variant::OP_AND || p_operation == Variant::OP_OR) {6071// Those work for any type of argument and always return a boolean.6072// They don't use the Variant operator since they have short-circuit semantics.6073r_valid = true;6074GDScriptParser::DataType result;6075result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;6076result.kind = GDScriptParser::DataType::BUILTIN;6077result.builtin_type = Variant::BOOL;6078return result;6079}60806081Variant::Type a_type = p_a.builtin_type;6082Variant::Type b_type = p_b.builtin_type;60836084if (p_a.kind == GDScriptParser::DataType::ENUM) {6085if (p_a.is_meta_type) {6086a_type = Variant::DICTIONARY;6087} else {6088a_type = Variant::INT;6089}6090}6091if (p_b.kind == GDScriptParser::DataType::ENUM) {6092if (p_b.is_meta_type) {6093b_type = Variant::DICTIONARY;6094} else {6095b_type = Variant::INT;6096}6097}60986099GDScriptParser::DataType result;6100bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();61016102if (p_operation == Variant::OP_ADD && a_type == Variant::ARRAY && b_type == Variant::ARRAY) {6103if (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)) {6104r_valid = true;6105result = p_a;6106result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;6107return result;6108}6109}61106111Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);6112bool validated = op_eval != nullptr;61136114if (validated) {6115r_valid = true;6116result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;6117result.kind = GDScriptParser::DataType::BUILTIN;6118result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);6119} else {6120r_valid = !hard_operation;6121result.kind = GDScriptParser::DataType::VARIANT;6122}61236124return result;6125}61266127bool 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) {6128#ifdef DEBUG_ENABLED6129if (p_source_node) {6130if (p_target.kind == GDScriptParser::DataType::ENUM) {6131if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {6132parser->push_warning(p_source_node, GDScriptWarning::INT_AS_ENUM_WITHOUT_CAST);6133}6134}6135}6136#endif // DEBUG_ENABLED6137return check_type_compatibility(p_target, p_source, p_allow_implicit_conversion, p_source_node);6138}61396140// TODO: Add safe/unsafe return variable (for variant cases)6141bool 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) {6142// These return "true" so it doesn't affect users negatively.6143ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");6144ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");61456146if (p_target.kind == GDScriptParser::DataType::VARIANT) {6147// Variant can receive anything.6148return true;6149}61506151if (p_source.kind == GDScriptParser::DataType::VARIANT) {6152// TODO: This is acceptable but unsafe. Make sure unsafe line is set.6153return true;6154}61556156if (p_target.kind == GDScriptParser::DataType::BUILTIN) {6157bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;6158if (!valid && p_allow_implicit_conversion) {6159valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);6160}6161if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {6162// Enum value is also integer.6163valid = true;6164}6165if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {6166// Check the element type.6167if (p_target.has_container_element_type(0) && p_source.has_container_element_type(0)) {6168valid = p_target.get_container_element_type(0) == p_source.get_container_element_type(0);6169}6170}6171if (valid && p_target.builtin_type == Variant::DICTIONARY && p_source.builtin_type == Variant::DICTIONARY) {6172// Check the element types.6173if (p_target.has_container_element_type(0) && p_source.has_container_element_type(0)) {6174valid = p_target.get_container_element_type(0) == p_source.get_container_element_type(0);6175}6176if (valid && p_target.has_container_element_type(1) && p_source.has_container_element_type(1)) {6177valid = p_target.get_container_element_type(1) == p_source.get_container_element_type(1);6178}6179}6180return valid;6181}61826183if (p_target.kind == GDScriptParser::DataType::ENUM) {6184if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {6185return true;6186}6187if (p_source.kind == GDScriptParser::DataType::ENUM) {6188if (p_source.native_type == p_target.native_type) {6189return true;6190}6191}6192return false;6193}61946195// From here on the target type is an object, so we have to test polymorphism.61966197if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {6198// null is acceptable in object.6199return true;6200}62016202StringName src_native;6203Ref<Script> src_script;6204const GDScriptParser::ClassNode *src_class = nullptr;62056206switch (p_source.kind) {6207case GDScriptParser::DataType::NATIVE:6208if (p_target.kind != GDScriptParser::DataType::NATIVE) {6209// Non-native class cannot be supertype of native.6210return false;6211}6212if (p_source.is_meta_type) {6213src_native = GDScriptNativeClass::get_class_static();6214} else {6215src_native = p_source.native_type;6216}6217break;6218case GDScriptParser::DataType::SCRIPT:6219if (p_target.kind == GDScriptParser::DataType::CLASS) {6220// A script type cannot be a subtype of a GDScript class.6221return false;6222}6223if (p_source.script_type.is_null()) {6224return false;6225}6226if (p_source.is_meta_type) {6227src_native = p_source.script_type->get_class_name();6228} else {6229src_script = p_source.script_type;6230src_native = src_script->get_instance_base_type();6231}6232break;6233case GDScriptParser::DataType::CLASS:6234if (p_source.is_meta_type) {6235src_native = GDScript::get_class_static();6236} else {6237src_class = p_source.class_type;6238const GDScriptParser::ClassNode *base = src_class;6239while (base->base_type.kind == GDScriptParser::DataType::CLASS) {6240base = base->base_type.class_type;6241}6242src_native = base->base_type.native_type;6243src_script = base->base_type.script_type;6244}6245break;6246case GDScriptParser::DataType::VARIANT:6247case GDScriptParser::DataType::BUILTIN:6248case GDScriptParser::DataType::ENUM:6249case GDScriptParser::DataType::RESOLVING:6250case GDScriptParser::DataType::UNRESOLVED:6251break; // Already solved before.6252}62536254switch (p_target.kind) {6255case GDScriptParser::DataType::NATIVE: {6256if (p_target.is_meta_type) {6257return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());6258}6259return ClassDB::is_parent_class(src_native, p_target.native_type);6260}6261case GDScriptParser::DataType::SCRIPT:6262if (p_target.is_meta_type) {6263return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());6264}6265while (src_script.is_valid()) {6266if (src_script == p_target.script_type) {6267return true;6268}6269src_script = src_script->get_base_script();6270}6271return false;6272case GDScriptParser::DataType::CLASS:6273if (p_target.is_meta_type) {6274return ClassDB::is_parent_class(src_native, GDScript::get_class_static());6275}6276while (src_class != nullptr) {6277if (src_class == p_target.class_type || src_class->fqcn == p_target.class_type->fqcn) {6278return true;6279}6280src_class = src_class->base_type.class_type;6281}6282return false;6283case GDScriptParser::DataType::VARIANT:6284case GDScriptParser::DataType::BUILTIN:6285case GDScriptParser::DataType::ENUM:6286case GDScriptParser::DataType::RESOLVING:6287case GDScriptParser::DataType::UNRESOLVED:6288break; // Already solved before.6289}62906291return false;6292}62936294void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {6295mark_node_unsafe(p_origin);6296parser->push_error(p_message, p_origin);6297}62986299void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {6300#ifdef DEBUG_ENABLED6301if (p_node == nullptr) {6302return;6303}63046305for (int i = p_node->start_line; i <= p_node->end_line; i++) {6306parser->unsafe_lines.insert(i);6307}6308#endif // DEBUG_ENABLED6309}63106311void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) {6312GDScriptParser::IdentifierNode *identifier = nullptr;6313if (p_node->type == GDScriptParser::Node::IDENTIFIER) {6314identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node);6315} else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) {6316GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node);6317if (subscript->is_attribute) {6318identifier = subscript->attribute;6319}6320}6321if (identifier == nullptr) {6322return;6323}63246325GDScriptParser::Node *source = nullptr;6326switch (identifier->source) {6327case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {6328source = identifier->variable_source;6329} break;6330case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {6331source = identifier->parameter_source;6332} break;6333case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {6334source = identifier->variable_source;6335} break;6336case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {6337source = identifier->bind_source;6338} break;6339default:6340break;6341}6342if (source == nullptr) {6343return;6344}63456346GDScriptParser::DataType datatype;6347datatype.kind = GDScriptParser::DataType::VARIANT;6348source->set_datatype(datatype);6349}63506351void GDScriptAnalyzer::mark_lambda_use_self() {6352GDScriptParser::LambdaNode *lambda = current_lambda;6353while (lambda != nullptr) {6354lambda->use_self = true;6355lambda = lambda->parent_lambda;6356}6357}63586359void GDScriptAnalyzer::resolve_pending_lambda_bodies() {6360if (pending_body_resolution_lambdas.is_empty()) {6361return;6362}63636364GDScriptParser::LambdaNode *previous_lambda = current_lambda;6365bool previous_static_context = static_context;63666367List<GDScriptParser::LambdaNode *> lambdas = pending_body_resolution_lambdas;6368pending_body_resolution_lambdas.clear();63696370for (GDScriptParser::LambdaNode *lambda : lambdas) {6371current_lambda = lambda;6372static_context = lambda->function->is_static;63736374resolve_function_body(lambda->function, true);63756376int captures_amount = lambda->captures.size();6377if (captures_amount > 0) {6378// Create space for lambda parameters.6379// At the beginning to not mess with optional parameters.6380int param_count = lambda->function->parameters.size();6381lambda->function->parameters.resize(param_count + captures_amount);6382for (int i = param_count - 1; i >= 0; i--) {6383lambda->function->parameters.write[i + captures_amount] = lambda->function->parameters[i];6384lambda->function->parameters_indices[lambda->function->parameters[i]->identifier->name] = i + captures_amount;6385}63866387// Add captures as extra parameters at the beginning.6388for (int i = 0; i < lambda->captures.size(); i++) {6389GDScriptParser::IdentifierNode *capture = lambda->captures[i];6390GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();6391capture_param->identifier = capture;6392capture_param->usages = capture->usages;6393capture_param->set_datatype(capture->get_datatype());63946395lambda->function->parameters.write[i] = capture_param;6396lambda->function->parameters_indices[capture->name] = i;6397}6398}6399}64006401current_lambda = previous_lambda;6402static_context = previous_static_context;6403}64046405bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {6406return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);6407}64086409Error GDScriptAnalyzer::resolve_inheritance() {6410return resolve_class_inheritance(parser->head, true);6411}64126413Error GDScriptAnalyzer::resolve_interface() {6414resolve_class_interface(parser->head, true);6415return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6416}64176418Error GDScriptAnalyzer::resolve_body() {6419resolve_class_body(parser->head, true);64206421#ifdef DEBUG_ENABLED6422// Apply here, after all `@warning_ignore`s have been resolved and applied.6423parser->apply_pending_warnings();6424#endif // DEBUG_ENABLED64256426return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6427}64286429Error GDScriptAnalyzer::resolve_dependencies() {6430for (KeyValue<String, Ref<GDScriptParserRef>> &K : parser->depended_parsers) {6431if (K.value.is_null()) {6432return ERR_PARSE_ERROR;6433}6434K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);6435}64366437return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;6438}64396440Error GDScriptAnalyzer::analyze() {6441parser->errors.clear();64426443Error err = resolve_inheritance();6444if (err) {6445return err;6446}64476448resolve_interface();6449err = resolve_body();6450if (err) {6451return err;6452}64536454return resolve_dependencies();6455}64566457GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {6458parser = p_parser;6459}646064616462