Path: blob/master/modules/gdscript/gdscript_compiler.cpp
20843 views
/**************************************************************************/1/* gdscript_compiler.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_compiler.h"3132#include "gdscript.h"33#include "gdscript_analyzer.h"34#include "gdscript_byte_codegen.h"35#include "gdscript_cache.h"36#include "gdscript_utility_functions.h"3738#include "core/config/engine.h"39#include "core/config/project_settings.h"4041#include "scene/scene_string_names.h"4243bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {44if (codegen.function_node && codegen.function_node->is_static) {45return false;46}4748if (_is_local_or_parameter(codegen, p_name)) {49return false; //shadowed50}5152return _is_class_member_property(codegen.script, p_name);53}5455bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {56GDScript *scr = owner;57GDScriptNativeClass *nc = nullptr;58while (scr) {59if (scr->native.is_valid()) {60nc = scr->native.ptr();61}62scr = scr->base.ptr();63}6465ERR_FAIL_NULL_V(nc, false);6667return ClassDB::has_property(nc->get_name(), p_name);68}6970bool GDScriptCompiler::_is_local_or_parameter(CodeGen &codegen, const StringName &p_name) {71return codegen.parameters.has(p_name) || codegen.locals.has(p_name);72}7374void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::Node *p_node) {75if (!error.is_empty()) {76return;77}7879error = p_error;80if (p_node) {81err_line = p_node->start_line;82err_column = p_node->start_column;83} else {84err_line = 0;85err_column = 0;86}87}8889GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner, bool p_handle_metatype) {90if (!p_datatype.is_set() || !p_datatype.is_hard_type() || p_datatype.is_coroutine) {91return GDScriptDataType();92}9394GDScriptDataType result;9596switch (p_datatype.kind) {97case GDScriptParser::DataType::VARIANT: {98result.kind = GDScriptDataType::VARIANT;99} break;100case GDScriptParser::DataType::BUILTIN: {101result.kind = GDScriptDataType::BUILTIN;102result.builtin_type = p_datatype.builtin_type;103} break;104case GDScriptParser::DataType::NATIVE: {105if (p_handle_metatype && p_datatype.is_meta_type) {106result.kind = GDScriptDataType::NATIVE;107result.builtin_type = Variant::OBJECT;108// Fixes GH-82255. `GDScriptNativeClass` is obtainable in GDScript,109// but is not a registered and exposed class, so `GDScriptNativeClass`110// is missing from `GDScriptLanguage::get_singleton()->get_global_map()`.111//result.native_type = GDScriptNativeClass::get_class_static();112result.native_type = Object::get_class_static();113break;114}115116result.kind = GDScriptDataType::NATIVE;117result.builtin_type = p_datatype.builtin_type;118result.native_type = p_datatype.native_type;119120#ifdef DEBUG_ENABLED121if (unlikely(!GDScriptLanguage::get_singleton()->get_global_map().has(result.native_type))) {122_set_error(vformat(R"(GDScript bug (please report): Native class "%s" not found.)", result.native_type), nullptr);123return GDScriptDataType();124}125#endif126} break;127case GDScriptParser::DataType::SCRIPT: {128if (p_handle_metatype && p_datatype.is_meta_type) {129result.kind = GDScriptDataType::NATIVE;130result.builtin_type = Variant::OBJECT;131result.native_type = p_datatype.script_type.is_valid() ? p_datatype.script_type->get_class_name() : Script::get_class_static();132break;133}134135result.kind = GDScriptDataType::SCRIPT;136result.builtin_type = p_datatype.builtin_type;137result.script_type_ref = p_datatype.script_type;138result.script_type = result.script_type_ref.ptr();139result.native_type = p_datatype.native_type;140} break;141case GDScriptParser::DataType::CLASS: {142if (p_handle_metatype && p_datatype.is_meta_type) {143result.kind = GDScriptDataType::NATIVE;144result.builtin_type = Variant::OBJECT;145result.native_type = GDScript::get_class_static();146break;147}148149result.kind = GDScriptDataType::GDSCRIPT;150result.builtin_type = p_datatype.builtin_type;151result.native_type = p_datatype.native_type;152153bool is_local_class = parser->has_class(p_datatype.class_type);154155Ref<GDScript> script;156if (is_local_class) {157script = Ref<GDScript>(main_script);158} else {159Error err = OK;160script = GDScriptCache::get_shallow_script(p_datatype.script_path, err, p_owner->path);161if (err) {162_set_error(vformat(R"(Could not find script "%s": %s)", p_datatype.script_path, error_names[err]), nullptr);163return GDScriptDataType();164}165}166167if (script.is_valid()) {168script = Ref<GDScript>(script->find_class(p_datatype.class_type->fqcn));169}170171if (script.is_null()) {172_set_error(vformat(R"(Could not find class "%s" in "%s".)", p_datatype.class_type->fqcn, p_datatype.script_path), nullptr);173return GDScriptDataType();174} else {175// Only hold a strong reference if the owner of the element qualified with this type is not local, to avoid cyclic references (leaks).176// TODO: Might lead to use after free if script_type is a subclass and is used after its parent is freed.177if (!is_local_class) {178result.script_type_ref = script;179}180result.script_type = script.ptr();181result.native_type = p_datatype.native_type;182}183} break;184case GDScriptParser::DataType::ENUM:185if (p_handle_metatype && p_datatype.is_meta_type) {186result.kind = GDScriptDataType::BUILTIN;187result.builtin_type = Variant::DICTIONARY;188break;189}190191result.kind = GDScriptDataType::BUILTIN;192result.builtin_type = p_datatype.builtin_type;193break;194case GDScriptParser::DataType::RESOLVING:195case GDScriptParser::DataType::UNRESOLVED: {196_set_error("Parser bug (please report): converting unresolved type.", nullptr);197return GDScriptDataType();198}199}200201for (int i = 0; i < p_datatype.container_element_types.size(); i++) {202result.set_container_element_type(i, _gdtype_from_datatype(p_datatype.get_container_element_type_or_variant(i), p_owner, false));203}204205return result;206}207208static bool _is_exact_type(const PropertyInfo &p_par_type, const GDScriptDataType &p_arg_type) {209if (!p_arg_type.has_type()) {210return false;211}212if (p_par_type.type == Variant::NIL) {213return false;214}215if (p_par_type.type == Variant::OBJECT) {216if (p_arg_type.kind == GDScriptDataType::BUILTIN) {217return false;218}219StringName class_name;220if (p_arg_type.kind == GDScriptDataType::NATIVE) {221class_name = p_arg_type.native_type;222} else {223class_name = p_arg_type.native_type == StringName() ? p_arg_type.script_type->get_instance_base_type() : p_arg_type.native_type;224}225return p_par_type.class_name == class_name || ClassDB::is_parent_class(class_name, p_par_type.class_name);226} else {227if (p_arg_type.kind != GDScriptDataType::BUILTIN) {228return false;229}230return p_par_type.type == p_arg_type.builtin_type;231}232}233234static bool _can_use_validate_call(const MethodBind *p_method, const Vector<GDScriptCodeGenerator::Address> &p_arguments) {235if (p_method->is_vararg()) {236// Validated call won't work with vararg methods.237return false;238}239if (p_method->get_argument_count() != p_arguments.size()) {240// Validated call won't work with default arguments.241return false;242}243MethodInfo info;244ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info);245for (int64_t i = 0; i < info.arguments.size(); ++i) {246if (!_is_exact_type(info.arguments[i], p_arguments[i].type)) {247return false;248}249}250return true;251}252253GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root, bool p_initializer) {254if (p_expression->is_constant && !(p_expression->get_datatype().is_meta_type && p_expression->get_datatype().kind == GDScriptParser::DataType::CLASS)) {255return codegen.add_constant(p_expression->reduced_value);256}257258GDScriptCodeGenerator *gen = codegen.generator;259260switch (p_expression->type) {261case GDScriptParser::Node::IDENTIFIER: {262// Look for identifiers in current scope.263const GDScriptParser::IdentifierNode *in = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);264265StringName identifier = in->name;266267switch (in->source) {268// LOCALS.269case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:270case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:271case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:272case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:273case GDScriptParser::IdentifierNode::LOCAL_BIND: {274// Try function parameters.275if (codegen.parameters.has(identifier)) {276return codegen.parameters[identifier];277}278279// Try local variables and constants.280if (!p_initializer && codegen.locals.has(identifier)) {281return codegen.locals[identifier];282}283} break;284285// MEMBERS.286case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:287case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:288case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:289case GDScriptParser::IdentifierNode::INHERITED_VARIABLE: {290// Try class members.291if (_is_class_member_property(codegen, identifier)) {292// Get property.293GDScriptCodeGenerator::Address temp = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype(), codegen.script));294gen->write_get_member(temp, identifier);295return temp;296}297298// Try members.299if (!codegen.function_node || !codegen.function_node->is_static) {300// Try member variables.301if (codegen.script->member_indices.has(identifier)) {302if (codegen.script->member_indices[identifier].getter != StringName() && codegen.script->member_indices[identifier].getter != codegen.function_name) {303// Perform getter.304GDScriptCodeGenerator::Address temp = codegen.add_temporary(codegen.script->member_indices[identifier].data_type);305Vector<GDScriptCodeGenerator::Address> args; // No argument needed.306gen->write_call_self(temp, codegen.script->member_indices[identifier].getter, args);307return temp;308} else {309// No getter or inside getter: direct member access.310int idx = codegen.script->member_indices[identifier].index;311return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, idx, codegen.script->get_member_type(identifier));312}313}314}315316// Try methods and signals (can be Callable and Signal).317{318// Search upwards through parent classes:319const GDScriptParser::ClassNode *base_class = codegen.class_node;320while (base_class != nullptr) {321if (base_class->has_member(identifier)) {322const GDScriptParser::ClassNode::Member &member = base_class->get_member(identifier);323if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) {324// Get like it was a property.325GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here.326327GDScriptCodeGenerator::Address base(GDScriptCodeGenerator::Address::SELF);328if (member.type == GDScriptParser::ClassNode::Member::FUNCTION && member.function->is_static) {329base = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::CLASS);330}331332gen->write_get_named(temp, identifier, base);333return temp;334}335}336base_class = base_class->base_type.class_type;337}338339// Try in native base.340GDScript *scr = codegen.script;341GDScriptNativeClass *nc = nullptr;342while (scr) {343if (scr->native.is_valid()) {344nc = scr->native.ptr();345}346scr = scr->base.ptr();347}348349if (nc && (identifier == CoreStringName(free_) || ClassDB::has_signal(nc->get_name(), identifier) || ClassDB::has_method(nc->get_name(), identifier))) {350// Get like it was a property.351GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here.352GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF);353354gen->write_get_named(temp, identifier, self);355return temp;356}357}358} break;359case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:360case GDScriptParser::IdentifierNode::MEMBER_CLASS: {361// Try class constants.362GDScript *owner = codegen.script;363while (owner) {364GDScript *scr = owner;365GDScriptNativeClass *nc = nullptr;366367while (scr) {368if (scr->constants.has(identifier)) {369return codegen.add_constant(scr->constants[identifier]); // TODO: Get type here.370}371if (scr->native.is_valid()) {372nc = scr->native.ptr();373}374scr = scr->base.ptr();375}376377// Class C++ integer constant.378if (nc) {379bool success = false;380int64_t constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success);381if (success) {382return codegen.add_constant(constant);383}384}385386owner = owner->_owner;387}388} break;389case GDScriptParser::IdentifierNode::STATIC_VARIABLE: {390// Try static variables.391GDScript *scr = codegen.script;392while (scr) {393if (scr->static_variables_indices.has(identifier)) {394if (scr->static_variables_indices[identifier].getter != StringName() && scr->static_variables_indices[identifier].getter != codegen.function_name) {395// Perform getter.396GDScriptCodeGenerator::Address temp = codegen.add_temporary(scr->static_variables_indices[identifier].data_type);397GDScriptCodeGenerator::Address class_addr(GDScriptCodeGenerator::Address::CLASS);398Vector<GDScriptCodeGenerator::Address> args; // No argument needed.399gen->write_call(temp, class_addr, scr->static_variables_indices[identifier].getter, args);400return temp;401} else {402// No getter or inside getter: direct variable access.403GDScriptCodeGenerator::Address temp = codegen.add_temporary(scr->static_variables_indices[identifier].data_type);404GDScriptCodeGenerator::Address _class = codegen.add_constant(scr);405int index = scr->static_variables_indices[identifier].index;406gen->write_get_static_variable(temp, _class, index);407return temp;408}409}410scr = scr->base.ptr();411}412} break;413414// GLOBALS.415case GDScriptParser::IdentifierNode::NATIVE_CLASS:416case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE: {417// Try globals.418if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {419// If it's an autoload singleton, we postpone to load it at runtime.420// This is so one autoload doesn't try to load another before it's compiled.421HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads(ProjectSettings::get_singleton()->get_autoload_list());422if (autoloads.has(identifier) && autoloads[identifier].is_singleton) {423GDScriptCodeGenerator::Address global = codegen.add_temporary(_gdtype_from_datatype(in->get_datatype(), codegen.script));424int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];425gen->write_store_global(global, idx);426return global;427} else {428int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];429Variant global = GDScriptLanguage::get_singleton()->get_global_array()[idx];430return codegen.add_constant(global);431}432}433434// Try global classes.435if (ScriptServer::is_global_class(identifier)) {436const GDScriptParser::ClassNode *class_node = codegen.class_node;437while (class_node->outer) {438class_node = class_node->outer;439}440441Ref<Resource> res;442443if (class_node->identifier && class_node->identifier->name == identifier) {444res = Ref<GDScript>(main_script);445} else {446String global_class_path = ScriptServer::get_global_class_path(identifier);447if (ResourceLoader::get_resource_type(global_class_path) == "GDScript") {448Error err = OK;449// Should not need to pass p_owner since analyzer will already have done it.450res = GDScriptCache::get_shallow_script(global_class_path, err);451if (err != OK) {452_set_error("Can't load global class " + String(identifier), p_expression);453r_error = ERR_COMPILATION_FAILED;454return GDScriptCodeGenerator::Address();455}456} else {457res = ResourceLoader::load(global_class_path);458if (res.is_null()) {459_set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression);460r_error = ERR_COMPILATION_FAILED;461return GDScriptCodeGenerator::Address();462}463}464}465466return codegen.add_constant(res);467}468469#ifdef TOOLS_ENABLED470if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) {471GDScriptCodeGenerator::Address global = codegen.add_temporary(); // TODO: Get type.472gen->write_store_named_global(global, identifier);473return global;474}475#endif476477} break;478}479480// Not found, error.481_set_error("Identifier not found: " + String(identifier), p_expression);482r_error = ERR_COMPILATION_FAILED;483return GDScriptCodeGenerator::Address();484} break;485case GDScriptParser::Node::LITERAL: {486// Return constant.487const GDScriptParser::LiteralNode *cn = static_cast<const GDScriptParser::LiteralNode *>(p_expression);488489return codegen.add_constant(cn->value);490} break;491case GDScriptParser::Node::SELF: {492//return constant493if (codegen.function_node && codegen.function_node->is_static) {494_set_error("'self' not present in static function.", p_expression);495r_error = ERR_COMPILATION_FAILED;496return GDScriptCodeGenerator::Address();497}498return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF);499} break;500case GDScriptParser::Node::ARRAY: {501const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);502Vector<GDScriptCodeGenerator::Address> values;503504// Create the result temporary first since it's the last to be killed.505GDScriptDataType array_type = _gdtype_from_datatype(an->get_datatype(), codegen.script);506GDScriptCodeGenerator::Address result = codegen.add_temporary(array_type);507508for (int i = 0; i < an->elements.size(); i++) {509GDScriptCodeGenerator::Address val = _parse_expression(codegen, r_error, an->elements[i]);510if (r_error) {511return GDScriptCodeGenerator::Address();512}513values.push_back(val);514}515516if (array_type.has_container_element_type(0)) {517gen->write_construct_typed_array(result, array_type.get_container_element_type(0), values);518} else {519gen->write_construct_array(result, values);520}521522for (int i = 0; i < values.size(); i++) {523if (values[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {524gen->pop_temporary();525}526}527528return result;529} break;530case GDScriptParser::Node::DICTIONARY: {531const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);532Vector<GDScriptCodeGenerator::Address> elements;533534// Create the result temporary first since it's the last to be killed.535GDScriptDataType dict_type = _gdtype_from_datatype(dn->get_datatype(), codegen.script);536GDScriptCodeGenerator::Address result = codegen.add_temporary(dict_type);537538for (int i = 0; i < dn->elements.size(); i++) {539// Key.540GDScriptCodeGenerator::Address element;541switch (dn->style) {542case GDScriptParser::DictionaryNode::PYTHON_DICT:543// Python-style: key is any expression.544element = _parse_expression(codegen, r_error, dn->elements[i].key);545if (r_error) {546return GDScriptCodeGenerator::Address();547}548break;549case GDScriptParser::DictionaryNode::LUA_TABLE:550// Lua-style: key is an identifier interpreted as StringName.551StringName key = dn->elements[i].key->reduced_value.operator StringName();552element = codegen.add_constant(key);553break;554}555556elements.push_back(element);557558element = _parse_expression(codegen, r_error, dn->elements[i].value);559if (r_error) {560return GDScriptCodeGenerator::Address();561}562563elements.push_back(element);564}565566if (dict_type.has_container_element_types()) {567gen->write_construct_typed_dictionary(result, dict_type.get_container_element_type_or_variant(0), dict_type.get_container_element_type_or_variant(1), elements);568} else {569gen->write_construct_dictionary(result, elements);570}571572for (int i = 0; i < elements.size(); i++) {573if (elements[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {574gen->pop_temporary();575}576}577578return result;579} break;580case GDScriptParser::Node::CAST: {581const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);582GDScriptDataType cast_type = _gdtype_from_datatype(cn->get_datatype(), codegen.script, false);583584GDScriptCodeGenerator::Address result;585if (cast_type.has_type()) {586// Create temporary for result first since it will be deleted last.587result = codegen.add_temporary(cast_type);588589GDScriptCodeGenerator::Address src = _parse_expression(codegen, r_error, cn->operand);590591gen->write_cast(result, src, cast_type);592593if (src.mode == GDScriptCodeGenerator::Address::TEMPORARY) {594gen->pop_temporary();595}596} else {597result = _parse_expression(codegen, r_error, cn->operand);598}599600return result;601} break;602case GDScriptParser::Node::CALL: {603const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);604bool is_awaited = p_expression == awaited_node;605GDScriptDataType type = _gdtype_from_datatype(call->get_datatype(), codegen.script);606GDScriptCodeGenerator::Address result;607if (p_root) {608result = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::NIL);609} else {610result = codegen.add_temporary(type);611}612613Vector<GDScriptCodeGenerator::Address> arguments;614for (int i = 0; i < call->arguments.size(); i++) {615GDScriptCodeGenerator::Address arg = _parse_expression(codegen, r_error, call->arguments[i]);616if (r_error) {617return GDScriptCodeGenerator::Address();618}619arguments.push_back(arg);620}621622if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) {623gen->write_construct(result, GDScriptParser::get_builtin_type(call->function_name), arguments);624} else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && Variant::has_utility_function(call->function_name)) {625// Variant utility function.626gen->write_call_utility(result, call->function_name, arguments);627} else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptUtilityFunctions::function_exists(call->function_name)) {628// GDScript utility function.629gen->write_call_gdscript_utility(result, call->function_name, arguments);630} else {631// Regular function.632const GDScriptParser::ExpressionNode *callee = call->callee;633634if (call->is_super) {635// Super call.636gen->write_super_call(result, call->function_name, arguments);637} else {638if (callee->type == GDScriptParser::Node::IDENTIFIER) {639// Self function call.640if (ClassDB::has_method(codegen.script->native->get_name(), call->function_name)) {641// Native method, use faster path.642GDScriptCodeGenerator::Address self;643self.mode = GDScriptCodeGenerator::Address::SELF;644MethodBind *method = ClassDB::get_method(codegen.script->native->get_name(), call->function_name);645646if (_can_use_validate_call(method, arguments)) {647// Exact arguments, use validated call.648gen->write_call_method_bind_validated(result, self, method, arguments);649} else {650// Not exact arguments, but still can use method bind call.651gen->write_call_method_bind(result, self, method, arguments);652}653} else if (call->is_static || codegen.is_static || (codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") {654GDScriptCodeGenerator::Address self;655self.mode = GDScriptCodeGenerator::Address::CLASS;656if (is_awaited) {657gen->write_call_async(result, self, call->function_name, arguments);658} else {659gen->write_call(result, self, call->function_name, arguments);660}661} else {662if (is_awaited) {663gen->write_call_self_async(result, call->function_name, arguments);664} else {665gen->write_call_self(result, call->function_name, arguments);666}667}668} else if (callee->type == GDScriptParser::Node::SUBSCRIPT) {669const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);670671if (subscript->is_attribute) {672// May be static built-in method call.673if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name) < Variant::VARIANT_MAX) {674gen->write_call_builtin_type_static(result, GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name), subscript->attribute->name, arguments);675} else if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && call->function_name != SNAME("new") &&676static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->source == GDScriptParser::IdentifierNode::NATIVE_CLASS && !Engine::get_singleton()->has_singleton(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name)) {677// It's a static native method call.678StringName class_name = static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name;679MethodBind *method = ClassDB::get_method(class_name, subscript->attribute->name);680if (_can_use_validate_call(method, arguments)) {681// Exact arguments, use validated call.682gen->write_call_native_static_validated(result, method, arguments);683} else {684// Not exact arguments, use regular static call685gen->write_call_native_static(result, class_name, subscript->attribute->name, arguments);686}687} else {688GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);689if (r_error) {690return GDScriptCodeGenerator::Address();691}692if (is_awaited) {693gen->write_call_async(result, base, call->function_name, arguments);694} else if (base.type.kind != GDScriptDataType::VARIANT && base.type.kind != GDScriptDataType::BUILTIN) {695// Native method, use faster path.696StringName class_name;697if (base.type.kind == GDScriptDataType::NATIVE) {698class_name = base.type.native_type;699} else {700class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type;701}702if (GDScriptAnalyzer::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) {703MethodBind *method = ClassDB::get_method(class_name, call->function_name);704if (_can_use_validate_call(method, arguments)) {705// Exact arguments, use validated call.706gen->write_call_method_bind_validated(result, base, method, arguments);707} else {708// Not exact arguments, but still can use method bind call.709gen->write_call_method_bind(result, base, method, arguments);710}711} else {712gen->write_call(result, base, call->function_name, arguments);713}714} else if (base.type.kind == GDScriptDataType::BUILTIN) {715gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments);716} else {717gen->write_call(result, base, call->function_name, arguments);718}719if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {720gen->pop_temporary();721}722}723} else {724_set_error("Cannot call something that isn't a function.", call->callee);725r_error = ERR_COMPILATION_FAILED;726return GDScriptCodeGenerator::Address();727}728} else {729_set_error("Compiler bug (please report): incorrect callee type in call node.", call->callee);730r_error = ERR_COMPILATION_FAILED;731return GDScriptCodeGenerator::Address();732}733}734}735736for (int i = 0; i < arguments.size(); i++) {737if (arguments[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {738gen->pop_temporary();739}740}741return result;742} break;743case GDScriptParser::Node::GET_NODE: {744const GDScriptParser::GetNodeNode *get_node = static_cast<const GDScriptParser::GetNodeNode *>(p_expression);745746Vector<GDScriptCodeGenerator::Address> args;747args.push_back(codegen.add_constant(NodePath(get_node->full_path)));748749GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype(), codegen.script));750751MethodBind *get_node_method = ClassDB::get_method("Node", "get_node");752gen->write_call_method_bind_validated(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args);753754return result;755} break;756case GDScriptParser::Node::PRELOAD: {757const GDScriptParser::PreloadNode *preload = static_cast<const GDScriptParser::PreloadNode *>(p_expression);758759// Add resource as constant.760return codegen.add_constant(preload->resource);761} break;762case GDScriptParser::Node::AWAIT: {763const GDScriptParser::AwaitNode *await = static_cast<const GDScriptParser::AwaitNode *>(p_expression);764765GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype(), codegen.script));766GDScriptParser::ExpressionNode *previous_awaited_node = awaited_node;767awaited_node = await->to_await;768GDScriptCodeGenerator::Address argument = _parse_expression(codegen, r_error, await->to_await);769awaited_node = previous_awaited_node;770if (r_error) {771return GDScriptCodeGenerator::Address();772}773774gen->write_await(result, argument);775776if (argument.mode == GDScriptCodeGenerator::Address::TEMPORARY) {777gen->pop_temporary();778}779780return result;781} break;782// Indexing operator.783case GDScriptParser::Node::SUBSCRIPT: {784const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);785GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype(), codegen.script));786787GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);788if (r_error) {789return GDScriptCodeGenerator::Address();790}791792bool named = subscript->is_attribute;793StringName name;794GDScriptCodeGenerator::Address index;795if (subscript->is_attribute) {796if (subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {797GDScriptParser::IdentifierNode *identifier = subscript->attribute;798HashMap<StringName, GDScript::MemberInfo>::Iterator MI = codegen.script->member_indices.find(identifier->name);799800#ifdef DEBUG_ENABLED801if (MI && MI->value.getter == codegen.function_name) {802String n = identifier->name;803_set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", identifier);804r_error = ERR_COMPILATION_FAILED;805return GDScriptCodeGenerator::Address();806}807#endif808809if (MI && MI->value.getter == "") {810// Remove result temp as we don't need it.811gen->pop_temporary();812// Faster than indexing self (as if no self. had been used).813return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, MI->value.index, _gdtype_from_datatype(subscript->get_datatype(), codegen.script));814}815}816817name = subscript->attribute->name;818named = true;819} else {820if (subscript->index->is_constant && subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {821// Also, somehow, named (speed up anyway).822name = subscript->index->reduced_value;823named = true;824} else {825// Regular indexing.826index = _parse_expression(codegen, r_error, subscript->index);827if (r_error) {828return GDScriptCodeGenerator::Address();829}830}831}832833if (named) {834gen->write_get_named(result, name, base);835} else {836gen->write_get(result, index, base);837}838839if (index.mode == GDScriptCodeGenerator::Address::TEMPORARY) {840gen->pop_temporary();841}842if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {843gen->pop_temporary();844}845846return result;847} break;848case GDScriptParser::Node::UNARY_OPERATOR: {849const GDScriptParser::UnaryOpNode *unary = static_cast<const GDScriptParser::UnaryOpNode *>(p_expression);850851GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(unary->get_datatype(), codegen.script));852853GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, unary->operand);854if (r_error) {855return GDScriptCodeGenerator::Address();856}857858gen->write_unary_operator(result, unary->variant_op, operand);859860if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {861gen->pop_temporary();862}863864return result;865}866case GDScriptParser::Node::BINARY_OPERATOR: {867const GDScriptParser::BinaryOpNode *binary = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);868869GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(binary->get_datatype(), codegen.script));870871switch (binary->operation) {872case GDScriptParser::BinaryOpNode::OP_LOGIC_AND: {873// AND operator with early out on failure.874GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);875gen->write_and_left_operand(left_operand);876GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);877gen->write_and_right_operand(right_operand);878879gen->write_end_and(result);880881if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {882gen->pop_temporary();883}884if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {885gen->pop_temporary();886}887} break;888case GDScriptParser::BinaryOpNode::OP_LOGIC_OR: {889// OR operator with early out on success.890GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);891gen->write_or_left_operand(left_operand);892GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);893gen->write_or_right_operand(right_operand);894895gen->write_end_or(result);896897if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {898gen->pop_temporary();899}900if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {901gen->pop_temporary();902}903} break;904default: {905GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);906GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);907908gen->write_binary_operator(result, binary->variant_op, left_operand, right_operand);909910if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {911gen->pop_temporary();912}913if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {914gen->pop_temporary();915}916}917}918return result;919} break;920case GDScriptParser::Node::TERNARY_OPERATOR: {921// x IF a ELSE y operator with early out on failure.922const GDScriptParser::TernaryOpNode *ternary = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);923GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(ternary->get_datatype(), codegen.script));924925gen->write_start_ternary(result);926927GDScriptCodeGenerator::Address condition = _parse_expression(codegen, r_error, ternary->condition);928if (r_error) {929return GDScriptCodeGenerator::Address();930}931gen->write_ternary_condition(condition);932933if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {934gen->pop_temporary();935}936937GDScriptCodeGenerator::Address true_expr = _parse_expression(codegen, r_error, ternary->true_expr);938if (r_error) {939return GDScriptCodeGenerator::Address();940}941gen->write_ternary_true_expr(true_expr);942if (true_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {943gen->pop_temporary();944}945946GDScriptCodeGenerator::Address false_expr = _parse_expression(codegen, r_error, ternary->false_expr);947if (r_error) {948return GDScriptCodeGenerator::Address();949}950gen->write_ternary_false_expr(false_expr);951if (false_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {952gen->pop_temporary();953}954955gen->write_end_ternary();956957return result;958} break;959case GDScriptParser::Node::TYPE_TEST: {960const GDScriptParser::TypeTestNode *type_test = static_cast<const GDScriptParser::TypeTestNode *>(p_expression);961GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(type_test->get_datatype(), codegen.script));962963GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, type_test->operand);964GDScriptDataType test_type = _gdtype_from_datatype(type_test->test_datatype, codegen.script, false);965if (r_error) {966return GDScriptCodeGenerator::Address();967}968969if (test_type.has_type()) {970gen->write_type_test(result, operand, test_type);971} else {972gen->write_assign_true(result);973}974975if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {976gen->pop_temporary();977}978979return result;980} break;981case GDScriptParser::Node::ASSIGNMENT: {982const GDScriptParser::AssignmentNode *assignment = static_cast<const GDScriptParser::AssignmentNode *>(p_expression);983984if (assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {985// SET (chained) MODE!986const GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(assignment->assignee);987#ifdef DEBUG_ENABLED988if (subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {989HashMap<StringName, GDScript::MemberInfo>::Iterator MI = codegen.script->member_indices.find(subscript->attribute->name);990if (MI && MI->value.setter == codegen.function_name) {991String n = subscript->attribute->name;992_set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", subscript);993r_error = ERR_COMPILATION_FAILED;994return GDScriptCodeGenerator::Address();995}996}997#endif998/* Find chain of sets */9991000StringName assign_class_member_property;10011002GDScriptCodeGenerator::Address target_member_property;1003bool is_member_property = false;1004bool member_property_has_setter = false;1005bool member_property_is_in_setter = false;1006bool is_static = false;1007GDScriptCodeGenerator::Address static_var_class;1008int static_var_index = 0;1009GDScriptDataType static_var_data_type;1010StringName var_name;1011StringName member_property_setter_function;10121013List<const GDScriptParser::SubscriptNode *> chain;10141015{1016// Create get/set chain.1017const GDScriptParser::SubscriptNode *n = subscript;1018while (true) {1019chain.push_back(n);1020if (n->base->type != GDScriptParser::Node::SUBSCRIPT) {1021// Check for a property.1022if (n->base->type == GDScriptParser::Node::IDENTIFIER) {1023GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(n->base);1024var_name = identifier->name;1025if (_is_class_member_property(codegen, var_name)) {1026assign_class_member_property = var_name;1027} else if (!_is_local_or_parameter(codegen, var_name)) {1028if (codegen.script->member_indices.has(var_name)) {1029is_member_property = true;1030is_static = false;1031const GDScript::MemberInfo &minfo = codegen.script->member_indices[var_name];1032member_property_setter_function = minfo.setter;1033member_property_has_setter = member_property_setter_function != StringName();1034member_property_is_in_setter = member_property_has_setter && member_property_setter_function == codegen.function_name;1035target_member_property.mode = GDScriptCodeGenerator::Address::MEMBER;1036target_member_property.address = minfo.index;1037target_member_property.type = minfo.data_type;1038} else {1039// Try static variables.1040GDScript *scr = codegen.script;1041while (scr) {1042if (scr->static_variables_indices.has(var_name)) {1043is_member_property = true;1044is_static = true;1045const GDScript::MemberInfo &minfo = scr->static_variables_indices[var_name];1046member_property_setter_function = minfo.setter;1047member_property_has_setter = member_property_setter_function != StringName();1048member_property_is_in_setter = member_property_has_setter && member_property_setter_function == codegen.function_name;1049static_var_class = codegen.add_constant(scr);1050static_var_index = minfo.index;1051static_var_data_type = minfo.data_type;1052break;1053}1054scr = scr->base.ptr();1055}1056}1057}1058}1059break;1060}1061n = static_cast<const GDScriptParser::SubscriptNode *>(n->base);1062}1063}10641065/* Chain of gets */10661067// Get at (potential) root stack pos, so it can be returned.1068GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, chain.back()->get()->base);1069const bool base_known_type = base.type.has_type();1070const bool base_is_shared = Variant::is_type_shared(base.type.builtin_type);10711072if (r_error) {1073return GDScriptCodeGenerator::Address();1074}10751076GDScriptCodeGenerator::Address prev_base = base;10771078// In case the base has a setter, don't use the address directly, as we want to call that setter.1079// So use a temp value instead and call the setter at the end.1080GDScriptCodeGenerator::Address base_temp;1081if ((!base_known_type || !base_is_shared) && base.mode == GDScriptCodeGenerator::Address::MEMBER && member_property_has_setter && !member_property_is_in_setter) {1082base_temp = codegen.add_temporary(base.type);1083gen->write_assign(base_temp, base);1084prev_base = base_temp;1085}10861087struct ChainInfo {1088bool is_named = false;1089GDScriptCodeGenerator::Address base;1090GDScriptCodeGenerator::Address key;1091StringName name;1092};10931094List<ChainInfo> set_chain;10951096for (List<const GDScriptParser::SubscriptNode *>::Element *E = chain.back(); E; E = E->prev()) {1097if (E == chain.front()) {1098// Skip the main subscript, since we'll assign to that.1099break;1100}1101const GDScriptParser::SubscriptNode *subscript_elem = E->get();1102GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript_elem->get_datatype(), codegen.script));1103GDScriptCodeGenerator::Address key;1104StringName name;11051106if (subscript_elem->is_attribute) {1107name = subscript_elem->attribute->name;1108gen->write_get_named(value, name, prev_base);1109} else {1110key = _parse_expression(codegen, r_error, subscript_elem->index);1111if (r_error) {1112return GDScriptCodeGenerator::Address();1113}1114gen->write_get(value, key, prev_base);1115}11161117// Store base and key for setting it back later.1118set_chain.push_front({ subscript_elem->is_attribute, prev_base, key, name }); // Push to front to invert the list.1119prev_base = value;1120}11211122// Get value to assign.1123GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value);1124if (r_error) {1125return GDScriptCodeGenerator::Address();1126}1127// Get the key if needed.1128GDScriptCodeGenerator::Address key;1129StringName name;1130if (subscript->is_attribute) {1131name = subscript->attribute->name;1132} else {1133key = _parse_expression(codegen, r_error, subscript->index);1134if (r_error) {1135return GDScriptCodeGenerator::Address();1136}1137}11381139// Perform operator if any.1140if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {1141GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script));1142GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype(), codegen.script));1143if (subscript->is_attribute) {1144gen->write_get_named(value, name, prev_base);1145} else {1146gen->write_get(value, key, prev_base);1147}1148gen->write_binary_operator(op_result, assignment->variant_op, value, assigned);1149gen->pop_temporary();1150if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1151gen->pop_temporary();1152}1153assigned = op_result;1154}11551156// Perform assignment.1157if (subscript->is_attribute) {1158gen->write_set_named(prev_base, name, assigned);1159} else {1160gen->write_set(prev_base, key, assigned);1161}1162if (key.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1163gen->pop_temporary();1164}1165if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1166gen->pop_temporary();1167}11681169assigned = prev_base;11701171// Set back the values into their bases.1172for (const ChainInfo &info : set_chain) {1173bool known_type = assigned.type.has_type();1174bool is_shared = Variant::is_type_shared(assigned.type.builtin_type);11751176if (!known_type || !is_shared) {1177if (!known_type) {1178// Jump shared values since they are already updated in-place.1179gen->write_jump_if_shared(assigned);1180}1181if (!info.is_named) {1182gen->write_set(info.base, info.key, assigned);1183} else {1184gen->write_set_named(info.base, info.name, assigned);1185}1186if (!known_type) {1187gen->write_end_jump_if_shared();1188}1189}1190if (!info.is_named && info.key.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1191gen->pop_temporary();1192}1193if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1194gen->pop_temporary();1195}1196assigned = info.base;1197}11981199bool known_type = assigned.type.has_type();1200bool is_shared = Variant::is_type_shared(assigned.type.builtin_type);12011202if (!known_type || !is_shared) {1203// If this is a class member property, also assign to it.1204// This allow things like: position.x += 2.01205if (assign_class_member_property != StringName()) {1206if (!known_type) {1207gen->write_jump_if_shared(assigned);1208}1209gen->write_set_member(assigned, assign_class_member_property);1210if (!known_type) {1211gen->write_end_jump_if_shared();1212}1213} else if (is_member_property) {1214// Same as above but for script members.1215if (!known_type) {1216gen->write_jump_if_shared(assigned);1217}1218if (member_property_has_setter && !member_property_is_in_setter) {1219Vector<GDScriptCodeGenerator::Address> args;1220args.push_back(assigned);1221GDScriptCodeGenerator::Address call_base = is_static ? GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::CLASS) : GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF);1222gen->write_call(GDScriptCodeGenerator::Address(), call_base, member_property_setter_function, args);1223} else if (is_static) {1224GDScriptCodeGenerator::Address temp = codegen.add_temporary(static_var_data_type);1225gen->write_assign(temp, assigned);1226gen->write_set_static_variable(temp, static_var_class, static_var_index);1227gen->pop_temporary();1228} else {1229gen->write_assign(target_member_property, assigned);1230}1231if (!known_type) {1232gen->write_end_jump_if_shared();1233}1234}1235} else if (base_temp.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1236if (!base_known_type) {1237gen->write_jump_if_shared(base);1238}1239// Save the temp value back to the base by calling its setter.1240gen->write_call(GDScriptCodeGenerator::Address(), base, member_property_setter_function, { assigned });1241if (!base_known_type) {1242gen->write_end_jump_if_shared();1243}1244}12451246if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1247gen->pop_temporary();1248}1249} else if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name)) {1250// Assignment to member property.1251GDScriptCodeGenerator::Address assigned_value = _parse_expression(codegen, r_error, assignment->assigned_value);1252if (r_error) {1253return GDScriptCodeGenerator::Address();1254}12551256GDScriptCodeGenerator::Address to_assign = assigned_value;1257bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE;12581259StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name;12601261if (has_operation) {1262GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script));1263GDScriptCodeGenerator::Address member = codegen.add_temporary(_gdtype_from_datatype(assignment->assignee->get_datatype(), codegen.script));1264gen->write_get_member(member, name);1265gen->write_binary_operator(op_result, assignment->variant_op, member, assigned_value);1266gen->pop_temporary(); // Pop member temp.1267to_assign = op_result;1268}12691270gen->write_set_member(to_assign, name);12711272if (to_assign.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1273gen->pop_temporary(); // Pop the assigned expression or the temp result if it has operation.1274}1275if (has_operation && assigned_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1276gen->pop_temporary(); // Pop the assigned expression if not done before.1277}1278} else {1279// Regular assignment.1280if (assignment->assignee->type != GDScriptParser::Node::IDENTIFIER) {1281_set_error("Compiler bug (please report): Expected the assignee to be an identifier here.", assignment->assignee);1282r_error = ERR_COMPILATION_FAILED;1283return GDScriptCodeGenerator::Address();1284}1285GDScriptCodeGenerator::Address member;1286bool is_member = false;1287bool has_setter = false;1288bool is_in_setter = false;1289bool is_static = false;1290GDScriptCodeGenerator::Address static_var_class;1291int static_var_index = 0;1292GDScriptDataType static_var_data_type;1293StringName var_name;1294StringName setter_function;1295var_name = static_cast<const GDScriptParser::IdentifierNode *>(assignment->assignee)->name;1296if (!_is_local_or_parameter(codegen, var_name)) {1297if (codegen.script->member_indices.has(var_name)) {1298is_member = true;1299is_static = false;1300GDScript::MemberInfo &minfo = codegen.script->member_indices[var_name];1301setter_function = minfo.setter;1302has_setter = setter_function != StringName();1303is_in_setter = has_setter && setter_function == codegen.function_name;1304member.mode = GDScriptCodeGenerator::Address::MEMBER;1305member.address = minfo.index;1306member.type = minfo.data_type;1307} else {1308// Try static variables.1309GDScript *scr = codegen.script;1310while (scr) {1311if (scr->static_variables_indices.has(var_name)) {1312is_member = true;1313is_static = true;1314GDScript::MemberInfo &minfo = scr->static_variables_indices[var_name];1315setter_function = minfo.setter;1316has_setter = setter_function != StringName();1317is_in_setter = has_setter && setter_function == codegen.function_name;1318static_var_class = codegen.add_constant(scr);1319static_var_index = minfo.index;1320static_var_data_type = minfo.data_type;1321break;1322}1323scr = scr->base.ptr();1324}1325}1326}13271328GDScriptCodeGenerator::Address target;1329if (is_member) {1330target = member; // _parse_expression could call its getter, but we want to know the actual address1331} else {1332target = _parse_expression(codegen, r_error, assignment->assignee);1333if (r_error) {1334return GDScriptCodeGenerator::Address();1335}1336}13371338GDScriptCodeGenerator::Address assigned_value = _parse_expression(codegen, r_error, assignment->assigned_value);1339if (r_error) {1340return GDScriptCodeGenerator::Address();1341}13421343GDScriptCodeGenerator::Address to_assign;1344bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE;1345if (has_operation) {1346// Perform operation.1347GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script));1348GDScriptCodeGenerator::Address og_value = _parse_expression(codegen, r_error, assignment->assignee);1349gen->write_binary_operator(op_result, assignment->variant_op, og_value, assigned_value);1350to_assign = op_result;13511352if (og_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1353gen->pop_temporary();1354}1355} else {1356to_assign = assigned_value;1357}13581359if (has_setter && !is_in_setter) {1360// Call setter.1361Vector<GDScriptCodeGenerator::Address> args;1362args.push_back(to_assign);1363GDScriptCodeGenerator::Address call_base = is_static ? GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::CLASS) : GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF);1364gen->write_call(GDScriptCodeGenerator::Address(), call_base, setter_function, args);1365} else if (is_static) {1366GDScriptCodeGenerator::Address temp = codegen.add_temporary(static_var_data_type);1367if (assignment->use_conversion_assign) {1368gen->write_assign_with_conversion(temp, to_assign);1369} else {1370gen->write_assign(temp, to_assign);1371}1372gen->write_set_static_variable(temp, static_var_class, static_var_index);1373gen->pop_temporary();1374} else {1375// Just assign.1376if (assignment->use_conversion_assign) {1377gen->write_assign_with_conversion(target, to_assign);1378} else {1379gen->write_assign(target, to_assign);1380}1381}13821383if (to_assign.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1384gen->pop_temporary(); // Pop assigned value or temp operation result.1385}1386if (has_operation && assigned_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1387gen->pop_temporary(); // Pop assigned value if not done before.1388}1389if (target.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1390gen->pop_temporary(); // Pop the target to assignment.1391}1392}1393return GDScriptCodeGenerator::Address(); // Assignment does not return a value.1394} break;1395case GDScriptParser::Node::LAMBDA: {1396const GDScriptParser::LambdaNode *lambda = static_cast<const GDScriptParser::LambdaNode *>(p_expression);1397GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(lambda->get_datatype(), codegen.script));13981399Vector<GDScriptCodeGenerator::Address> captures;1400captures.resize(lambda->captures.size());1401for (int i = 0; i < lambda->captures.size(); i++) {1402captures.write[i] = _parse_expression(codegen, r_error, lambda->captures[i]);1403if (r_error) {1404return GDScriptCodeGenerator::Address();1405}1406}14071408GDScriptFunction *function = _parse_function(r_error, codegen.script, codegen.class_node, lambda->function, false, true);1409if (r_error) {1410return GDScriptCodeGenerator::Address();1411}14121413codegen.script->lambda_info.insert(function, { (int)lambda->captures.size(), lambda->use_self });1414gen->write_lambda(result, function, captures, lambda->use_self);14151416for (int i = 0; i < captures.size(); i++) {1417if (captures[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {1418gen->pop_temporary();1419}1420}14211422return result;1423} break;1424default: {1425_set_error("Compiler bug (please report): Unexpected node in parse tree while parsing expression.", p_expression); // Unreachable code.1426r_error = ERR_COMPILATION_FAILED;1427return GDScriptCodeGenerator::Address();1428} break;1429}1430}14311432GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &codegen, Error &r_error, const GDScriptParser::PatternNode *p_pattern, const GDScriptCodeGenerator::Address &p_value_addr, const GDScriptCodeGenerator::Address &p_type_addr, const GDScriptCodeGenerator::Address &p_previous_test, bool p_is_first, bool p_is_nested) {1433switch (p_pattern->pattern_type) {1434case GDScriptParser::PatternNode::PT_LITERAL: {1435if (p_is_nested) {1436codegen.generator->write_and_left_operand(p_previous_test);1437} else if (!p_is_first) {1438codegen.generator->write_or_left_operand(p_previous_test);1439}14401441// Get literal type into constant map.1442Variant::Type literal_type = p_pattern->literal->value.get_type();1443GDScriptCodeGenerator::Address literal_type_addr = codegen.add_constant(literal_type);14441445// Equality is always a boolean.1446GDScriptDataType equality_type;1447equality_type.kind = GDScriptDataType::BUILTIN;1448equality_type.builtin_type = Variant::BOOL;14491450// Check type equality.1451GDScriptCodeGenerator::Address type_equality_addr = codegen.add_temporary(equality_type);1452codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr);14531454if (literal_type == Variant::STRING) {1455GDScriptCodeGenerator::Address type_stringname_addr = codegen.add_constant(Variant::STRING_NAME);14561457// Check StringName <-> String type equality.1458GDScriptCodeGenerator::Address tmp_comp_addr = codegen.add_temporary(equality_type);14591460codegen.generator->write_binary_operator(tmp_comp_addr, Variant::OP_EQUAL, p_type_addr, type_stringname_addr);1461codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_OR, type_equality_addr, tmp_comp_addr);14621463codegen.generator->pop_temporary(); // Remove tmp_comp_addr from stack.1464} else if (literal_type == Variant::STRING_NAME) {1465GDScriptCodeGenerator::Address type_string_addr = codegen.add_constant(Variant::STRING);14661467// Check String <-> StringName type equality.1468GDScriptCodeGenerator::Address tmp_comp_addr = codegen.add_temporary(equality_type);14691470codegen.generator->write_binary_operator(tmp_comp_addr, Variant::OP_EQUAL, p_type_addr, type_string_addr);1471codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_OR, type_equality_addr, tmp_comp_addr);14721473codegen.generator->pop_temporary(); // Remove tmp_comp_addr from stack.1474}14751476codegen.generator->write_and_left_operand(type_equality_addr);14771478// Get literal.1479GDScriptCodeGenerator::Address literal_addr = _parse_expression(codegen, r_error, p_pattern->literal);1480if (r_error) {1481return GDScriptCodeGenerator::Address();1482}14831484// Check value equality.1485GDScriptCodeGenerator::Address equality_addr = codegen.add_temporary(equality_type);1486codegen.generator->write_binary_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr);1487codegen.generator->write_and_right_operand(equality_addr);14881489// AND both together (reuse temporary location).1490codegen.generator->write_end_and(type_equality_addr);14911492codegen.generator->pop_temporary(); // Remove equality_addr from stack.14931494if (literal_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1495codegen.generator->pop_temporary();1496}14971498// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1499if (p_is_nested) {1500// Use the previous value as target, since we only need one temporary variable.1501codegen.generator->write_and_right_operand(type_equality_addr);1502codegen.generator->write_end_and(p_previous_test);1503} else if (!p_is_first) {1504// Use the previous value as target, since we only need one temporary variable.1505codegen.generator->write_or_right_operand(type_equality_addr);1506codegen.generator->write_end_or(p_previous_test);1507} else {1508// Just assign this value to the accumulator temporary.1509codegen.generator->write_assign(p_previous_test, type_equality_addr);1510}1511codegen.generator->pop_temporary(); // Remove type_equality_addr.15121513return p_previous_test;1514} break;1515case GDScriptParser::PatternNode::PT_EXPRESSION: {1516if (p_is_nested) {1517codegen.generator->write_and_left_operand(p_previous_test);1518} else if (!p_is_first) {1519codegen.generator->write_or_left_operand(p_previous_test);1520}15211522GDScriptCodeGenerator::Address type_string_addr = codegen.add_constant(Variant::STRING);1523GDScriptCodeGenerator::Address type_stringname_addr = codegen.add_constant(Variant::STRING_NAME);15241525// Equality is always a boolean.1526GDScriptDataType equality_type;1527equality_type.kind = GDScriptDataType::BUILTIN;1528equality_type.builtin_type = Variant::BOOL;15291530// Create the result temps first since it's the last to go away.1531GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(equality_type);1532GDScriptCodeGenerator::Address equality_test_addr = codegen.add_temporary(equality_type);1533GDScriptCodeGenerator::Address stringy_comp_addr = codegen.add_temporary(equality_type);1534GDScriptCodeGenerator::Address stringy_comp_addr_2 = codegen.add_temporary(equality_type);1535GDScriptCodeGenerator::Address expr_type_addr = codegen.add_temporary();15361537// Evaluate expression.1538GDScriptCodeGenerator::Address expr_addr;1539expr_addr = _parse_expression(codegen, r_error, p_pattern->expression);1540if (r_error) {1541return GDScriptCodeGenerator::Address();1542}15431544// Evaluate expression type.1545Vector<GDScriptCodeGenerator::Address> typeof_args;1546typeof_args.push_back(expr_addr);1547codegen.generator->write_call_utility(expr_type_addr, "typeof", typeof_args);15481549// Check type equality.1550codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, expr_type_addr);15511552// Check for String <-> StringName comparison.1553codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_EQUAL, p_type_addr, type_string_addr);1554codegen.generator->write_binary_operator(stringy_comp_addr_2, Variant::OP_EQUAL, expr_type_addr, type_stringname_addr);1555codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_AND, stringy_comp_addr, stringy_comp_addr_2);1556codegen.generator->write_binary_operator(result_addr, Variant::OP_OR, result_addr, stringy_comp_addr);15571558// Check for StringName <-> String comparison.1559codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_EQUAL, p_type_addr, type_stringname_addr);1560codegen.generator->write_binary_operator(stringy_comp_addr_2, Variant::OP_EQUAL, expr_type_addr, type_string_addr);1561codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_AND, stringy_comp_addr, stringy_comp_addr_2);1562codegen.generator->write_binary_operator(result_addr, Variant::OP_OR, result_addr, stringy_comp_addr);15631564codegen.generator->pop_temporary(); // Remove expr_type_addr from stack.1565codegen.generator->pop_temporary(); // Remove stringy_comp_addr_2 from stack.1566codegen.generator->pop_temporary(); // Remove stringy_comp_addr from stack.15671568codegen.generator->write_and_left_operand(result_addr);15691570// Check value equality.1571codegen.generator->write_binary_operator(equality_test_addr, Variant::OP_EQUAL, p_value_addr, expr_addr);1572codegen.generator->write_and_right_operand(equality_test_addr);15731574// AND both type and value equality.1575codegen.generator->write_end_and(result_addr);15761577// We don't need the expression temporary anymore.1578if (expr_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1579codegen.generator->pop_temporary();1580}1581codegen.generator->pop_temporary(); // Remove equality_test_addr from stack.15821583// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1584if (p_is_nested) {1585// Use the previous value as target, since we only need one temporary variable.1586codegen.generator->write_and_right_operand(result_addr);1587codegen.generator->write_end_and(p_previous_test);1588} else if (!p_is_first) {1589// Use the previous value as target, since we only need one temporary variable.1590codegen.generator->write_or_right_operand(result_addr);1591codegen.generator->write_end_or(p_previous_test);1592} else {1593// Just assign this value to the accumulator temporary.1594codegen.generator->write_assign(p_previous_test, result_addr);1595}1596codegen.generator->pop_temporary(); // Remove temp result addr.15971598return p_previous_test;1599} break;1600case GDScriptParser::PatternNode::PT_ARRAY: {1601if (p_is_nested) {1602codegen.generator->write_and_left_operand(p_previous_test);1603} else if (!p_is_first) {1604codegen.generator->write_or_left_operand(p_previous_test);1605}1606// Get array type into constant map.1607GDScriptCodeGenerator::Address array_type_addr = codegen.add_constant((int)Variant::ARRAY);16081609// Equality is always a boolean.1610GDScriptDataType temp_type;1611temp_type.kind = GDScriptDataType::BUILTIN;1612temp_type.builtin_type = Variant::BOOL;16131614// Check type equality.1615GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);1616codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr);1617codegen.generator->write_and_left_operand(result_addr);16181619// Store pattern length in constant map.1620GDScriptCodeGenerator::Address array_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->array.size() - 1 : p_pattern->array.size());16211622// Get value length.1623temp_type.builtin_type = Variant::INT;1624GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);1625Vector<GDScriptCodeGenerator::Address> len_args;1626len_args.push_back(p_value_addr);1627codegen.generator->write_call_gdscript_utility(value_length_addr, "len", len_args);16281629// Test length compatibility.1630temp_type.builtin_type = Variant::BOOL;1631GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);1632codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr);1633codegen.generator->write_and_right_operand(length_compat_addr);16341635// AND type and length check.1636codegen.generator->write_end_and(result_addr);16371638// Remove length temporaries.1639codegen.generator->pop_temporary();1640codegen.generator->pop_temporary();16411642// Create temporaries outside the loop so they can be reused.1643GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();1644GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();16451646// Evaluate element by element.1647for (int i = 0; i < p_pattern->array.size(); i++) {1648if (p_pattern->array[i]->pattern_type == GDScriptParser::PatternNode::PT_REST) {1649// Don't want to access an extra element of the user array.1650break;1651}16521653// Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).1654codegen.generator->write_and_left_operand(result_addr);16551656// Add index to constant map.1657GDScriptCodeGenerator::Address index_addr = codegen.add_constant(i);16581659// Get the actual element from the user-sent array.1660codegen.generator->write_get(element_addr, index_addr, p_value_addr);16611662// Also get type of element.1663Vector<GDScriptCodeGenerator::Address> typeof_args;1664typeof_args.push_back(element_addr);1665codegen.generator->write_call_utility(element_type_addr, "typeof", typeof_args);16661667// Try the pattern inside the element.1668result_addr = _parse_match_pattern(codegen, r_error, p_pattern->array[i], element_addr, element_type_addr, result_addr, false, true);1669if (r_error != OK) {1670return GDScriptCodeGenerator::Address();1671}16721673codegen.generator->write_and_right_operand(result_addr);1674codegen.generator->write_end_and(result_addr);1675}1676// Remove element temporaries.1677codegen.generator->pop_temporary();1678codegen.generator->pop_temporary();16791680// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1681if (p_is_nested) {1682// Use the previous value as target, since we only need one temporary variable.1683codegen.generator->write_and_right_operand(result_addr);1684codegen.generator->write_end_and(p_previous_test);1685} else if (!p_is_first) {1686// Use the previous value as target, since we only need one temporary variable.1687codegen.generator->write_or_right_operand(result_addr);1688codegen.generator->write_end_or(p_previous_test);1689} else {1690// Just assign this value to the accumulator temporary.1691codegen.generator->write_assign(p_previous_test, result_addr);1692}1693codegen.generator->pop_temporary(); // Remove temp result addr.16941695return p_previous_test;1696} break;1697case GDScriptParser::PatternNode::PT_DICTIONARY: {1698if (p_is_nested) {1699codegen.generator->write_and_left_operand(p_previous_test);1700} else if (!p_is_first) {1701codegen.generator->write_or_left_operand(p_previous_test);1702}1703// Get dictionary type into constant map.1704GDScriptCodeGenerator::Address dict_type_addr = codegen.add_constant((int)Variant::DICTIONARY);17051706// Equality is always a boolean.1707GDScriptDataType temp_type;1708temp_type.kind = GDScriptDataType::BUILTIN;1709temp_type.builtin_type = Variant::BOOL;17101711// Check type equality.1712GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);1713codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr);1714codegen.generator->write_and_left_operand(result_addr);17151716// Store pattern length in constant map.1717GDScriptCodeGenerator::Address dict_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());17181719// Get user's dictionary length.1720temp_type.builtin_type = Variant::INT;1721GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);1722Vector<GDScriptCodeGenerator::Address> func_args;1723func_args.push_back(p_value_addr);1724codegen.generator->write_call_gdscript_utility(value_length_addr, "len", func_args);17251726// Test length compatibility.1727temp_type.builtin_type = Variant::BOOL;1728GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);1729codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr);1730codegen.generator->write_and_right_operand(length_compat_addr);17311732// AND type and length check.1733codegen.generator->write_end_and(result_addr);17341735// Remove length temporaries.1736codegen.generator->pop_temporary();1737codegen.generator->pop_temporary();17381739// Create temporaries outside the loop so they can be reused.1740GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();1741GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();17421743// Evaluate element by element.1744for (int i = 0; i < p_pattern->dictionary.size(); i++) {1745const GDScriptParser::PatternNode::Pair &element = p_pattern->dictionary[i];1746if (element.value_pattern && element.value_pattern->pattern_type == GDScriptParser::PatternNode::PT_REST) {1747// Ignore rest pattern.1748break;1749}17501751// Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).1752codegen.generator->write_and_left_operand(result_addr);17531754// Get the pattern key.1755GDScriptCodeGenerator::Address pattern_key_addr = _parse_expression(codegen, r_error, element.key);1756if (r_error) {1757return GDScriptCodeGenerator::Address();1758}17591760// Check if pattern key exists in user's dictionary. This will be AND-ed with next result.1761func_args.clear();1762func_args.push_back(pattern_key_addr);1763codegen.generator->write_call(result_addr, p_value_addr, "has", func_args);17641765if (element.value_pattern != nullptr) {1766// Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).1767codegen.generator->write_and_left_operand(result_addr);17681769// Get actual value from user dictionary.1770codegen.generator->write_get(element_addr, pattern_key_addr, p_value_addr);17711772// Also get type of value.1773func_args.clear();1774func_args.push_back(element_addr);1775codegen.generator->write_call_utility(element_type_addr, "typeof", func_args);17761777// Try the pattern inside the value.1778result_addr = _parse_match_pattern(codegen, r_error, element.value_pattern, element_addr, element_type_addr, result_addr, false, true);1779if (r_error != OK) {1780return GDScriptCodeGenerator::Address();1781}1782codegen.generator->write_and_right_operand(result_addr);1783codegen.generator->write_end_and(result_addr);1784}17851786codegen.generator->write_and_right_operand(result_addr);1787codegen.generator->write_end_and(result_addr);17881789// Remove pattern key temporary.1790if (pattern_key_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1791codegen.generator->pop_temporary();1792}1793}17941795// Remove element temporaries.1796codegen.generator->pop_temporary();1797codegen.generator->pop_temporary();17981799// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1800if (p_is_nested) {1801// Use the previous value as target, since we only need one temporary variable.1802codegen.generator->write_and_right_operand(result_addr);1803codegen.generator->write_end_and(p_previous_test);1804} else if (!p_is_first) {1805// Use the previous value as target, since we only need one temporary variable.1806codegen.generator->write_or_right_operand(result_addr);1807codegen.generator->write_end_or(p_previous_test);1808} else {1809// Just assign this value to the accumulator temporary.1810codegen.generator->write_assign(p_previous_test, result_addr);1811}1812codegen.generator->pop_temporary(); // Remove temp result addr.18131814return p_previous_test;1815} break;1816case GDScriptParser::PatternNode::PT_REST:1817// Do nothing.1818return p_previous_test;1819break;1820case GDScriptParser::PatternNode::PT_BIND: {1821if (p_is_nested) {1822codegen.generator->write_and_left_operand(p_previous_test);1823} else if (!p_is_first) {1824codegen.generator->write_or_left_operand(p_previous_test);1825}1826// Get the bind address.1827GDScriptCodeGenerator::Address bind = codegen.locals[p_pattern->bind->name];18281829// Assign value to bound variable.1830codegen.generator->write_assign(bind, p_value_addr);1831}1832[[fallthrough]]; // Act like matching anything too.1833case GDScriptParser::PatternNode::PT_WILDCARD:1834// If this is a fall through we don't want to do this again.1835if (p_pattern->pattern_type != GDScriptParser::PatternNode::PT_BIND) {1836if (p_is_nested) {1837codegen.generator->write_and_left_operand(p_previous_test);1838} else if (!p_is_first) {1839codegen.generator->write_or_left_operand(p_previous_test);1840}1841}1842// This matches anything so just do the same as `if(true)`.1843// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1844if (p_is_nested) {1845// Use the operator with the `true` constant so it works as always matching.1846GDScriptCodeGenerator::Address constant = codegen.add_constant(true);1847codegen.generator->write_and_right_operand(constant);1848codegen.generator->write_end_and(p_previous_test);1849} else if (!p_is_first) {1850// Use the operator with the `true` constant so it works as always matching.1851GDScriptCodeGenerator::Address constant = codegen.add_constant(true);1852codegen.generator->write_or_right_operand(constant);1853codegen.generator->write_end_or(p_previous_test);1854} else {1855// Just assign this value to the accumulator temporary.1856codegen.generator->write_assign_true(p_previous_test);1857}1858return p_previous_test;1859}18601861_set_error("Compiler bug (please report): Reaching the end of pattern compilation without matching a pattern.", p_pattern);1862r_error = ERR_COMPILATION_FAILED;1863return p_previous_test;1864}18651866List<GDScriptCodeGenerator::Address> GDScriptCompiler::_add_block_locals(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block) {1867List<GDScriptCodeGenerator::Address> addresses;1868for (int i = 0; i < p_block->locals.size(); i++) {1869if (p_block->locals[i].type == GDScriptParser::SuiteNode::Local::PARAMETER || p_block->locals[i].type == GDScriptParser::SuiteNode::Local::FOR_VARIABLE) {1870// Parameters are added directly from function and loop variables are declared explicitly.1871continue;1872}1873addresses.push_back(codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype(), codegen.script)));1874}1875return addresses;1876}18771878// Avoid keeping in the stack long-lived references to objects, which may prevent `RefCounted` objects from being freed.1879void GDScriptCompiler::_clear_block_locals(CodeGen &codegen, const List<GDScriptCodeGenerator::Address> &p_locals) {1880for (const GDScriptCodeGenerator::Address &local : p_locals) {1881if (local.type.can_contain_object()) {1882codegen.generator->clear_address(local);1883}1884}1885}18861887Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals, bool p_clear_locals) {1888Error err = OK;1889GDScriptCodeGenerator *gen = codegen.generator;1890List<GDScriptCodeGenerator::Address> block_locals;18911892gen->clear_temporaries();1893codegen.start_block();18941895if (p_add_locals) {1896block_locals = _add_block_locals(codegen, p_block);1897}18981899for (int i = 0; i < p_block->statements.size(); i++) {1900const GDScriptParser::Node *s = p_block->statements[i];19011902gen->write_newline(s->start_line);19031904switch (s->type) {1905case GDScriptParser::Node::MATCH: {1906const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(s);19071908codegen.start_block(); // Add an extra block, since @special locals belong to the match scope.19091910// Evaluate the match expression.1911GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype(), codegen.script));1912GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, err, match->test);1913if (err) {1914return err;1915}19161917// Assign to local.1918// TODO: This can be improved by passing the target to parse_expression().1919gen->write_assign(value, value_expr);19201921if (value_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1922codegen.generator->pop_temporary();1923}19241925// Then, let's save the type of the value in the stack too, so we can reuse for later comparisons.1926GDScriptDataType typeof_type;1927typeof_type.kind = GDScriptDataType::BUILTIN;1928typeof_type.builtin_type = Variant::INT;1929GDScriptCodeGenerator::Address type = codegen.add_local("@match_type", typeof_type);19301931Vector<GDScriptCodeGenerator::Address> typeof_args;1932typeof_args.push_back(value);1933gen->write_call_utility(type, "typeof", typeof_args);19341935// Now we can actually start testing.1936// For each branch.1937for (int j = 0; j < match->branches.size(); j++) {1938if (j > 0) {1939// Use `else` to not check the next branch after matching.1940gen->write_else();1941}19421943const GDScriptParser::MatchBranchNode *branch = match->branches[j];19441945codegen.start_block(); // Add an extra block, since binds belong to the match branch scope.19461947// Add locals in block before patterns, so temporaries don't use the stack address for binds.1948List<GDScriptCodeGenerator::Address> branch_locals = _add_block_locals(codegen, branch->block);19491950gen->write_newline(branch->start_line);19511952// For each pattern in branch.1953GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary();1954for (int k = 0; k < branch->patterns.size(); k++) {1955pattern_result = _parse_match_pattern(codegen, err, branch->patterns[k], value, type, pattern_result, k == 0, false);1956if (err != OK) {1957return err;1958}1959}19601961// If there's a guard, check its condition too.1962if (branch->guard_body != nullptr) {1963// Do this first so the guard does not run unless the pattern matched.1964gen->write_and_left_operand(pattern_result);19651966// Don't actually use the block for the guard.1967// The binds are already in the locals and we don't want to clear the result of the guard condition before we check the actual match.1968GDScriptCodeGenerator::Address guard_result = _parse_expression(codegen, err, static_cast<GDScriptParser::ExpressionNode *>(branch->guard_body->statements[0]));1969if (err) {1970return err;1971}19721973gen->write_and_right_operand(guard_result);1974gen->write_end_and(pattern_result);19751976if (guard_result.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1977codegen.generator->pop_temporary();1978}1979}19801981// Check if pattern did match.1982gen->write_if(pattern_result);19831984// Remove the result from stack.1985gen->pop_temporary();19861987// Parse the branch block.1988err = _parse_block(codegen, branch->block, false); // Don't add locals again.1989if (err) {1990return err;1991}19921993_clear_block_locals(codegen, branch_locals);19941995codegen.end_block(); // Get out of extra block for binds.1996}19971998// End all nested `if`s.1999for (int j = 0; j < match->branches.size(); j++) {2000gen->write_endif();2001}20022003codegen.end_block(); // Get out of extra block for match's @special locals.2004} break;2005case GDScriptParser::Node::IF: {2006const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s);2007GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, if_n->condition);2008if (err) {2009return err;2010}20112012gen->write_if(condition);20132014if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2015codegen.generator->pop_temporary();2016}20172018err = _parse_block(codegen, if_n->true_block);2019if (err) {2020return err;2021}20222023if (if_n->false_block) {2024gen->write_else();20252026err = _parse_block(codegen, if_n->false_block);2027if (err) {2028return err;2029}2030}20312032gen->write_endif();2033} break;2034case GDScriptParser::Node::FOR: {2035const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s);20362037// Add an extra block, since the iterator and @special locals belong to the loop scope.2038// Also we use custom logic to clear block locals.2039codegen.start_block();20402041GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype(), codegen.script));20422043// Optimize `range()` call to not allocate an array.2044GDScriptParser::CallNode *range_call = nullptr;2045if (for_n->list && for_n->list->type == GDScriptParser::Node::CALL) {2046GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(for_n->list);2047if (call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {2048if (static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name == "range") {2049range_call = call;2050}2051}2052}20532054gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype(), codegen.script), range_call != nullptr);20552056if (range_call != nullptr) {2057Vector<GDScriptCodeGenerator::Address> args;2058args.resize(range_call->arguments.size());20592060for (int j = 0; j < args.size(); j++) {2061args.write[j] = _parse_expression(codegen, err, range_call->arguments[j]);2062if (err) {2063return err;2064}2065}20662067switch (args.size()) {2068case 1:2069gen->write_for_range_assignment(codegen.add_constant(0), args[0], codegen.add_constant(1));2070break;2071case 2:2072gen->write_for_range_assignment(args[0], args[1], codegen.add_constant(1));2073break;2074case 3:2075gen->write_for_range_assignment(args[0], args[1], args[2]);2076break;2077default:2078_set_error(R"*(Analyzer bug: Wrong "range()" argument count.)*", range_call);2079return ERR_BUG;2080}20812082for (int j = 0; j < args.size(); j++) {2083if (args[j].mode == GDScriptCodeGenerator::Address::TEMPORARY) {2084codegen.generator->pop_temporary();2085}2086}2087} else {2088GDScriptCodeGenerator::Address list = _parse_expression(codegen, err, for_n->list);2089if (err) {2090return err;2091}20922093gen->write_for_list_assignment(list);20942095if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2096codegen.generator->pop_temporary();2097}2098}20992100gen->write_for(iterator, for_n->use_conversion_assign, range_call != nullptr);21012102// Loop variables must be cleared even when `break`/`continue` is used.2103List<GDScriptCodeGenerator::Address> loop_locals = _add_block_locals(codegen, for_n->loop);21042105//_clear_block_locals(codegen, loop_locals); // Inside loop, before block - for `continue`. // TODO21062107err = _parse_block(codegen, for_n->loop, false); // Don't add locals again.2108if (err) {2109return err;2110}21112112gen->write_endfor(range_call != nullptr);21132114_clear_block_locals(codegen, loop_locals); // Outside loop, after block - for `break` and normal exit.21152116codegen.end_block(); // Get out of extra block for loop iterator, @special locals, and custom locals clearing.2117} break;2118case GDScriptParser::Node::WHILE: {2119const GDScriptParser::WhileNode *while_n = static_cast<const GDScriptParser::WhileNode *>(s);21202121codegen.start_block(); // Add an extra block, since we use custom logic to clear block locals.21222123gen->start_while_condition();21242125GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, while_n->condition);2126if (err) {2127return err;2128}21292130gen->write_while(condition);21312132if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2133codegen.generator->pop_temporary();2134}21352136// Loop variables must be cleared even when `break`/`continue` is used.2137List<GDScriptCodeGenerator::Address> loop_locals = _add_block_locals(codegen, while_n->loop);21382139//_clear_block_locals(codegen, loop_locals); // Inside loop, before block - for `continue`. // TODO21402141err = _parse_block(codegen, while_n->loop, false); // Don't add locals again.2142if (err) {2143return err;2144}21452146gen->write_endwhile();21472148_clear_block_locals(codegen, loop_locals); // Outside loop, after block - for `break` and normal exit.21492150codegen.end_block(); // Get out of extra block for custom locals clearing.2151} break;2152case GDScriptParser::Node::BREAK: {2153gen->write_break();2154} break;2155case GDScriptParser::Node::CONTINUE: {2156gen->write_continue();2157} break;2158case GDScriptParser::Node::RETURN: {2159const GDScriptParser::ReturnNode *return_n = static_cast<const GDScriptParser::ReturnNode *>(s);21602161GDScriptCodeGenerator::Address return_value;21622163if (return_n->return_value != nullptr) {2164return_value = _parse_expression(codegen, err, return_n->return_value);2165if (err) {2166return err;2167}2168}21692170if (return_n->void_return) {2171// Always return "null", even if the expression is a call to a void function.2172gen->write_return(codegen.add_constant(Variant()));2173} else {2174gen->write_return(return_value);2175}2176if (return_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2177codegen.generator->pop_temporary();2178}2179} break;2180case GDScriptParser::Node::ASSERT: {2181#ifdef DEBUG_ENABLED2182const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s);21832184GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, as->condition);2185if (err) {2186return err;2187}21882189GDScriptCodeGenerator::Address message;21902191if (as->message) {2192message = _parse_expression(codegen, err, as->message);2193if (err) {2194return err;2195}2196}2197gen->write_assert(condition, message);21982199if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2200codegen.generator->pop_temporary();2201}2202if (message.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2203codegen.generator->pop_temporary();2204}2205#endif2206} break;2207case GDScriptParser::Node::BREAKPOINT: {2208#ifdef DEBUG_ENABLED2209gen->write_breakpoint();2210#endif2211} break;2212case GDScriptParser::Node::VARIABLE: {2213const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s);2214// Should be already in stack when the block began.2215GDScriptCodeGenerator::Address local = codegen.locals[lv->identifier->name];2216GDScriptDataType local_type = _gdtype_from_datatype(lv->get_datatype(), codegen.script);22172218bool initialized = false;2219if (lv->initializer != nullptr) {2220GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, err, lv->initializer);2221if (err) {2222return err;2223}2224if (lv->use_conversion_assign) {2225gen->write_assign_with_conversion(local, src_address);2226} else {2227gen->write_assign(local, src_address);2228}2229if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2230codegen.generator->pop_temporary();2231}2232initialized = true;2233} else if (local_type.kind == GDScriptDataType::BUILTIN || codegen.generator->is_local_dirty(local)) {2234// Initialize with default for the type. Built-in types must always be cleared (they cannot be `null`).2235// Objects and untyped variables are assigned to `null` only if the stack address has been reused and not cleared.2236codegen.generator->clear_address(local);2237initialized = true;2238}22392240// Don't check `is_local_dirty()` since the variable must be assigned to `null` **on each iteration**.2241if (!initialized && p_block->is_in_loop) {2242codegen.generator->clear_address(local);2243}2244} break;2245case GDScriptParser::Node::CONSTANT: {2246// Local constants.2247const GDScriptParser::ConstantNode *lc = static_cast<const GDScriptParser::ConstantNode *>(s);2248if (!lc->initializer->is_constant) {2249_set_error("Local constant must have a constant value as initializer.", lc->initializer);2250return ERR_PARSE_ERROR;2251}22522253codegen.add_local_constant(lc->identifier->name, lc->initializer->reduced_value);2254} break;2255case GDScriptParser::Node::PASS:2256// Nothing to do.2257break;2258default: {2259// Expression.2260if (s->is_expression()) {2261GDScriptCodeGenerator::Address expr = _parse_expression(codegen, err, static_cast<const GDScriptParser::ExpressionNode *>(s), true);2262if (err) {2263return err;2264}2265if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2266codegen.generator->pop_temporary();2267}2268} else {2269_set_error("Compiler bug (please report): unexpected node in parse tree while parsing statement.", s); // Unreachable code.2270return ERR_INVALID_DATA;2271}2272} break;2273}22742275gen->clear_temporaries();2276}22772278if (p_add_locals && p_clear_locals) {2279_clear_block_locals(codegen, block_locals);2280}22812282codegen.end_block();2283return OK;2284}22852286GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready, bool p_for_lambda) {2287r_error = OK;2288CodeGen codegen;2289codegen.generator = memnew(GDScriptByteCodeGenerator);22902291codegen.class_node = p_class;2292codegen.script = p_script;2293codegen.function_node = p_func;22942295StringName func_name;2296bool is_abstract = false;2297bool is_static = false;2298Variant rpc_config;2299GDScriptDataType return_type;2300return_type.kind = GDScriptDataType::BUILTIN;2301return_type.builtin_type = Variant::NIL;23022303if (p_func) {2304if (p_func->identifier) {2305func_name = p_func->identifier->name;2306} else {2307func_name = "<anonymous lambda>";2308}2309is_abstract = p_func->is_abstract;2310is_static = p_func->is_static;2311rpc_config = p_func->rpc_config;2312return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);2313} else {2314if (p_for_ready) {2315func_name = "@implicit_ready";2316} else {2317func_name = "@implicit_new";2318}2319}23202321MethodInfo method_info;23222323codegen.function_name = func_name;2324method_info.name = func_name;2325codegen.is_static = is_static;2326if (is_abstract) {2327method_info.flags |= METHOD_FLAG_VIRTUAL_REQUIRED;2328}2329if (is_static) {2330method_info.flags |= METHOD_FLAG_STATIC;2331}2332codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type);23332334int optional_parameters = 0;2335GDScriptCodeGenerator::Address vararg_addr;23362337if (p_func) {2338for (int i = 0; i < p_func->parameters.size(); i++) {2339const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];2340GDScriptDataType par_type = _gdtype_from_datatype(parameter->get_datatype(), p_script);2341uint32_t par_addr = codegen.generator->add_parameter(parameter->identifier->name, parameter->initializer != nullptr, par_type);2342codegen.parameters[parameter->identifier->name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::FUNCTION_PARAMETER, par_addr, par_type);23432344method_info.arguments.push_back(parameter->get_datatype().to_property_info(parameter->identifier->name));23452346if (parameter->initializer != nullptr) {2347optional_parameters++;2348}2349}23502351if (p_func->is_vararg()) {2352vararg_addr = codegen.add_local(p_func->rest_parameter->identifier->name, _gdtype_from_datatype(p_func->rest_parameter->get_datatype(), codegen.script));2353method_info.flags |= METHOD_FLAG_VARARG;2354}23552356method_info.default_arguments.append_array(p_func->default_arg_values);2357}23582359// Parse initializer if applies.2360bool is_implicit_initializer = !p_for_ready && !p_func && !p_for_lambda;2361bool is_initializer = p_func && !p_for_lambda && p_func->identifier->name == GDScriptLanguage::get_singleton()->strings._init;2362bool is_implicit_ready = !p_func && p_for_ready;23632364if (!p_for_lambda && is_implicit_initializer) {2365// Initialize the default values for typed variables before anything.2366// This avoids crashes if they are accessed with validated calls before being properly initialized.2367// It may happen with out-of-order access or with `@onready` variables.2368for (const GDScriptParser::ClassNode::Member &member : p_class->members) {2369if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {2370continue;2371}23722373const GDScriptParser::VariableNode *field = member.variable;2374if (field->is_static) {2375continue;2376}23772378GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2379if (field_type.has_type()) {2380codegen.generator->write_newline(field->start_line);23812382GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, field_type);23832384if (field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type(0)) {2385codegen.generator->write_construct_typed_array(dst_address, field_type.get_container_element_type(0), Vector<GDScriptCodeGenerator::Address>());2386} else if (field_type.builtin_type == Variant::DICTIONARY && field_type.has_container_element_types()) {2387codegen.generator->write_construct_typed_dictionary(dst_address, field_type.get_container_element_type_or_variant(0),2388field_type.get_container_element_type_or_variant(1), Vector<GDScriptCodeGenerator::Address>());2389} else if (field_type.kind == GDScriptDataType::BUILTIN) {2390codegen.generator->write_construct(dst_address, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());2391}2392// The `else` branch is for objects, in such case we leave it as `null`.2393}2394}2395}23962397if (!p_for_lambda && (is_implicit_initializer || is_implicit_ready)) {2398// Initialize class fields.2399for (int i = 0; i < p_class->members.size(); i++) {2400if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {2401continue;2402}2403const GDScriptParser::VariableNode *field = p_class->members[i].variable;2404if (field->is_static) {2405continue;2406}24072408if (field->onready != is_implicit_ready) {2409// Only initialize in `@implicit_ready()`.2410continue;2411}24122413if (field->initializer) {2414codegen.generator->write_newline(field->initializer->start_line);24152416GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true);2417if (r_error) {2418memdelete(codegen.generator);2419return nullptr;2420}24212422GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2423GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, field_type);24242425if (field->use_conversion_assign) {2426codegen.generator->write_assign_with_conversion(dst_address, src_address);2427} else {2428codegen.generator->write_assign(dst_address, src_address);2429}2430if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2431codegen.generator->pop_temporary();2432}2433}2434}2435}24362437// Parse default argument code if applies.2438if (p_func) {2439if (optional_parameters > 0) {2440codegen.generator->start_parameters();2441for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) {2442const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];2443GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, r_error, parameter->initializer);2444if (r_error) {2445memdelete(codegen.generator);2446return nullptr;2447}2448GDScriptCodeGenerator::Address dst_addr = codegen.parameters[parameter->identifier->name];2449codegen.generator->write_assign_default_parameter(dst_addr, src_addr, parameter->use_conversion_assign);2450if (src_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2451codegen.generator->pop_temporary();2452}2453}2454codegen.generator->end_parameters();2455}24562457// No need to reset locals at the end of the function, the stack will be cleared anyway.2458r_error = _parse_block(codegen, p_func->body, true, false);2459if (r_error) {2460memdelete(codegen.generator);2461return nullptr;2462}2463}24642465#ifdef DEBUG_ENABLED2466if (EngineDebugger::is_active()) {2467String signature;2468// Path.2469if (!p_script->get_script_path().is_empty()) {2470signature += p_script->get_script_path();2471}2472// Location.2473if (p_func) {2474signature += "::" + itos(p_func->body->start_line);2475} else {2476signature += "::0";2477}24782479// Function and class.24802481if (p_class->identifier) {2482signature += "::" + String(p_class->identifier->name) + "." + String(func_name);2483} else {2484signature += "::" + String(func_name);2485}24862487if (p_for_lambda) {2488signature += "(lambda)";2489}24902491codegen.generator->set_signature(signature);2492}2493#endif24942495if (p_func) {2496codegen.generator->set_initial_line(p_func->start_line);2497} else {2498codegen.generator->set_initial_line(0);2499}25002501GDScriptFunction *gd_function = codegen.generator->write_end();25022503if (is_initializer) {2504p_script->initializer = gd_function;2505} else if (is_implicit_initializer) {2506p_script->implicit_initializer = gd_function;2507} else if (is_implicit_ready) {2508p_script->implicit_ready = gd_function;2509}25102511if (p_func) {2512// If no `return` statement, then return type is `void`, not `Variant`.2513if (p_func->body->has_return) {2514gd_function->return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);2515method_info.return_val = p_func->get_datatype().to_property_info(String());2516} else {2517gd_function->return_type = GDScriptDataType();2518gd_function->return_type.kind = GDScriptDataType::BUILTIN;2519gd_function->return_type.builtin_type = Variant::NIL;2520}25212522if (p_func->is_vararg()) {2523gd_function->_vararg_index = vararg_addr.address;2524}2525}25262527gd_function->method_info = method_info;25282529if (!is_implicit_initializer && !is_implicit_ready && !p_for_lambda) {2530p_script->member_functions[func_name] = gd_function;2531}25322533memdelete(codegen.generator);25342535return gd_function;2536}25372538GDScriptFunction *GDScriptCompiler::_make_static_initializer(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class) {2539r_error = OK;2540CodeGen codegen;2541codegen.generator = memnew(GDScriptByteCodeGenerator);25422543codegen.class_node = p_class;2544codegen.script = p_script;25452546StringName func_name = SNAME("@static_initializer");2547bool is_static = true;2548Variant rpc_config;2549GDScriptDataType return_type;2550return_type.kind = GDScriptDataType::BUILTIN;2551return_type.builtin_type = Variant::NIL;25522553codegen.function_name = func_name;2554codegen.is_static = is_static;2555codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type);25562557// The static initializer is always called on the same class where the static variables are defined,2558// so the CLASS address (current class) can be used instead of `codegen.add_constant(p_script)`.2559GDScriptCodeGenerator::Address class_addr(GDScriptCodeGenerator::Address::CLASS);25602561// Initialize the default values for typed variables before anything.2562// This avoids crashes if they are accessed with validated calls before being properly initialized.2563// It may happen with out-of-order access or with `@onready` variables.2564for (const GDScriptParser::ClassNode::Member &member : p_class->members) {2565if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {2566continue;2567}25682569const GDScriptParser::VariableNode *field = member.variable;2570if (!field->is_static) {2571continue;2572}25732574GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2575if (field_type.has_type()) {2576codegen.generator->write_newline(field->start_line);25772578if (field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type(0)) {2579GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2580codegen.generator->write_construct_typed_array(temp, field_type.get_container_element_type(0), Vector<GDScriptCodeGenerator::Address>());2581codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2582codegen.generator->pop_temporary();2583} else if (field_type.builtin_type == Variant::DICTIONARY && field_type.has_container_element_types()) {2584GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2585codegen.generator->write_construct_typed_dictionary(temp, field_type.get_container_element_type_or_variant(0),2586field_type.get_container_element_type_or_variant(1), Vector<GDScriptCodeGenerator::Address>());2587codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2588codegen.generator->pop_temporary();2589} else if (field_type.kind == GDScriptDataType::BUILTIN) {2590GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2591codegen.generator->write_construct(temp, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());2592codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2593codegen.generator->pop_temporary();2594}2595// The `else` branch is for objects, in such case we leave it as `null`.2596}2597}25982599for (int i = 0; i < p_class->members.size(); i++) {2600// Initialize static fields.2601if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {2602continue;2603}2604const GDScriptParser::VariableNode *field = p_class->members[i].variable;2605if (!field->is_static) {2606continue;2607}26082609if (field->initializer) {2610codegen.generator->write_newline(field->initializer->start_line);26112612GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true);2613if (r_error) {2614memdelete(codegen.generator);2615return nullptr;2616}26172618GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2619GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);26202621if (field->use_conversion_assign) {2622codegen.generator->write_assign_with_conversion(temp, src_address);2623} else {2624codegen.generator->write_assign(temp, src_address);2625}2626if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2627codegen.generator->pop_temporary();2628}26292630codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2631codegen.generator->pop_temporary();2632}2633}26342635if (p_script->has_method(GDScriptLanguage::get_singleton()->strings._static_init)) {2636codegen.generator->write_newline(p_class->start_line);2637codegen.generator->write_call(GDScriptCodeGenerator::Address(), class_addr, GDScriptLanguage::get_singleton()->strings._static_init, Vector<GDScriptCodeGenerator::Address>());2638}26392640#ifdef DEBUG_ENABLED2641if (EngineDebugger::is_active()) {2642String signature;2643// Path.2644if (!p_script->get_script_path().is_empty()) {2645signature += p_script->get_script_path();2646}2647// Location.2648signature += "::0";26492650// Function and class.26512652if (p_class->identifier) {2653signature += "::" + String(p_class->identifier->name) + "." + String(func_name);2654} else {2655signature += "::" + String(func_name);2656}26572658codegen.generator->set_signature(signature);2659}2660#endif26612662codegen.generator->set_initial_line(p_class->start_line);26632664GDScriptFunction *gd_function = codegen.generator->write_end();26652666memdelete(codegen.generator);26672668return gd_function;2669}26702671Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) {2672Error err = OK;26732674GDScriptParser::FunctionNode *function;26752676if (p_is_setter) {2677function = p_variable->setter;2678} else {2679function = p_variable->getter;2680}26812682_parse_function(err, p_script, p_class, function);26832684return err;2685}26862687// Prepares given script, and inner class scripts, for compilation. It populates class members and2688// initializes method RPC info for its base classes first, then for itself, then for inner classes.2689// WARNING: This function cannot initiate compilation of other classes, or it will result in2690// cyclic dependency issues.2691Error GDScriptCompiler::_prepare_compilation(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {2692if (parsed_classes.has(p_script)) {2693return OK;2694}26952696if (parsing_classes.has(p_script)) {2697String class_name = p_class->identifier ? String(p_class->identifier->name) : p_class->fqcn;2698_set_error(vformat(R"(Cyclic class reference for "%s".)", class_name), p_class);2699return ERR_PARSE_ERROR;2700}27012702parsing_classes.insert(p_script);27032704p_script->clearing = true;27052706p_script->cancel_pending_functions(true);27072708p_script->native = Ref<GDScriptNativeClass>();2709p_script->base = Ref<GDScript>();2710p_script->members.clear();27112712// This makes possible to clear script constants and member_functions without heap-use-after-free errors.2713HashMap<StringName, Variant> constants;2714for (const KeyValue<StringName, Variant> &E : p_script->constants) {2715constants.insert(E.key, E.value);2716}2717p_script->constants.clear();2718constants.clear();2719HashMap<StringName, GDScriptFunction *> member_functions;2720for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->member_functions) {2721member_functions.insert(E.key, E.value);2722}2723p_script->member_functions.clear();2724for (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {2725memdelete(E.value);2726}2727member_functions.clear();27282729p_script->static_variables.clear();27302731if (p_script->implicit_initializer) {2732memdelete(p_script->implicit_initializer);2733}2734if (p_script->implicit_ready) {2735memdelete(p_script->implicit_ready);2736}2737if (p_script->static_initializer) {2738memdelete(p_script->static_initializer);2739}27402741p_script->member_functions.clear();2742p_script->member_indices.clear();2743p_script->static_variables_indices.clear();2744p_script->static_variables.clear();2745p_script->_signals.clear();2746p_script->initializer = nullptr;2747p_script->implicit_initializer = nullptr;2748p_script->implicit_ready = nullptr;2749p_script->static_initializer = nullptr;2750p_script->rpc_config.clear();2751p_script->lambda_info.clear();27522753p_script->clearing = false;27542755p_script->tool = parser->is_tool();2756p_script->_is_abstract = p_class->is_abstract;27572758if (p_script->local_name != StringName()) {2759if (GDScriptAnalyzer::class_exists(p_script->local_name)) {2760_set_error(vformat(R"(The class "%s" shadows a native class)", p_script->local_name), p_class);2761return ERR_ALREADY_EXISTS;2762}2763}27642765GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type, p_script, false);27662767if (base_type.native_type == StringName()) {2768_set_error(vformat(R"(Parser bug (please report): Empty native type in base class "%s")", p_script->path), p_class);2769return ERR_BUG;2770}27712772int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[base_type.native_type];27732774p_script->native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx];2775if (p_script->native.is_null()) {2776_set_error("Compiler bug (please report): script native type is null.", nullptr);2777return ERR_BUG;2778}27792780// Inheritance2781switch (base_type.kind) {2782case GDScriptDataType::NATIVE:2783// Nothing more to do.2784break;2785case GDScriptDataType::GDSCRIPT: {2786Ref<GDScript> base = Ref<GDScript>(base_type.script_type);2787if (base.is_null()) {2788_set_error("Compiler bug (please report): base script type is null.", nullptr);2789return ERR_BUG;2790}27912792if (main_script->has_class(base.ptr())) {2793Error err = _prepare_compilation(base.ptr(), p_class->base_type.class_type, p_keep_state);2794if (err) {2795return err;2796}2797} else if (!base->is_valid()) {2798Error err = OK;2799Ref<GDScript> base_root = GDScriptCache::get_shallow_script(base->path, err, p_script->path);2800if (err) {2801_set_error(vformat(R"(Could not parse base class "%s" from "%s": %s)", base->fully_qualified_name, base->path, error_names[err]), nullptr);2802return err;2803}2804if (base_root.is_valid()) {2805base = Ref<GDScript>(base_root->find_class(base->fully_qualified_name));2806}2807if (base.is_null()) {2808_set_error(vformat(R"(Could not find class "%s" in "%s".)", base->fully_qualified_name, base->path), nullptr);2809return ERR_COMPILATION_FAILED;2810}28112812err = _prepare_compilation(base.ptr(), p_class->base_type.class_type, p_keep_state);2813if (err) {2814_set_error(vformat(R"(Could not populate class members of base class "%s" in "%s".)", base->fully_qualified_name, base->path), nullptr);2815return err;2816}2817}28182819p_script->base = base;2820p_script->member_indices = base->member_indices;2821} break;2822default: {2823_set_error("Parser bug (please report): invalid inheritance.", nullptr);2824return ERR_BUG;2825} break;2826}28272828// Duplicate RPC information from base GDScript2829// Base script isn't valid because it should not have been compiled yet, but the reference contains relevant info.2830if (base_type.kind == GDScriptDataType::GDSCRIPT && p_script->base.is_valid()) {2831p_script->rpc_config = p_script->base->rpc_config.duplicate();2832}28332834for (int i = 0; i < p_class->members.size(); i++) {2835const GDScriptParser::ClassNode::Member &member = p_class->members[i];2836switch (member.type) {2837case GDScriptParser::ClassNode::Member::VARIABLE: {2838const GDScriptParser::VariableNode *variable = member.variable;2839StringName name = variable->identifier->name;28402841GDScript::MemberInfo minfo;2842switch (variable->property) {2843case GDScriptParser::VariableNode::PROP_NONE:2844break; // Nothing to do.2845case GDScriptParser::VariableNode::PROP_SETGET:2846if (variable->setter_pointer != nullptr) {2847minfo.setter = variable->setter_pointer->name;2848}2849if (variable->getter_pointer != nullptr) {2850minfo.getter = variable->getter_pointer->name;2851}2852break;2853case GDScriptParser::VariableNode::PROP_INLINE:2854if (variable->setter != nullptr) {2855minfo.setter = "@" + variable->identifier->name + "_setter";2856}2857if (variable->getter != nullptr) {2858minfo.getter = "@" + variable->identifier->name + "_getter";2859}2860break;2861}28622863const GDScriptParser::DataType variable_type = variable->get_datatype();2864minfo.data_type = _gdtype_from_datatype(variable_type, p_script);28652866PropertyInfo prop_info = variable_type.to_property_info(name);2867PropertyInfo export_info = variable->export_info;28682869if (variable->exported) {2870if (!minfo.data_type.has_type()) {2871prop_info.type = export_info.type;2872prop_info.class_name = export_info.class_name;2873}2874prop_info.hint = export_info.hint;2875prop_info.hint_string = export_info.hint_string;2876prop_info.usage = export_info.usage;2877} else {2878// Enum hint doesn't really belong to the data type information, so we don't want to add it to2879// `GDScriptParser::DataType::to_property_info()`. However, we still want to add this metadata2880// for unexported properties so they display nicely in the Remote Tree Inspector.2881if (variable_type.kind == GDScriptParser::DataType::ENUM && !variable_type.is_meta_type) {2882prop_info.hint = PROPERTY_HINT_ENUM;28832884String enum_hint_string;2885bool first = true;2886for (const KeyValue<StringName, int64_t> &E : variable_type.enum_values) {2887if (first) {2888first = false;2889} else {2890enum_hint_string += ",";2891}2892enum_hint_string += E.key.operator String().capitalize().xml_escape();2893enum_hint_string += ":";2894enum_hint_string += String::num_int64(E.value).xml_escape();2895}28962897prop_info.hint_string = enum_hint_string;2898}2899}2900prop_info.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;2901minfo.property_info = prop_info;29022903if (variable->is_static) {2904minfo.index = p_script->static_variables_indices.size();2905p_script->static_variables_indices[name] = minfo;2906} else {2907minfo.index = p_script->member_indices.size();2908p_script->member_indices[name] = minfo;2909p_script->members.insert(name);2910}29112912#ifdef TOOLS_ENABLED2913if (variable->initializer != nullptr && variable->initializer->is_constant) {2914p_script->member_default_values[name] = variable->initializer->reduced_value;2915GDScriptCompiler::convert_to_initializer_type(p_script->member_default_values[name], variable);2916} else {2917p_script->member_default_values.erase(name);2918}2919#endif2920} break;29212922case GDScriptParser::ClassNode::Member::CONSTANT: {2923const GDScriptParser::ConstantNode *constant = member.constant;2924StringName name = constant->identifier->name;29252926p_script->constants.insert(name, constant->initializer->reduced_value);2927} break;29282929case GDScriptParser::ClassNode::Member::ENUM_VALUE: {2930const GDScriptParser::EnumNode::Value &enum_value = member.enum_value;2931StringName name = enum_value.identifier->name;29322933p_script->constants.insert(name, enum_value.value);2934} break;29352936case GDScriptParser::ClassNode::Member::SIGNAL: {2937const GDScriptParser::SignalNode *signal = member.signal;2938StringName name = signal->identifier->name;29392940p_script->_signals[name] = signal->method_info;2941} break;29422943case GDScriptParser::ClassNode::Member::ENUM: {2944const GDScriptParser::EnumNode *enum_n = member.m_enum;2945StringName name = enum_n->identifier->name;29462947p_script->constants.insert(name, enum_n->dictionary);2948} break;29492950case GDScriptParser::ClassNode::Member::GROUP: {2951const GDScriptParser::AnnotationNode *annotation = member.annotation;2952// Avoid name conflict. See GH-78252.2953StringName name = vformat("@group_%d_%s", p_script->members.size(), annotation->export_info.name);29542955// This is not a normal member, but we need this to keep indices in order.2956GDScript::MemberInfo minfo;2957minfo.index = p_script->member_indices.size();29582959PropertyInfo prop_info;2960prop_info.name = annotation->export_info.name;2961prop_info.usage = annotation->export_info.usage;2962prop_info.hint_string = annotation->export_info.hint_string;2963minfo.property_info = prop_info;29642965p_script->member_indices[name] = minfo;2966p_script->members.insert(name);2967} break;29682969case GDScriptParser::ClassNode::Member::FUNCTION: {2970const GDScriptParser::FunctionNode *function_n = member.function;29712972Variant config = function_n->rpc_config;2973if (config.get_type() != Variant::NIL) {2974p_script->rpc_config[function_n->identifier->name] = config;2975}2976} break;2977default:2978break; // Nothing to do here.2979}2980}29812982p_script->static_variables.resize(p_script->static_variables_indices.size());29832984parsed_classes.insert(p_script);2985parsing_classes.erase(p_script);29862987// Populate inner classes.2988for (int i = 0; i < p_class->members.size(); i++) {2989const GDScriptParser::ClassNode::Member &member = p_class->members[i];2990if (member.type != member.CLASS) {2991continue;2992}2993const GDScriptParser::ClassNode *inner_class = member.m_class;2994StringName name = inner_class->identifier->name;2995Ref<GDScript> &subclass = p_script->subclasses[name];2996GDScript *subclass_ptr = subclass.ptr();29972998// Subclass might still be parsing, just skip it2999if (!parsing_classes.has(subclass_ptr)) {3000Error err = _prepare_compilation(subclass_ptr, inner_class, p_keep_state);3001if (err) {3002return err;3003}3004}30053006p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants3007}30083009return OK;3010}30113012Error GDScriptCompiler::_compile_class(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {3013// Compile member functions, getters, and setters.3014for (int i = 0; i < p_class->members.size(); i++) {3015const GDScriptParser::ClassNode::Member &member = p_class->members[i];3016if (member.type == member.FUNCTION) {3017const GDScriptParser::FunctionNode *function = member.function;3018Error err = OK;3019_parse_function(err, p_script, p_class, function);3020if (err) {3021return err;3022}3023} else if (member.type == member.VARIABLE) {3024const GDScriptParser::VariableNode *variable = member.variable;3025if (variable->property == GDScriptParser::VariableNode::PROP_INLINE) {3026if (variable->setter != nullptr) {3027Error err = _parse_setter_getter(p_script, p_class, variable, true);3028if (err) {3029return err;3030}3031}3032if (variable->getter != nullptr) {3033Error err = _parse_setter_getter(p_script, p_class, variable, false);3034if (err) {3035return err;3036}3037}3038}3039}3040}30413042{3043// Create `@implicit_new()` special function in any case.3044Error err = OK;3045_parse_function(err, p_script, p_class, nullptr);3046if (err) {3047return err;3048}3049}30503051if (p_class->onready_used) {3052// Create `@implicit_ready()` special function.3053Error err = OK;3054_parse_function(err, p_script, p_class, nullptr, true);3055if (err) {3056return err;3057}3058}30593060if (p_class->has_static_data) {3061Error err = OK;3062GDScriptFunction *func = _make_static_initializer(err, p_script, p_class);3063p_script->static_initializer = func;3064if (err) {3065return err;3066}3067}30683069#ifdef DEBUG_ENABLED30703071//validate instances if keeping state30723073if (p_keep_state) {3074for (RBSet<Object *>::Element *E = p_script->instances.front(); E;) {3075RBSet<Object *>::Element *N = E->next();30763077ScriptInstance *si = E->get()->get_script_instance();3078if (si->is_placeholder()) {3079#ifdef TOOLS_ENABLED3080PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si);30813082if (p_script->is_tool()) {3083//re-create as an instance3084p_script->placeholders.erase(psi); //remove placeholder30853086GDScriptInstance *instance = memnew(GDScriptInstance);3087instance->members.resize(p_script->member_indices.size());3088instance->script = Ref<GDScript>(p_script);3089instance->owner = E->get();30903091//needed for hot reloading3092for (const KeyValue<StringName, GDScript::MemberInfo> &F : p_script->member_indices) {3093instance->member_indices_cache[F.key] = F.value.index;3094}3095instance->owner->set_script_instance(instance);30963097/* STEP 2, INITIALIZE AND CONSTRUCT */30983099Callable::CallError ce;3100p_script->initializer->call(instance, nullptr, 0, ce);31013102if (ce.error != Callable::CallError::CALL_OK) {3103//well, tough luck, not gonna do anything here3104}3105}3106#endif // TOOLS_ENABLED3107} else {3108GDScriptInstance *gi = static_cast<GDScriptInstance *>(si);3109gi->reload_members();3110}31113112E = N;3113}3114}3115#endif //DEBUG_ENABLED31163117has_static_data = p_class->has_static_data;31183119for (int i = 0; i < p_class->members.size(); i++) {3120if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {3121continue;3122}3123const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;3124StringName name = inner_class->identifier->name;3125GDScript *subclass = p_script->subclasses[name].ptr();31263127Error err = _compile_class(subclass, inner_class, p_keep_state);3128if (err) {3129return err;3130}31313132has_static_data = has_static_data || inner_class->has_static_data;3133}31343135p_script->_static_default_init();31363137p_script->valid = true;3138return OK;3139}31403141void GDScriptCompiler::convert_to_initializer_type(Variant &p_variant, const GDScriptParser::VariableNode *p_node) {3142// Set p_variant to the value of p_node's initializer, with the type of p_node's variable.3143GDScriptParser::DataType member_t = p_node->datatype;3144GDScriptParser::DataType init_t = p_node->initializer->datatype;3145if (member_t.is_hard_type() && init_t.is_hard_type() &&3146member_t.kind == GDScriptParser::DataType::BUILTIN && init_t.kind == GDScriptParser::DataType::BUILTIN) {3147if (Variant::can_convert_strict(init_t.builtin_type, member_t.builtin_type)) {3148const Variant *v = &p_node->initializer->reduced_value;3149Callable::CallError ce;3150Variant::construct(member_t.builtin_type, p_variant, &v, 1, ce);3151}3152}3153}31543155void GDScriptCompiler::make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {3156p_script->fully_qualified_name = p_class->fqcn;3157p_script->local_name = p_class->identifier ? p_class->identifier->name : StringName();3158p_script->global_name = p_class->get_global_name();3159p_script->simplified_icon_path = p_class->simplified_icon_path;31603161HashMap<StringName, Ref<GDScript>> old_subclasses;31623163if (p_keep_state) {3164old_subclasses = p_script->subclasses;3165}31663167p_script->subclasses.clear();31683169for (int i = 0; i < p_class->members.size(); i++) {3170if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {3171continue;3172}3173const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;3174StringName name = inner_class->identifier->name;31753176Ref<GDScript> subclass;31773178if (old_subclasses.has(name)) {3179subclass = old_subclasses[name];3180} else {3181subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(inner_class->fqcn);3182}31833184if (subclass.is_null()) {3185subclass.instantiate();3186}31873188subclass->_owner = p_script;3189subclass->path = p_script->path;3190p_script->subclasses.insert(name, subclass);31913192make_scripts(subclass.ptr(), inner_class, p_keep_state);3193}3194}31953196GDScriptCompiler::FunctionLambdaInfo GDScriptCompiler::_get_function_replacement_info(GDScriptFunction *p_func, int p_index, int p_depth, GDScriptFunction *p_parent_func) {3197FunctionLambdaInfo info;3198info.function = p_func;3199info.parent = p_parent_func;3200info.script = p_func->get_script();3201info.name = p_func->get_name();3202info.line = p_func->_initial_line;3203info.index = p_index;3204info.depth = p_depth;3205info.capture_count = 0;3206info.use_self = false;3207info.arg_count = p_func->_argument_count;3208info.default_arg_count = p_func->_default_arg_count;3209info.sublambdas = _get_function_lambda_replacement_info(p_func, p_depth, p_parent_func);32103211ERR_FAIL_NULL_V(info.script, info);3212GDScript::LambdaInfo *extra_info = info.script->lambda_info.getptr(p_func);3213if (extra_info != nullptr) {3214info.capture_count = extra_info->capture_count;3215info.use_self = extra_info->use_self;3216} else {3217info.capture_count = 0;3218info.use_self = false;3219}32203221return info;3222}32233224Vector<GDScriptCompiler::FunctionLambdaInfo> GDScriptCompiler::_get_function_lambda_replacement_info(GDScriptFunction *p_func, int p_depth, GDScriptFunction *p_parent_func) {3225Vector<FunctionLambdaInfo> result;3226// Only scrape the lambdas inside p_func.3227for (int i = 0; i < p_func->lambdas.size(); ++i) {3228result.push_back(_get_function_replacement_info(p_func->lambdas[i], i, p_depth + 1, p_func));3229}3230return result;3231}32323233GDScriptCompiler::ScriptLambdaInfo GDScriptCompiler::_get_script_lambda_replacement_info(GDScript *p_script) {3234ScriptLambdaInfo info;32353236if (p_script->implicit_initializer) {3237info.implicit_initializer_info = _get_function_lambda_replacement_info(p_script->implicit_initializer);3238}3239if (p_script->implicit_ready) {3240info.implicit_ready_info = _get_function_lambda_replacement_info(p_script->implicit_ready);3241}3242if (p_script->static_initializer) {3243info.static_initializer_info = _get_function_lambda_replacement_info(p_script->static_initializer);3244}32453246for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->member_functions) {3247info.member_function_infos.insert(E.key, _get_function_lambda_replacement_info(E.value));3248}32493250for (const KeyValue<StringName, Ref<GDScript>> &KV : p_script->get_subclasses()) {3251info.subclass_info.insert(KV.key, _get_script_lambda_replacement_info(KV.value.ptr()));3252}32533254return info;3255}32563257bool GDScriptCompiler::_do_function_infos_match(const FunctionLambdaInfo &p_old_info, const FunctionLambdaInfo *p_new_info) {3258if (p_new_info == nullptr) {3259return false;3260}32613262if (p_new_info->capture_count != p_old_info.capture_count || p_new_info->use_self != p_old_info.use_self) {3263return false;3264}32653266int old_required_arg_count = p_old_info.arg_count - p_old_info.default_arg_count;3267int new_required_arg_count = p_new_info->arg_count - p_new_info->default_arg_count;3268if (new_required_arg_count > old_required_arg_count || p_new_info->arg_count < old_required_arg_count) {3269return false;3270}32713272return true;3273}32743275void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const FunctionLambdaInfo &p_old_info, const FunctionLambdaInfo *p_new_info) {3276ERR_FAIL_COND(r_replacements.has(p_old_info.function));3277if (!_do_function_infos_match(p_old_info, p_new_info)) {3278p_new_info = nullptr;3279}32803281r_replacements.insert(p_old_info.function, p_new_info != nullptr ? p_new_info->function : nullptr);3282_get_function_ptr_replacements(r_replacements, p_old_info.sublambdas, p_new_info != nullptr ? &p_new_info->sublambdas : nullptr);3283}32843285void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const Vector<FunctionLambdaInfo> &p_old_infos, const Vector<FunctionLambdaInfo> *p_new_infos) {3286for (int i = 0; i < p_old_infos.size(); ++i) {3287const FunctionLambdaInfo &old_info = p_old_infos[i];3288const FunctionLambdaInfo *new_info = nullptr;3289if (p_new_infos != nullptr && p_new_infos->size() == p_old_infos.size()) {3290// For now only attempt if the size is the same.3291new_info = &p_new_infos->get(i);3292}3293_get_function_ptr_replacements(r_replacements, old_info, new_info);3294}3295}32963297void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const ScriptLambdaInfo &p_old_info, const ScriptLambdaInfo *p_new_info) {3298_get_function_ptr_replacements(r_replacements, p_old_info.implicit_initializer_info, p_new_info != nullptr ? &p_new_info->implicit_initializer_info : nullptr);3299_get_function_ptr_replacements(r_replacements, p_old_info.implicit_ready_info, p_new_info != nullptr ? &p_new_info->implicit_ready_info : nullptr);3300_get_function_ptr_replacements(r_replacements, p_old_info.static_initializer_info, p_new_info != nullptr ? &p_new_info->static_initializer_info : nullptr);33013302for (const KeyValue<StringName, Vector<FunctionLambdaInfo>> &old_kv : p_old_info.member_function_infos) {3303_get_function_ptr_replacements(r_replacements, old_kv.value, p_new_info != nullptr ? p_new_info->member_function_infos.getptr(old_kv.key) : nullptr);3304}3305for (int i = 0; i < p_old_info.other_function_infos.size(); ++i) {3306const FunctionLambdaInfo &old_other_info = p_old_info.other_function_infos[i];3307const FunctionLambdaInfo *new_other_info = nullptr;3308if (p_new_info != nullptr && p_new_info->other_function_infos.size() == p_old_info.other_function_infos.size()) {3309// For now only attempt if the size is the same.3310new_other_info = &p_new_info->other_function_infos[i];3311}3312// Needs to be called on all old lambdas, even if there's no replacement.3313_get_function_ptr_replacements(r_replacements, old_other_info, new_other_info);3314}3315for (const KeyValue<StringName, ScriptLambdaInfo> &old_kv : p_old_info.subclass_info) {3316const ScriptLambdaInfo &old_subinfo = old_kv.value;3317const ScriptLambdaInfo *new_subinfo = p_new_info != nullptr ? p_new_info->subclass_info.getptr(old_kv.key) : nullptr;3318_get_function_ptr_replacements(r_replacements, old_subinfo, new_subinfo);3319}3320}33213322Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) {3323err_line = -1;3324err_column = -1;3325error = "";3326parser = p_parser;3327main_script = p_script;3328const GDScriptParser::ClassNode *root = parser->get_tree();33293330source = p_script->get_path();33313332ScriptLambdaInfo old_lambda_info = _get_script_lambda_replacement_info(p_script);33333334// Create scripts for subclasses beforehand so they can be referenced3335make_scripts(p_script, root, p_keep_state);33363337main_script->_owner = nullptr;3338Error err = _prepare_compilation(main_script, parser->get_tree(), p_keep_state);33393340if (err) {3341return err;3342}33433344err = _compile_class(main_script, root, p_keep_state);3345if (err) {3346return err;3347}33483349ScriptLambdaInfo new_lambda_info = _get_script_lambda_replacement_info(p_script);33503351HashMap<GDScriptFunction *, GDScriptFunction *> func_ptr_replacements;3352_get_function_ptr_replacements(func_ptr_replacements, old_lambda_info, &new_lambda_info);3353main_script->_recurse_replace_function_ptrs(func_ptr_replacements);33543355if (has_static_data && !root->annotated_static_unload) {3356GDScriptCache::add_static_script(p_script);3357}33583359err = GDScriptCache::finish_compiling(main_script->path);3360if (err) {3361_set_error(R"(Failed to compile depended scripts.)", nullptr);3362}3363return err;3364}33653366String GDScriptCompiler::get_error() const {3367return error;3368}33693370int GDScriptCompiler::get_error_line() const {3371return err_line;3372}33733374int GDScriptCompiler::get_error_column() const {3375return err_column;3376}33773378GDScriptCompiler::GDScriptCompiler() {3379}338033813382