Path: blob/master/modules/gdscript/gdscript_compiler.cpp
10277 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_byte_codegen.h"34#include "gdscript_cache.h"35#include "gdscript_utility_functions.h"3637#include "core/config/engine.h"38#include "core/config/project_settings.h"3940#include "scene/scene_string_names.h"4142bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {43if (codegen.function_node && codegen.function_node->is_static) {44return false;45}4647if (_is_local_or_parameter(codegen, p_name)) {48return false; //shadowed49}5051return _is_class_member_property(codegen.script, p_name);52}5354bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {55GDScript *scr = owner;56GDScriptNativeClass *nc = nullptr;57while (scr) {58if (scr->native.is_valid()) {59nc = scr->native.ptr();60}61scr = scr->_base;62}6364ERR_FAIL_NULL_V(nc, false);6566return ClassDB::has_property(nc->get_name(), p_name);67}6869bool GDScriptCompiler::_is_local_or_parameter(CodeGen &codegen, const StringName &p_name) {70return codegen.parameters.has(p_name) || codegen.locals.has(p_name);71}7273void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::Node *p_node) {74if (!error.is_empty()) {75return;76}7778error = p_error;79if (p_node) {80err_line = p_node->start_line;81err_column = p_node->start_column;82} else {83err_line = 0;84err_column = 0;85}86}8788GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner, bool p_handle_metatype) {89if (!p_datatype.is_set() || !p_datatype.is_hard_type() || p_datatype.is_coroutine) {90return GDScriptDataType();91}9293GDScriptDataType result;94result.has_type = true;9596switch (p_datatype.kind) {97case GDScriptParser::DataType::VARIANT: {98result.has_type = false;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;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;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;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.has_type && 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 (ClassDB::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.has_type && 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;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;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.has_type = true;1448equality_type.kind = GDScriptDataType::BUILTIN;1449equality_type.builtin_type = Variant::BOOL;14501451// Check type equality.1452GDScriptCodeGenerator::Address type_equality_addr = codegen.add_temporary(equality_type);1453codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr);14541455if (literal_type == Variant::STRING) {1456GDScriptCodeGenerator::Address type_stringname_addr = codegen.add_constant(Variant::STRING_NAME);14571458// Check StringName <-> String type equality.1459GDScriptCodeGenerator::Address tmp_comp_addr = codegen.add_temporary(equality_type);14601461codegen.generator->write_binary_operator(tmp_comp_addr, Variant::OP_EQUAL, p_type_addr, type_stringname_addr);1462codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_OR, type_equality_addr, tmp_comp_addr);14631464codegen.generator->pop_temporary(); // Remove tmp_comp_addr from stack.1465} else if (literal_type == Variant::STRING_NAME) {1466GDScriptCodeGenerator::Address type_string_addr = codegen.add_constant(Variant::STRING);14671468// Check String <-> StringName type equality.1469GDScriptCodeGenerator::Address tmp_comp_addr = codegen.add_temporary(equality_type);14701471codegen.generator->write_binary_operator(tmp_comp_addr, Variant::OP_EQUAL, p_type_addr, type_string_addr);1472codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_OR, type_equality_addr, tmp_comp_addr);14731474codegen.generator->pop_temporary(); // Remove tmp_comp_addr from stack.1475}14761477codegen.generator->write_and_left_operand(type_equality_addr);14781479// Get literal.1480GDScriptCodeGenerator::Address literal_addr = _parse_expression(codegen, r_error, p_pattern->literal);1481if (r_error) {1482return GDScriptCodeGenerator::Address();1483}14841485// Check value equality.1486GDScriptCodeGenerator::Address equality_addr = codegen.add_temporary(equality_type);1487codegen.generator->write_binary_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr);1488codegen.generator->write_and_right_operand(equality_addr);14891490// AND both together (reuse temporary location).1491codegen.generator->write_end_and(type_equality_addr);14921493codegen.generator->pop_temporary(); // Remove equality_addr from stack.14941495if (literal_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1496codegen.generator->pop_temporary();1497}14981499// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1500if (p_is_nested) {1501// Use the previous value as target, since we only need one temporary variable.1502codegen.generator->write_and_right_operand(type_equality_addr);1503codegen.generator->write_end_and(p_previous_test);1504} else if (!p_is_first) {1505// Use the previous value as target, since we only need one temporary variable.1506codegen.generator->write_or_right_operand(type_equality_addr);1507codegen.generator->write_end_or(p_previous_test);1508} else {1509// Just assign this value to the accumulator temporary.1510codegen.generator->write_assign(p_previous_test, type_equality_addr);1511}1512codegen.generator->pop_temporary(); // Remove type_equality_addr.15131514return p_previous_test;1515} break;1516case GDScriptParser::PatternNode::PT_EXPRESSION: {1517if (p_is_nested) {1518codegen.generator->write_and_left_operand(p_previous_test);1519} else if (!p_is_first) {1520codegen.generator->write_or_left_operand(p_previous_test);1521}15221523GDScriptCodeGenerator::Address type_string_addr = codegen.add_constant(Variant::STRING);1524GDScriptCodeGenerator::Address type_stringname_addr = codegen.add_constant(Variant::STRING_NAME);15251526// Equality is always a boolean.1527GDScriptDataType equality_type;1528equality_type.has_type = true;1529equality_type.kind = GDScriptDataType::BUILTIN;1530equality_type.builtin_type = Variant::BOOL;15311532// Create the result temps first since it's the last to go away.1533GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(equality_type);1534GDScriptCodeGenerator::Address equality_test_addr = codegen.add_temporary(equality_type);1535GDScriptCodeGenerator::Address stringy_comp_addr = codegen.add_temporary(equality_type);1536GDScriptCodeGenerator::Address stringy_comp_addr_2 = codegen.add_temporary(equality_type);1537GDScriptCodeGenerator::Address expr_type_addr = codegen.add_temporary();15381539// Evaluate expression.1540GDScriptCodeGenerator::Address expr_addr;1541expr_addr = _parse_expression(codegen, r_error, p_pattern->expression);1542if (r_error) {1543return GDScriptCodeGenerator::Address();1544}15451546// Evaluate expression type.1547Vector<GDScriptCodeGenerator::Address> typeof_args;1548typeof_args.push_back(expr_addr);1549codegen.generator->write_call_utility(expr_type_addr, "typeof", typeof_args);15501551// Check type equality.1552codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, expr_type_addr);15531554// Check for String <-> StringName comparison.1555codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_EQUAL, p_type_addr, type_string_addr);1556codegen.generator->write_binary_operator(stringy_comp_addr_2, Variant::OP_EQUAL, expr_type_addr, type_stringname_addr);1557codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_AND, stringy_comp_addr, stringy_comp_addr_2);1558codegen.generator->write_binary_operator(result_addr, Variant::OP_OR, result_addr, stringy_comp_addr);15591560// Check for StringName <-> String comparison.1561codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_EQUAL, p_type_addr, type_stringname_addr);1562codegen.generator->write_binary_operator(stringy_comp_addr_2, Variant::OP_EQUAL, expr_type_addr, type_string_addr);1563codegen.generator->write_binary_operator(stringy_comp_addr, Variant::OP_AND, stringy_comp_addr, stringy_comp_addr_2);1564codegen.generator->write_binary_operator(result_addr, Variant::OP_OR, result_addr, stringy_comp_addr);15651566codegen.generator->pop_temporary(); // Remove expr_type_addr from stack.1567codegen.generator->pop_temporary(); // Remove stringy_comp_addr_2 from stack.1568codegen.generator->pop_temporary(); // Remove stringy_comp_addr from stack.15691570codegen.generator->write_and_left_operand(result_addr);15711572// Check value equality.1573codegen.generator->write_binary_operator(equality_test_addr, Variant::OP_EQUAL, p_value_addr, expr_addr);1574codegen.generator->write_and_right_operand(equality_test_addr);15751576// AND both type and value equality.1577codegen.generator->write_end_and(result_addr);15781579// We don't need the expression temporary anymore.1580if (expr_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1581codegen.generator->pop_temporary();1582}1583codegen.generator->pop_temporary(); // Remove equality_test_addr from stack.15841585// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1586if (p_is_nested) {1587// Use the previous value as target, since we only need one temporary variable.1588codegen.generator->write_and_right_operand(result_addr);1589codegen.generator->write_end_and(p_previous_test);1590} else if (!p_is_first) {1591// Use the previous value as target, since we only need one temporary variable.1592codegen.generator->write_or_right_operand(result_addr);1593codegen.generator->write_end_or(p_previous_test);1594} else {1595// Just assign this value to the accumulator temporary.1596codegen.generator->write_assign(p_previous_test, result_addr);1597}1598codegen.generator->pop_temporary(); // Remove temp result addr.15991600return p_previous_test;1601} break;1602case GDScriptParser::PatternNode::PT_ARRAY: {1603if (p_is_nested) {1604codegen.generator->write_and_left_operand(p_previous_test);1605} else if (!p_is_first) {1606codegen.generator->write_or_left_operand(p_previous_test);1607}1608// Get array type into constant map.1609GDScriptCodeGenerator::Address array_type_addr = codegen.add_constant((int)Variant::ARRAY);16101611// Equality is always a boolean.1612GDScriptDataType temp_type;1613temp_type.has_type = true;1614temp_type.kind = GDScriptDataType::BUILTIN;1615temp_type.builtin_type = Variant::BOOL;16161617// Check type equality.1618GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);1619codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr);1620codegen.generator->write_and_left_operand(result_addr);16211622// Store pattern length in constant map.1623GDScriptCodeGenerator::Address array_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->array.size() - 1 : p_pattern->array.size());16241625// Get value length.1626temp_type.builtin_type = Variant::INT;1627GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);1628Vector<GDScriptCodeGenerator::Address> len_args;1629len_args.push_back(p_value_addr);1630codegen.generator->write_call_gdscript_utility(value_length_addr, "len", len_args);16311632// Test length compatibility.1633temp_type.builtin_type = Variant::BOOL;1634GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);1635codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr);1636codegen.generator->write_and_right_operand(length_compat_addr);16371638// AND type and length check.1639codegen.generator->write_end_and(result_addr);16401641// Remove length temporaries.1642codegen.generator->pop_temporary();1643codegen.generator->pop_temporary();16441645// Create temporaries outside the loop so they can be reused.1646GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();1647GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();16481649// Evaluate element by element.1650for (int i = 0; i < p_pattern->array.size(); i++) {1651if (p_pattern->array[i]->pattern_type == GDScriptParser::PatternNode::PT_REST) {1652// Don't want to access an extra element of the user array.1653break;1654}16551656// 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).1657codegen.generator->write_and_left_operand(result_addr);16581659// Add index to constant map.1660GDScriptCodeGenerator::Address index_addr = codegen.add_constant(i);16611662// Get the actual element from the user-sent array.1663codegen.generator->write_get(element_addr, index_addr, p_value_addr);16641665// Also get type of element.1666Vector<GDScriptCodeGenerator::Address> typeof_args;1667typeof_args.push_back(element_addr);1668codegen.generator->write_call_utility(element_type_addr, "typeof", typeof_args);16691670// Try the pattern inside the element.1671result_addr = _parse_match_pattern(codegen, r_error, p_pattern->array[i], element_addr, element_type_addr, result_addr, false, true);1672if (r_error != OK) {1673return GDScriptCodeGenerator::Address();1674}16751676codegen.generator->write_and_right_operand(result_addr);1677codegen.generator->write_end_and(result_addr);1678}1679// Remove element temporaries.1680codegen.generator->pop_temporary();1681codegen.generator->pop_temporary();16821683// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1684if (p_is_nested) {1685// Use the previous value as target, since we only need one temporary variable.1686codegen.generator->write_and_right_operand(result_addr);1687codegen.generator->write_end_and(p_previous_test);1688} else if (!p_is_first) {1689// Use the previous value as target, since we only need one temporary variable.1690codegen.generator->write_or_right_operand(result_addr);1691codegen.generator->write_end_or(p_previous_test);1692} else {1693// Just assign this value to the accumulator temporary.1694codegen.generator->write_assign(p_previous_test, result_addr);1695}1696codegen.generator->pop_temporary(); // Remove temp result addr.16971698return p_previous_test;1699} break;1700case GDScriptParser::PatternNode::PT_DICTIONARY: {1701if (p_is_nested) {1702codegen.generator->write_and_left_operand(p_previous_test);1703} else if (!p_is_first) {1704codegen.generator->write_or_left_operand(p_previous_test);1705}1706// Get dictionary type into constant map.1707GDScriptCodeGenerator::Address dict_type_addr = codegen.add_constant((int)Variant::DICTIONARY);17081709// Equality is always a boolean.1710GDScriptDataType temp_type;1711temp_type.has_type = true;1712temp_type.kind = GDScriptDataType::BUILTIN;1713temp_type.builtin_type = Variant::BOOL;17141715// Check type equality.1716GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);1717codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr);1718codegen.generator->write_and_left_operand(result_addr);17191720// Store pattern length in constant map.1721GDScriptCodeGenerator::Address dict_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());17221723// Get user's dictionary length.1724temp_type.builtin_type = Variant::INT;1725GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);1726Vector<GDScriptCodeGenerator::Address> func_args;1727func_args.push_back(p_value_addr);1728codegen.generator->write_call_gdscript_utility(value_length_addr, "len", func_args);17291730// Test length compatibility.1731temp_type.builtin_type = Variant::BOOL;1732GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);1733codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr);1734codegen.generator->write_and_right_operand(length_compat_addr);17351736// AND type and length check.1737codegen.generator->write_end_and(result_addr);17381739// Remove length temporaries.1740codegen.generator->pop_temporary();1741codegen.generator->pop_temporary();17421743// Create temporaries outside the loop so they can be reused.1744GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();1745GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();17461747// Evaluate element by element.1748for (int i = 0; i < p_pattern->dictionary.size(); i++) {1749const GDScriptParser::PatternNode::Pair &element = p_pattern->dictionary[i];1750if (element.value_pattern && element.value_pattern->pattern_type == GDScriptParser::PatternNode::PT_REST) {1751// Ignore rest pattern.1752break;1753}17541755// 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).1756codegen.generator->write_and_left_operand(result_addr);17571758// Get the pattern key.1759GDScriptCodeGenerator::Address pattern_key_addr = _parse_expression(codegen, r_error, element.key);1760if (r_error) {1761return GDScriptCodeGenerator::Address();1762}17631764// Check if pattern key exists in user's dictionary. This will be AND-ed with next result.1765func_args.clear();1766func_args.push_back(pattern_key_addr);1767codegen.generator->write_call(result_addr, p_value_addr, "has", func_args);17681769if (element.value_pattern != nullptr) {1770// 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).1771codegen.generator->write_and_left_operand(result_addr);17721773// Get actual value from user dictionary.1774codegen.generator->write_get(element_addr, pattern_key_addr, p_value_addr);17751776// Also get type of value.1777func_args.clear();1778func_args.push_back(element_addr);1779codegen.generator->write_call_utility(element_type_addr, "typeof", func_args);17801781// Try the pattern inside the value.1782result_addr = _parse_match_pattern(codegen, r_error, element.value_pattern, element_addr, element_type_addr, result_addr, false, true);1783if (r_error != OK) {1784return GDScriptCodeGenerator::Address();1785}1786codegen.generator->write_and_right_operand(result_addr);1787codegen.generator->write_end_and(result_addr);1788}17891790codegen.generator->write_and_right_operand(result_addr);1791codegen.generator->write_end_and(result_addr);17921793// Remove pattern key temporary.1794if (pattern_key_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1795codegen.generator->pop_temporary();1796}1797}17981799// Remove element temporaries.1800codegen.generator->pop_temporary();1801codegen.generator->pop_temporary();18021803// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1804if (p_is_nested) {1805// Use the previous value as target, since we only need one temporary variable.1806codegen.generator->write_and_right_operand(result_addr);1807codegen.generator->write_end_and(p_previous_test);1808} else if (!p_is_first) {1809// Use the previous value as target, since we only need one temporary variable.1810codegen.generator->write_or_right_operand(result_addr);1811codegen.generator->write_end_or(p_previous_test);1812} else {1813// Just assign this value to the accumulator temporary.1814codegen.generator->write_assign(p_previous_test, result_addr);1815}1816codegen.generator->pop_temporary(); // Remove temp result addr.18171818return p_previous_test;1819} break;1820case GDScriptParser::PatternNode::PT_REST:1821// Do nothing.1822return p_previous_test;1823break;1824case GDScriptParser::PatternNode::PT_BIND: {1825if (p_is_nested) {1826codegen.generator->write_and_left_operand(p_previous_test);1827} else if (!p_is_first) {1828codegen.generator->write_or_left_operand(p_previous_test);1829}1830// Get the bind address.1831GDScriptCodeGenerator::Address bind = codegen.locals[p_pattern->bind->name];18321833// Assign value to bound variable.1834codegen.generator->write_assign(bind, p_value_addr);1835}1836[[fallthrough]]; // Act like matching anything too.1837case GDScriptParser::PatternNode::PT_WILDCARD:1838// If this is a fall through we don't want to do this again.1839if (p_pattern->pattern_type != GDScriptParser::PatternNode::PT_BIND) {1840if (p_is_nested) {1841codegen.generator->write_and_left_operand(p_previous_test);1842} else if (!p_is_first) {1843codegen.generator->write_or_left_operand(p_previous_test);1844}1845}1846// This matches anything so just do the same as `if(true)`.1847// If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.1848if (p_is_nested) {1849// Use the operator with the `true` constant so it works as always matching.1850GDScriptCodeGenerator::Address constant = codegen.add_constant(true);1851codegen.generator->write_and_right_operand(constant);1852codegen.generator->write_end_and(p_previous_test);1853} else if (!p_is_first) {1854// Use the operator with the `true` constant so it works as always matching.1855GDScriptCodeGenerator::Address constant = codegen.add_constant(true);1856codegen.generator->write_or_right_operand(constant);1857codegen.generator->write_end_or(p_previous_test);1858} else {1859// Just assign this value to the accumulator temporary.1860codegen.generator->write_assign_true(p_previous_test);1861}1862return p_previous_test;1863}18641865_set_error("Compiler bug (please report): Reaching the end of pattern compilation without matching a pattern.", p_pattern);1866r_error = ERR_COMPILATION_FAILED;1867return p_previous_test;1868}18691870List<GDScriptCodeGenerator::Address> GDScriptCompiler::_add_block_locals(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block) {1871List<GDScriptCodeGenerator::Address> addresses;1872for (int i = 0; i < p_block->locals.size(); i++) {1873if (p_block->locals[i].type == GDScriptParser::SuiteNode::Local::PARAMETER || p_block->locals[i].type == GDScriptParser::SuiteNode::Local::FOR_VARIABLE) {1874// Parameters are added directly from function and loop variables are declared explicitly.1875continue;1876}1877addresses.push_back(codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype(), codegen.script)));1878}1879return addresses;1880}18811882// Avoid keeping in the stack long-lived references to objects, which may prevent `RefCounted` objects from being freed.1883void GDScriptCompiler::_clear_block_locals(CodeGen &codegen, const List<GDScriptCodeGenerator::Address> &p_locals) {1884for (const GDScriptCodeGenerator::Address &local : p_locals) {1885if (local.type.can_contain_object()) {1886codegen.generator->clear_address(local);1887}1888}1889}18901891Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals, bool p_clear_locals) {1892Error err = OK;1893GDScriptCodeGenerator *gen = codegen.generator;1894List<GDScriptCodeGenerator::Address> block_locals;18951896gen->clear_temporaries();1897codegen.start_block();18981899if (p_add_locals) {1900block_locals = _add_block_locals(codegen, p_block);1901}19021903for (int i = 0; i < p_block->statements.size(); i++) {1904const GDScriptParser::Node *s = p_block->statements[i];19051906gen->write_newline(s->start_line);19071908switch (s->type) {1909case GDScriptParser::Node::MATCH: {1910const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(s);19111912codegen.start_block(); // Add an extra block, since @special locals belong to the match scope.19131914// Evaluate the match expression.1915GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype(), codegen.script));1916GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, err, match->test);1917if (err) {1918return err;1919}19201921// Assign to local.1922// TODO: This can be improved by passing the target to parse_expression().1923gen->write_assign(value, value_expr);19241925if (value_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1926codegen.generator->pop_temporary();1927}19281929// Then, let's save the type of the value in the stack too, so we can reuse for later comparisons.1930GDScriptDataType typeof_type;1931typeof_type.has_type = true;1932typeof_type.kind = GDScriptDataType::BUILTIN;1933typeof_type.builtin_type = Variant::INT;1934GDScriptCodeGenerator::Address type = codegen.add_local("@match_type", typeof_type);19351936Vector<GDScriptCodeGenerator::Address> typeof_args;1937typeof_args.push_back(value);1938gen->write_call_utility(type, "typeof", typeof_args);19391940// Now we can actually start testing.1941// For each branch.1942for (int j = 0; j < match->branches.size(); j++) {1943if (j > 0) {1944// Use `else` to not check the next branch after matching.1945gen->write_else();1946}19471948const GDScriptParser::MatchBranchNode *branch = match->branches[j];19491950codegen.start_block(); // Add an extra block, since binds belong to the match branch scope.19511952// Add locals in block before patterns, so temporaries don't use the stack address for binds.1953List<GDScriptCodeGenerator::Address> branch_locals = _add_block_locals(codegen, branch->block);19541955gen->write_newline(branch->start_line);19561957// For each pattern in branch.1958GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary();1959for (int k = 0; k < branch->patterns.size(); k++) {1960pattern_result = _parse_match_pattern(codegen, err, branch->patterns[k], value, type, pattern_result, k == 0, false);1961if (err != OK) {1962return err;1963}1964}19651966// If there's a guard, check its condition too.1967if (branch->guard_body != nullptr) {1968// Do this first so the guard does not run unless the pattern matched.1969gen->write_and_left_operand(pattern_result);19701971// Don't actually use the block for the guard.1972// 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.1973GDScriptCodeGenerator::Address guard_result = _parse_expression(codegen, err, static_cast<GDScriptParser::ExpressionNode *>(branch->guard_body->statements[0]));1974if (err) {1975return err;1976}19771978gen->write_and_right_operand(guard_result);1979gen->write_end_and(pattern_result);19801981if (guard_result.mode == GDScriptCodeGenerator::Address::TEMPORARY) {1982codegen.generator->pop_temporary();1983}1984}19851986// Check if pattern did match.1987gen->write_if(pattern_result);19881989// Remove the result from stack.1990gen->pop_temporary();19911992// Parse the branch block.1993err = _parse_block(codegen, branch->block, false); // Don't add locals again.1994if (err) {1995return err;1996}19971998_clear_block_locals(codegen, branch_locals);19992000codegen.end_block(); // Get out of extra block for binds.2001}20022003// End all nested `if`s.2004for (int j = 0; j < match->branches.size(); j++) {2005gen->write_endif();2006}20072008codegen.end_block(); // Get out of extra block for match's @special locals.2009} break;2010case GDScriptParser::Node::IF: {2011const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s);2012GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, if_n->condition);2013if (err) {2014return err;2015}20162017gen->write_if(condition);20182019if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2020codegen.generator->pop_temporary();2021}20222023err = _parse_block(codegen, if_n->true_block);2024if (err) {2025return err;2026}20272028if (if_n->false_block) {2029gen->write_else();20302031err = _parse_block(codegen, if_n->false_block);2032if (err) {2033return err;2034}2035}20362037gen->write_endif();2038} break;2039case GDScriptParser::Node::FOR: {2040const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s);20412042// Add an extra block, since the iterator and @special locals belong to the loop scope.2043// Also we use custom logic to clear block locals.2044codegen.start_block();20452046GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype(), codegen.script));20472048// Optimize `range()` call to not allocate an array.2049GDScriptParser::CallNode *range_call = nullptr;2050if (for_n->list && for_n->list->type == GDScriptParser::Node::CALL) {2051GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(for_n->list);2052if (call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {2053if (static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name == "range") {2054range_call = call;2055}2056}2057}20582059gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype(), codegen.script), range_call != nullptr);20602061if (range_call != nullptr) {2062Vector<GDScriptCodeGenerator::Address> args;2063args.resize(range_call->arguments.size());20642065for (int j = 0; j < args.size(); j++) {2066args.write[j] = _parse_expression(codegen, err, range_call->arguments[j]);2067if (err) {2068return err;2069}2070}20712072switch (args.size()) {2073case 1:2074gen->write_for_range_assignment(codegen.add_constant(0), args[0], codegen.add_constant(1));2075break;2076case 2:2077gen->write_for_range_assignment(args[0], args[1], codegen.add_constant(1));2078break;2079case 3:2080gen->write_for_range_assignment(args[0], args[1], args[2]);2081break;2082default:2083_set_error(R"*(Analyzer bug: Wrong "range()" argument count.)*", range_call);2084return ERR_BUG;2085}20862087for (int j = 0; j < args.size(); j++) {2088if (args[j].mode == GDScriptCodeGenerator::Address::TEMPORARY) {2089codegen.generator->pop_temporary();2090}2091}2092} else {2093GDScriptCodeGenerator::Address list = _parse_expression(codegen, err, for_n->list);2094if (err) {2095return err;2096}20972098gen->write_for_list_assignment(list);20992100if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2101codegen.generator->pop_temporary();2102}2103}21042105gen->write_for(iterator, for_n->use_conversion_assign, range_call != nullptr);21062107// Loop variables must be cleared even when `break`/`continue` is used.2108List<GDScriptCodeGenerator::Address> loop_locals = _add_block_locals(codegen, for_n->loop);21092110//_clear_block_locals(codegen, loop_locals); // Inside loop, before block - for `continue`. // TODO21112112err = _parse_block(codegen, for_n->loop, false); // Don't add locals again.2113if (err) {2114return err;2115}21162117gen->write_endfor(range_call != nullptr);21182119_clear_block_locals(codegen, loop_locals); // Outside loop, after block - for `break` and normal exit.21202121codegen.end_block(); // Get out of extra block for loop iterator, @special locals, and custom locals clearing.2122} break;2123case GDScriptParser::Node::WHILE: {2124const GDScriptParser::WhileNode *while_n = static_cast<const GDScriptParser::WhileNode *>(s);21252126codegen.start_block(); // Add an extra block, since we use custom logic to clear block locals.21272128gen->start_while_condition();21292130GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, while_n->condition);2131if (err) {2132return err;2133}21342135gen->write_while(condition);21362137if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2138codegen.generator->pop_temporary();2139}21402141// Loop variables must be cleared even when `break`/`continue` is used.2142List<GDScriptCodeGenerator::Address> loop_locals = _add_block_locals(codegen, while_n->loop);21432144//_clear_block_locals(codegen, loop_locals); // Inside loop, before block - for `continue`. // TODO21452146err = _parse_block(codegen, while_n->loop, false); // Don't add locals again.2147if (err) {2148return err;2149}21502151gen->write_endwhile();21522153_clear_block_locals(codegen, loop_locals); // Outside loop, after block - for `break` and normal exit.21542155codegen.end_block(); // Get out of extra block for custom locals clearing.2156} break;2157case GDScriptParser::Node::BREAK: {2158gen->write_break();2159} break;2160case GDScriptParser::Node::CONTINUE: {2161gen->write_continue();2162} break;2163case GDScriptParser::Node::RETURN: {2164const GDScriptParser::ReturnNode *return_n = static_cast<const GDScriptParser::ReturnNode *>(s);21652166GDScriptCodeGenerator::Address return_value;21672168if (return_n->return_value != nullptr) {2169return_value = _parse_expression(codegen, err, return_n->return_value);2170if (err) {2171return err;2172}2173}21742175if (return_n->void_return) {2176// Always return "null", even if the expression is a call to a void function.2177gen->write_return(codegen.add_constant(Variant()));2178} else {2179gen->write_return(return_value);2180}2181if (return_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2182codegen.generator->pop_temporary();2183}2184} break;2185case GDScriptParser::Node::ASSERT: {2186#ifdef DEBUG_ENABLED2187const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s);21882189GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, as->condition);2190if (err) {2191return err;2192}21932194GDScriptCodeGenerator::Address message;21952196if (as->message) {2197message = _parse_expression(codegen, err, as->message);2198if (err) {2199return err;2200}2201}2202gen->write_assert(condition, message);22032204if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2205codegen.generator->pop_temporary();2206}2207if (message.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2208codegen.generator->pop_temporary();2209}2210#endif2211} break;2212case GDScriptParser::Node::BREAKPOINT: {2213#ifdef DEBUG_ENABLED2214gen->write_breakpoint();2215#endif2216} break;2217case GDScriptParser::Node::VARIABLE: {2218const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s);2219// Should be already in stack when the block began.2220GDScriptCodeGenerator::Address local = codegen.locals[lv->identifier->name];2221GDScriptDataType local_type = _gdtype_from_datatype(lv->get_datatype(), codegen.script);22222223bool initialized = false;2224if (lv->initializer != nullptr) {2225GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, err, lv->initializer);2226if (err) {2227return err;2228}2229if (lv->use_conversion_assign) {2230gen->write_assign_with_conversion(local, src_address);2231} else {2232gen->write_assign(local, src_address);2233}2234if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2235codegen.generator->pop_temporary();2236}2237initialized = true;2238} else if ((local_type.has_type && local_type.kind == GDScriptDataType::BUILTIN) || codegen.generator->is_local_dirty(local)) {2239// Initialize with default for the type. Built-in types must always be cleared (they cannot be `null`).2240// Objects and untyped variables are assigned to `null` only if the stack address has been reused and not cleared.2241codegen.generator->clear_address(local);2242initialized = true;2243}22442245// Don't check `is_local_dirty()` since the variable must be assigned to `null` **on each iteration**.2246if (!initialized && p_block->is_in_loop) {2247codegen.generator->clear_address(local);2248}2249} break;2250case GDScriptParser::Node::CONSTANT: {2251// Local constants.2252const GDScriptParser::ConstantNode *lc = static_cast<const GDScriptParser::ConstantNode *>(s);2253if (!lc->initializer->is_constant) {2254_set_error("Local constant must have a constant value as initializer.", lc->initializer);2255return ERR_PARSE_ERROR;2256}22572258codegen.add_local_constant(lc->identifier->name, lc->initializer->reduced_value);2259} break;2260case GDScriptParser::Node::PASS:2261// Nothing to do.2262break;2263default: {2264// Expression.2265if (s->is_expression()) {2266GDScriptCodeGenerator::Address expr = _parse_expression(codegen, err, static_cast<const GDScriptParser::ExpressionNode *>(s), true);2267if (err) {2268return err;2269}2270if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2271codegen.generator->pop_temporary();2272}2273} else {2274_set_error("Compiler bug (please report): unexpected node in parse tree while parsing statement.", s); // Unreachable code.2275return ERR_INVALID_DATA;2276}2277} break;2278}22792280gen->clear_temporaries();2281}22822283if (p_add_locals && p_clear_locals) {2284_clear_block_locals(codegen, block_locals);2285}22862287codegen.end_block();2288return OK;2289}22902291GDScriptFunction *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) {2292r_error = OK;2293CodeGen codegen;2294codegen.generator = memnew(GDScriptByteCodeGenerator);22952296codegen.class_node = p_class;2297codegen.script = p_script;2298codegen.function_node = p_func;22992300StringName func_name;2301bool is_abstract = false;2302bool is_static = false;2303Variant rpc_config;2304GDScriptDataType return_type;2305return_type.has_type = true;2306return_type.kind = GDScriptDataType::BUILTIN;2307return_type.builtin_type = Variant::NIL;23082309if (p_func) {2310if (p_func->identifier) {2311func_name = p_func->identifier->name;2312} else {2313func_name = "<anonymous lambda>";2314}2315is_abstract = p_func->is_abstract;2316is_static = p_func->is_static;2317rpc_config = p_func->rpc_config;2318return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);2319} else {2320if (p_for_ready) {2321func_name = "@implicit_ready";2322} else {2323func_name = "@implicit_new";2324}2325}23262327MethodInfo method_info;23282329codegen.function_name = func_name;2330method_info.name = func_name;2331codegen.is_static = is_static;2332if (is_abstract) {2333method_info.flags |= METHOD_FLAG_VIRTUAL_REQUIRED;2334}2335if (is_static) {2336method_info.flags |= METHOD_FLAG_STATIC;2337}2338codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type);23392340int optional_parameters = 0;2341GDScriptCodeGenerator::Address vararg_addr;23422343if (p_func) {2344for (int i = 0; i < p_func->parameters.size(); i++) {2345const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];2346GDScriptDataType par_type = _gdtype_from_datatype(parameter->get_datatype(), p_script);2347uint32_t par_addr = codegen.generator->add_parameter(parameter->identifier->name, parameter->initializer != nullptr, par_type);2348codegen.parameters[parameter->identifier->name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::FUNCTION_PARAMETER, par_addr, par_type);23492350method_info.arguments.push_back(parameter->get_datatype().to_property_info(parameter->identifier->name));23512352if (parameter->initializer != nullptr) {2353optional_parameters++;2354}2355}23562357if (p_func->is_vararg()) {2358vararg_addr = codegen.add_local(p_func->rest_parameter->identifier->name, _gdtype_from_datatype(p_func->rest_parameter->get_datatype(), codegen.script));2359method_info.flags |= METHOD_FLAG_VARARG;2360}23612362method_info.default_arguments.append_array(p_func->default_arg_values);2363}23642365// Parse initializer if applies.2366bool is_implicit_initializer = !p_for_ready && !p_func && !p_for_lambda;2367bool is_initializer = p_func && !p_for_lambda && p_func->identifier->name == GDScriptLanguage::get_singleton()->strings._init;2368bool is_implicit_ready = !p_func && p_for_ready;23692370if (!p_for_lambda && is_implicit_initializer) {2371// Initialize the default values for typed variables before anything.2372// This avoids crashes if they are accessed with validated calls before being properly initialized.2373// It may happen with out-of-order access or with `@onready` variables.2374for (const GDScriptParser::ClassNode::Member &member : p_class->members) {2375if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {2376continue;2377}23782379const GDScriptParser::VariableNode *field = member.variable;2380if (field->is_static) {2381continue;2382}23832384GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2385if (field_type.has_type) {2386codegen.generator->write_newline(field->start_line);23872388GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, field_type);23892390if (field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type(0)) {2391codegen.generator->write_construct_typed_array(dst_address, field_type.get_container_element_type(0), Vector<GDScriptCodeGenerator::Address>());2392} else if (field_type.builtin_type == Variant::DICTIONARY && field_type.has_container_element_types()) {2393codegen.generator->write_construct_typed_dictionary(dst_address, field_type.get_container_element_type_or_variant(0),2394field_type.get_container_element_type_or_variant(1), Vector<GDScriptCodeGenerator::Address>());2395} else if (field_type.kind == GDScriptDataType::BUILTIN) {2396codegen.generator->write_construct(dst_address, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());2397}2398// The `else` branch is for objects, in such case we leave it as `null`.2399}2400}2401}24022403if (!p_for_lambda && (is_implicit_initializer || is_implicit_ready)) {2404// Initialize class fields.2405for (int i = 0; i < p_class->members.size(); i++) {2406if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {2407continue;2408}2409const GDScriptParser::VariableNode *field = p_class->members[i].variable;2410if (field->is_static) {2411continue;2412}24132414if (field->onready != is_implicit_ready) {2415// Only initialize in `@implicit_ready()`.2416continue;2417}24182419if (field->initializer) {2420codegen.generator->write_newline(field->initializer->start_line);24212422GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true);2423if (r_error) {2424memdelete(codegen.generator);2425return nullptr;2426}24272428GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2429GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, field_type);24302431if (field->use_conversion_assign) {2432codegen.generator->write_assign_with_conversion(dst_address, src_address);2433} else {2434codegen.generator->write_assign(dst_address, src_address);2435}2436if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2437codegen.generator->pop_temporary();2438}2439}2440}2441}24422443// Parse default argument code if applies.2444if (p_func) {2445if (optional_parameters > 0) {2446codegen.generator->start_parameters();2447for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) {2448const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];2449GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, r_error, parameter->initializer);2450if (r_error) {2451memdelete(codegen.generator);2452return nullptr;2453}2454GDScriptCodeGenerator::Address dst_addr = codegen.parameters[parameter->identifier->name];2455codegen.generator->write_assign_default_parameter(dst_addr, src_addr, parameter->use_conversion_assign);2456if (src_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2457codegen.generator->pop_temporary();2458}2459}2460codegen.generator->end_parameters();2461}24622463// No need to reset locals at the end of the function, the stack will be cleared anyway.2464r_error = _parse_block(codegen, p_func->body, true, false);2465if (r_error) {2466memdelete(codegen.generator);2467return nullptr;2468}2469}24702471#ifdef DEBUG_ENABLED2472if (EngineDebugger::is_active()) {2473String signature;2474// Path.2475if (!p_script->get_script_path().is_empty()) {2476signature += p_script->get_script_path();2477}2478// Location.2479if (p_func) {2480signature += "::" + itos(p_func->body->start_line);2481} else {2482signature += "::0";2483}24842485// Function and class.24862487if (p_class->identifier) {2488signature += "::" + String(p_class->identifier->name) + "." + String(func_name);2489} else {2490signature += "::" + String(func_name);2491}24922493if (p_for_lambda) {2494signature += "(lambda)";2495}24962497codegen.generator->set_signature(signature);2498}2499#endif25002501if (p_func) {2502codegen.generator->set_initial_line(p_func->start_line);2503} else {2504codegen.generator->set_initial_line(0);2505}25062507GDScriptFunction *gd_function = codegen.generator->write_end();25082509if (is_initializer) {2510p_script->initializer = gd_function;2511} else if (is_implicit_initializer) {2512p_script->implicit_initializer = gd_function;2513} else if (is_implicit_ready) {2514p_script->implicit_ready = gd_function;2515}25162517if (p_func) {2518// If no `return` statement, then return type is `void`, not `Variant`.2519if (p_func->body->has_return) {2520gd_function->return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);2521method_info.return_val = p_func->get_datatype().to_property_info(String());2522} else {2523gd_function->return_type = GDScriptDataType();2524gd_function->return_type.has_type = true;2525gd_function->return_type.kind = GDScriptDataType::BUILTIN;2526gd_function->return_type.builtin_type = Variant::NIL;2527}25282529if (p_func->is_vararg()) {2530gd_function->_vararg_index = vararg_addr.address;2531}2532}25332534gd_function->method_info = method_info;25352536if (!is_implicit_initializer && !is_implicit_ready && !p_for_lambda) {2537p_script->member_functions[func_name] = gd_function;2538}25392540memdelete(codegen.generator);25412542return gd_function;2543}25442545GDScriptFunction *GDScriptCompiler::_make_static_initializer(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class) {2546r_error = OK;2547CodeGen codegen;2548codegen.generator = memnew(GDScriptByteCodeGenerator);25492550codegen.class_node = p_class;2551codegen.script = p_script;25522553StringName func_name = SNAME("@static_initializer");2554bool is_static = true;2555Variant rpc_config;2556GDScriptDataType return_type;2557return_type.has_type = true;2558return_type.kind = GDScriptDataType::BUILTIN;2559return_type.builtin_type = Variant::NIL;25602561codegen.function_name = func_name;2562codegen.is_static = is_static;2563codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type);25642565// The static initializer is always called on the same class where the static variables are defined,2566// so the CLASS address (current class) can be used instead of `codegen.add_constant(p_script)`.2567GDScriptCodeGenerator::Address class_addr(GDScriptCodeGenerator::Address::CLASS);25682569// Initialize the default values for typed variables before anything.2570// This avoids crashes if they are accessed with validated calls before being properly initialized.2571// It may happen with out-of-order access or with `@onready` variables.2572for (const GDScriptParser::ClassNode::Member &member : p_class->members) {2573if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {2574continue;2575}25762577const GDScriptParser::VariableNode *field = member.variable;2578if (!field->is_static) {2579continue;2580}25812582GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2583if (field_type.has_type) {2584codegen.generator->write_newline(field->start_line);25852586if (field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type(0)) {2587GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2588codegen.generator->write_construct_typed_array(temp, field_type.get_container_element_type(0), Vector<GDScriptCodeGenerator::Address>());2589codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2590codegen.generator->pop_temporary();2591} else if (field_type.builtin_type == Variant::DICTIONARY && field_type.has_container_element_types()) {2592GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2593codegen.generator->write_construct_typed_dictionary(temp, field_type.get_container_element_type_or_variant(0),2594field_type.get_container_element_type_or_variant(1), Vector<GDScriptCodeGenerator::Address>());2595codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2596codegen.generator->pop_temporary();2597} else if (field_type.kind == GDScriptDataType::BUILTIN) {2598GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);2599codegen.generator->write_construct(temp, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());2600codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2601codegen.generator->pop_temporary();2602}2603// The `else` branch is for objects, in such case we leave it as `null`.2604}2605}26062607for (int i = 0; i < p_class->members.size(); i++) {2608// Initialize static fields.2609if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {2610continue;2611}2612const GDScriptParser::VariableNode *field = p_class->members[i].variable;2613if (!field->is_static) {2614continue;2615}26162617if (field->initializer) {2618codegen.generator->write_newline(field->initializer->start_line);26192620GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true);2621if (r_error) {2622memdelete(codegen.generator);2623return nullptr;2624}26252626GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script);2627GDScriptCodeGenerator::Address temp = codegen.add_temporary(field_type);26282629if (field->use_conversion_assign) {2630codegen.generator->write_assign_with_conversion(temp, src_address);2631} else {2632codegen.generator->write_assign(temp, src_address);2633}2634if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {2635codegen.generator->pop_temporary();2636}26372638codegen.generator->write_set_static_variable(temp, class_addr, p_script->static_variables_indices[field->identifier->name].index);2639codegen.generator->pop_temporary();2640}2641}26422643if (p_script->has_method(GDScriptLanguage::get_singleton()->strings._static_init)) {2644codegen.generator->write_newline(p_class->start_line);2645codegen.generator->write_call(GDScriptCodeGenerator::Address(), class_addr, GDScriptLanguage::get_singleton()->strings._static_init, Vector<GDScriptCodeGenerator::Address>());2646}26472648#ifdef DEBUG_ENABLED2649if (EngineDebugger::is_active()) {2650String signature;2651// Path.2652if (!p_script->get_script_path().is_empty()) {2653signature += p_script->get_script_path();2654}2655// Location.2656signature += "::0";26572658// Function and class.26592660if (p_class->identifier) {2661signature += "::" + String(p_class->identifier->name) + "." + String(func_name);2662} else {2663signature += "::" + String(func_name);2664}26652666codegen.generator->set_signature(signature);2667}2668#endif26692670codegen.generator->set_initial_line(p_class->start_line);26712672GDScriptFunction *gd_function = codegen.generator->write_end();26732674memdelete(codegen.generator);26752676return gd_function;2677}26782679Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) {2680Error err = OK;26812682GDScriptParser::FunctionNode *function;26832684if (p_is_setter) {2685function = p_variable->setter;2686} else {2687function = p_variable->getter;2688}26892690_parse_function(err, p_script, p_class, function);26912692return err;2693}26942695// Prepares given script, and inner class scripts, for compilation. It populates class members and2696// initializes method RPC info for its base classes first, then for itself, then for inner classes.2697// WARNING: This function cannot initiate compilation of other classes, or it will result in2698// cyclic dependency issues.2699Error GDScriptCompiler::_prepare_compilation(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {2700if (parsed_classes.has(p_script)) {2701return OK;2702}27032704if (parsing_classes.has(p_script)) {2705String class_name = p_class->identifier ? String(p_class->identifier->name) : p_class->fqcn;2706_set_error(vformat(R"(Cyclic class reference for "%s".)", class_name), p_class);2707return ERR_PARSE_ERROR;2708}27092710parsing_classes.insert(p_script);27112712p_script->clearing = true;27132714p_script->cancel_pending_functions(true);27152716p_script->native = Ref<GDScriptNativeClass>();2717p_script->base = Ref<GDScript>();2718p_script->_base = nullptr;2719p_script->members.clear();27202721// This makes possible to clear script constants and member_functions without heap-use-after-free errors.2722HashMap<StringName, Variant> constants;2723for (const KeyValue<StringName, Variant> &E : p_script->constants) {2724constants.insert(E.key, E.value);2725}2726p_script->constants.clear();2727constants.clear();2728HashMap<StringName, GDScriptFunction *> member_functions;2729for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->member_functions) {2730member_functions.insert(E.key, E.value);2731}2732p_script->member_functions.clear();2733for (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {2734memdelete(E.value);2735}2736member_functions.clear();27372738p_script->static_variables.clear();27392740if (p_script->implicit_initializer) {2741memdelete(p_script->implicit_initializer);2742}2743if (p_script->implicit_ready) {2744memdelete(p_script->implicit_ready);2745}2746if (p_script->static_initializer) {2747memdelete(p_script->static_initializer);2748}27492750p_script->member_functions.clear();2751p_script->member_indices.clear();2752p_script->static_variables_indices.clear();2753p_script->static_variables.clear();2754p_script->_signals.clear();2755p_script->initializer = nullptr;2756p_script->implicit_initializer = nullptr;2757p_script->implicit_ready = nullptr;2758p_script->static_initializer = nullptr;2759p_script->rpc_config.clear();2760p_script->lambda_info.clear();27612762p_script->clearing = false;27632764p_script->tool = parser->is_tool();2765p_script->_is_abstract = p_class->is_abstract;27662767if (p_script->local_name != StringName()) {2768if (ClassDB::class_exists(p_script->local_name) && ClassDB::is_class_exposed(p_script->local_name)) {2769_set_error(vformat(R"(The class "%s" shadows a native class)", p_script->local_name), p_class);2770return ERR_ALREADY_EXISTS;2771}2772}27732774GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type, p_script, false);27752776if (base_type.native_type == StringName()) {2777_set_error(vformat(R"(Parser bug (please report): Empty native type in base class "%s")", p_script->path), p_class);2778return ERR_BUG;2779}27802781int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[base_type.native_type];27822783p_script->native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx];2784if (p_script->native.is_null()) {2785_set_error("Compiler bug (please report): script native type is null.", nullptr);2786return ERR_BUG;2787}27882789// Inheritance2790switch (base_type.kind) {2791case GDScriptDataType::NATIVE:2792// Nothing more to do.2793break;2794case GDScriptDataType::GDSCRIPT: {2795Ref<GDScript> base = Ref<GDScript>(base_type.script_type);2796if (base.is_null()) {2797_set_error("Compiler bug (please report): base script type is null.", nullptr);2798return ERR_BUG;2799}28002801if (main_script->has_class(base.ptr())) {2802Error err = _prepare_compilation(base.ptr(), p_class->base_type.class_type, p_keep_state);2803if (err) {2804return err;2805}2806} else if (!base->is_valid()) {2807Error err = OK;2808Ref<GDScript> base_root = GDScriptCache::get_shallow_script(base->path, err, p_script->path);2809if (err) {2810_set_error(vformat(R"(Could not parse base class "%s" from "%s": %s)", base->fully_qualified_name, base->path, error_names[err]), nullptr);2811return err;2812}2813if (base_root.is_valid()) {2814base = Ref<GDScript>(base_root->find_class(base->fully_qualified_name));2815}2816if (base.is_null()) {2817_set_error(vformat(R"(Could not find class "%s" in "%s".)", base->fully_qualified_name, base->path), nullptr);2818return ERR_COMPILATION_FAILED;2819}28202821err = _prepare_compilation(base.ptr(), p_class->base_type.class_type, p_keep_state);2822if (err) {2823_set_error(vformat(R"(Could not populate class members of base class "%s" in "%s".)", base->fully_qualified_name, base->path), nullptr);2824return err;2825}2826}28272828p_script->base = base;2829p_script->_base = base.ptr();2830p_script->member_indices = base->member_indices;2831} break;2832default: {2833_set_error("Parser bug (please report): invalid inheritance.", nullptr);2834return ERR_BUG;2835} break;2836}28372838// Duplicate RPC information from base GDScript2839// Base script isn't valid because it should not have been compiled yet, but the reference contains relevant info.2840if (base_type.kind == GDScriptDataType::GDSCRIPT && p_script->base.is_valid()) {2841p_script->rpc_config = p_script->base->rpc_config.duplicate();2842}28432844for (int i = 0; i < p_class->members.size(); i++) {2845const GDScriptParser::ClassNode::Member &member = p_class->members[i];2846switch (member.type) {2847case GDScriptParser::ClassNode::Member::VARIABLE: {2848const GDScriptParser::VariableNode *variable = member.variable;2849StringName name = variable->identifier->name;28502851GDScript::MemberInfo minfo;2852switch (variable->property) {2853case GDScriptParser::VariableNode::PROP_NONE:2854break; // Nothing to do.2855case GDScriptParser::VariableNode::PROP_SETGET:2856if (variable->setter_pointer != nullptr) {2857minfo.setter = variable->setter_pointer->name;2858}2859if (variable->getter_pointer != nullptr) {2860minfo.getter = variable->getter_pointer->name;2861}2862break;2863case GDScriptParser::VariableNode::PROP_INLINE:2864if (variable->setter != nullptr) {2865minfo.setter = "@" + variable->identifier->name + "_setter";2866}2867if (variable->getter != nullptr) {2868minfo.getter = "@" + variable->identifier->name + "_getter";2869}2870break;2871}2872minfo.data_type = _gdtype_from_datatype(variable->get_datatype(), p_script);28732874PropertyInfo prop_info = variable->get_datatype().to_property_info(name);2875PropertyInfo export_info = variable->export_info;28762877if (variable->exported) {2878if (!minfo.data_type.has_type) {2879prop_info.type = export_info.type;2880prop_info.class_name = export_info.class_name;2881}2882prop_info.hint = export_info.hint;2883prop_info.hint_string = export_info.hint_string;2884prop_info.usage = export_info.usage;2885}2886prop_info.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;2887minfo.property_info = prop_info;28882889if (variable->is_static) {2890minfo.index = p_script->static_variables_indices.size();2891p_script->static_variables_indices[name] = minfo;2892} else {2893minfo.index = p_script->member_indices.size();2894p_script->member_indices[name] = minfo;2895p_script->members.insert(name);2896}28972898#ifdef TOOLS_ENABLED2899if (variable->initializer != nullptr && variable->initializer->is_constant) {2900p_script->member_default_values[name] = variable->initializer->reduced_value;2901GDScriptCompiler::convert_to_initializer_type(p_script->member_default_values[name], variable);2902} else {2903p_script->member_default_values.erase(name);2904}2905#endif2906} break;29072908case GDScriptParser::ClassNode::Member::CONSTANT: {2909const GDScriptParser::ConstantNode *constant = member.constant;2910StringName name = constant->identifier->name;29112912p_script->constants.insert(name, constant->initializer->reduced_value);2913} break;29142915case GDScriptParser::ClassNode::Member::ENUM_VALUE: {2916const GDScriptParser::EnumNode::Value &enum_value = member.enum_value;2917StringName name = enum_value.identifier->name;29182919p_script->constants.insert(name, enum_value.value);2920} break;29212922case GDScriptParser::ClassNode::Member::SIGNAL: {2923const GDScriptParser::SignalNode *signal = member.signal;2924StringName name = signal->identifier->name;29252926p_script->_signals[name] = signal->method_info;2927} break;29282929case GDScriptParser::ClassNode::Member::ENUM: {2930const GDScriptParser::EnumNode *enum_n = member.m_enum;2931StringName name = enum_n->identifier->name;29322933p_script->constants.insert(name, enum_n->dictionary);2934} break;29352936case GDScriptParser::ClassNode::Member::GROUP: {2937const GDScriptParser::AnnotationNode *annotation = member.annotation;2938// Avoid name conflict. See GH-78252.2939StringName name = vformat("@group_%d_%s", p_script->members.size(), annotation->export_info.name);29402941// This is not a normal member, but we need this to keep indices in order.2942GDScript::MemberInfo minfo;2943minfo.index = p_script->member_indices.size();29442945PropertyInfo prop_info;2946prop_info.name = annotation->export_info.name;2947prop_info.usage = annotation->export_info.usage;2948prop_info.hint_string = annotation->export_info.hint_string;2949minfo.property_info = prop_info;29502951p_script->member_indices[name] = minfo;2952p_script->members.insert(name);2953} break;29542955case GDScriptParser::ClassNode::Member::FUNCTION: {2956const GDScriptParser::FunctionNode *function_n = member.function;29572958Variant config = function_n->rpc_config;2959if (config.get_type() != Variant::NIL) {2960p_script->rpc_config[function_n->identifier->name] = config;2961}2962} break;2963default:2964break; // Nothing to do here.2965}2966}29672968p_script->static_variables.resize(p_script->static_variables_indices.size());29692970parsed_classes.insert(p_script);2971parsing_classes.erase(p_script);29722973// Populate inner classes.2974for (int i = 0; i < p_class->members.size(); i++) {2975const GDScriptParser::ClassNode::Member &member = p_class->members[i];2976if (member.type != member.CLASS) {2977continue;2978}2979const GDScriptParser::ClassNode *inner_class = member.m_class;2980StringName name = inner_class->identifier->name;2981Ref<GDScript> &subclass = p_script->subclasses[name];2982GDScript *subclass_ptr = subclass.ptr();29832984// Subclass might still be parsing, just skip it2985if (!parsing_classes.has(subclass_ptr)) {2986Error err = _prepare_compilation(subclass_ptr, inner_class, p_keep_state);2987if (err) {2988return err;2989}2990}29912992p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants2993}29942995return OK;2996}29972998Error GDScriptCompiler::_compile_class(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {2999// Compile member functions, getters, and setters.3000for (int i = 0; i < p_class->members.size(); i++) {3001const GDScriptParser::ClassNode::Member &member = p_class->members[i];3002if (member.type == member.FUNCTION) {3003const GDScriptParser::FunctionNode *function = member.function;3004Error err = OK;3005_parse_function(err, p_script, p_class, function);3006if (err) {3007return err;3008}3009} else if (member.type == member.VARIABLE) {3010const GDScriptParser::VariableNode *variable = member.variable;3011if (variable->property == GDScriptParser::VariableNode::PROP_INLINE) {3012if (variable->setter != nullptr) {3013Error err = _parse_setter_getter(p_script, p_class, variable, true);3014if (err) {3015return err;3016}3017}3018if (variable->getter != nullptr) {3019Error err = _parse_setter_getter(p_script, p_class, variable, false);3020if (err) {3021return err;3022}3023}3024}3025}3026}30273028{3029// Create `@implicit_new()` special function in any case.3030Error err = OK;3031_parse_function(err, p_script, p_class, nullptr);3032if (err) {3033return err;3034}3035}30363037if (p_class->onready_used) {3038// Create `@implicit_ready()` special function.3039Error err = OK;3040_parse_function(err, p_script, p_class, nullptr, true);3041if (err) {3042return err;3043}3044}30453046if (p_class->has_static_data) {3047Error err = OK;3048GDScriptFunction *func = _make_static_initializer(err, p_script, p_class);3049p_script->static_initializer = func;3050if (err) {3051return err;3052}3053}30543055#ifdef DEBUG_ENABLED30563057//validate instances if keeping state30583059if (p_keep_state) {3060for (RBSet<Object *>::Element *E = p_script->instances.front(); E;) {3061RBSet<Object *>::Element *N = E->next();30623063ScriptInstance *si = E->get()->get_script_instance();3064if (si->is_placeholder()) {3065#ifdef TOOLS_ENABLED3066PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si);30673068if (p_script->is_tool()) {3069//re-create as an instance3070p_script->placeholders.erase(psi); //remove placeholder30713072GDScriptInstance *instance = memnew(GDScriptInstance);3073instance->base_ref_counted = Object::cast_to<RefCounted>(E->get());3074instance->members.resize(p_script->member_indices.size());3075instance->script = Ref<GDScript>(p_script);3076instance->owner = E->get();30773078//needed for hot reloading3079for (const KeyValue<StringName, GDScript::MemberInfo> &F : p_script->member_indices) {3080instance->member_indices_cache[F.key] = F.value.index;3081}3082instance->owner->set_script_instance(instance);30833084/* STEP 2, INITIALIZE AND CONSTRUCT */30853086Callable::CallError ce;3087p_script->initializer->call(instance, nullptr, 0, ce);30883089if (ce.error != Callable::CallError::CALL_OK) {3090//well, tough luck, not gonna do anything here3091}3092}3093#endif // TOOLS_ENABLED3094} else {3095GDScriptInstance *gi = static_cast<GDScriptInstance *>(si);3096gi->reload_members();3097}30983099E = N;3100}3101}3102#endif //DEBUG_ENABLED31033104has_static_data = p_class->has_static_data;31053106for (int i = 0; i < p_class->members.size(); i++) {3107if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {3108continue;3109}3110const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;3111StringName name = inner_class->identifier->name;3112GDScript *subclass = p_script->subclasses[name].ptr();31133114Error err = _compile_class(subclass, inner_class, p_keep_state);3115if (err) {3116return err;3117}31183119has_static_data = has_static_data || inner_class->has_static_data;3120}31213122p_script->_static_default_init();31233124p_script->valid = true;3125return OK;3126}31273128void GDScriptCompiler::convert_to_initializer_type(Variant &p_variant, const GDScriptParser::VariableNode *p_node) {3129// Set p_variant to the value of p_node's initializer, with the type of p_node's variable.3130GDScriptParser::DataType member_t = p_node->datatype;3131GDScriptParser::DataType init_t = p_node->initializer->datatype;3132if (member_t.is_hard_type() && init_t.is_hard_type() &&3133member_t.kind == GDScriptParser::DataType::BUILTIN && init_t.kind == GDScriptParser::DataType::BUILTIN) {3134if (Variant::can_convert_strict(init_t.builtin_type, member_t.builtin_type)) {3135const Variant *v = &p_node->initializer->reduced_value;3136Callable::CallError ce;3137Variant::construct(member_t.builtin_type, p_variant, &v, 1, ce);3138}3139}3140}31413142void GDScriptCompiler::make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {3143p_script->fully_qualified_name = p_class->fqcn;3144p_script->local_name = p_class->identifier ? p_class->identifier->name : StringName();3145p_script->global_name = p_class->get_global_name();3146p_script->simplified_icon_path = p_class->simplified_icon_path;31473148HashMap<StringName, Ref<GDScript>> old_subclasses;31493150if (p_keep_state) {3151old_subclasses = p_script->subclasses;3152}31533154p_script->subclasses.clear();31553156for (int i = 0; i < p_class->members.size(); i++) {3157if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {3158continue;3159}3160const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;3161StringName name = inner_class->identifier->name;31623163Ref<GDScript> subclass;31643165if (old_subclasses.has(name)) {3166subclass = old_subclasses[name];3167} else {3168subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(inner_class->fqcn);3169}31703171if (subclass.is_null()) {3172subclass.instantiate();3173}31743175subclass->_owner = p_script;3176subclass->path = p_script->path;3177p_script->subclasses.insert(name, subclass);31783179make_scripts(subclass.ptr(), inner_class, p_keep_state);3180}3181}31823183GDScriptCompiler::FunctionLambdaInfo GDScriptCompiler::_get_function_replacement_info(GDScriptFunction *p_func, int p_index, int p_depth, GDScriptFunction *p_parent_func) {3184FunctionLambdaInfo info;3185info.function = p_func;3186info.parent = p_parent_func;3187info.script = p_func->get_script();3188info.name = p_func->get_name();3189info.line = p_func->_initial_line;3190info.index = p_index;3191info.depth = p_depth;3192info.capture_count = 0;3193info.use_self = false;3194info.arg_count = p_func->_argument_count;3195info.default_arg_count = p_func->_default_arg_count;3196info.sublambdas = _get_function_lambda_replacement_info(p_func, p_depth, p_parent_func);31973198ERR_FAIL_NULL_V(info.script, info);3199GDScript::LambdaInfo *extra_info = info.script->lambda_info.getptr(p_func);3200if (extra_info != nullptr) {3201info.capture_count = extra_info->capture_count;3202info.use_self = extra_info->use_self;3203} else {3204info.capture_count = 0;3205info.use_self = false;3206}32073208return info;3209}32103211Vector<GDScriptCompiler::FunctionLambdaInfo> GDScriptCompiler::_get_function_lambda_replacement_info(GDScriptFunction *p_func, int p_depth, GDScriptFunction *p_parent_func) {3212Vector<FunctionLambdaInfo> result;3213// Only scrape the lambdas inside p_func.3214for (int i = 0; i < p_func->lambdas.size(); ++i) {3215result.push_back(_get_function_replacement_info(p_func->lambdas[i], i, p_depth + 1, p_func));3216}3217return result;3218}32193220GDScriptCompiler::ScriptLambdaInfo GDScriptCompiler::_get_script_lambda_replacement_info(GDScript *p_script) {3221ScriptLambdaInfo info;32223223if (p_script->implicit_initializer) {3224info.implicit_initializer_info = _get_function_lambda_replacement_info(p_script->implicit_initializer);3225}3226if (p_script->implicit_ready) {3227info.implicit_ready_info = _get_function_lambda_replacement_info(p_script->implicit_ready);3228}3229if (p_script->static_initializer) {3230info.static_initializer_info = _get_function_lambda_replacement_info(p_script->static_initializer);3231}32323233for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->member_functions) {3234info.member_function_infos.insert(E.key, _get_function_lambda_replacement_info(E.value));3235}32363237for (const KeyValue<StringName, Ref<GDScript>> &KV : p_script->get_subclasses()) {3238info.subclass_info.insert(KV.key, _get_script_lambda_replacement_info(KV.value.ptr()));3239}32403241return info;3242}32433244bool GDScriptCompiler::_do_function_infos_match(const FunctionLambdaInfo &p_old_info, const FunctionLambdaInfo *p_new_info) {3245if (p_new_info == nullptr) {3246return false;3247}32483249if (p_new_info->capture_count != p_old_info.capture_count || p_new_info->use_self != p_old_info.use_self) {3250return false;3251}32523253int old_required_arg_count = p_old_info.arg_count - p_old_info.default_arg_count;3254int new_required_arg_count = p_new_info->arg_count - p_new_info->default_arg_count;3255if (new_required_arg_count > old_required_arg_count || p_new_info->arg_count < old_required_arg_count) {3256return false;3257}32583259return true;3260}32613262void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const FunctionLambdaInfo &p_old_info, const FunctionLambdaInfo *p_new_info) {3263ERR_FAIL_COND(r_replacements.has(p_old_info.function));3264if (!_do_function_infos_match(p_old_info, p_new_info)) {3265p_new_info = nullptr;3266}32673268r_replacements.insert(p_old_info.function, p_new_info != nullptr ? p_new_info->function : nullptr);3269_get_function_ptr_replacements(r_replacements, p_old_info.sublambdas, p_new_info != nullptr ? &p_new_info->sublambdas : nullptr);3270}32713272void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const Vector<FunctionLambdaInfo> &p_old_infos, const Vector<FunctionLambdaInfo> *p_new_infos) {3273for (int i = 0; i < p_old_infos.size(); ++i) {3274const FunctionLambdaInfo &old_info = p_old_infos[i];3275const FunctionLambdaInfo *new_info = nullptr;3276if (p_new_infos != nullptr && p_new_infos->size() == p_old_infos.size()) {3277// For now only attempt if the size is the same.3278new_info = &p_new_infos->get(i);3279}3280_get_function_ptr_replacements(r_replacements, old_info, new_info);3281}3282}32833284void GDScriptCompiler::_get_function_ptr_replacements(HashMap<GDScriptFunction *, GDScriptFunction *> &r_replacements, const ScriptLambdaInfo &p_old_info, const ScriptLambdaInfo *p_new_info) {3285_get_function_ptr_replacements(r_replacements, p_old_info.implicit_initializer_info, p_new_info != nullptr ? &p_new_info->implicit_initializer_info : nullptr);3286_get_function_ptr_replacements(r_replacements, p_old_info.implicit_ready_info, p_new_info != nullptr ? &p_new_info->implicit_ready_info : nullptr);3287_get_function_ptr_replacements(r_replacements, p_old_info.static_initializer_info, p_new_info != nullptr ? &p_new_info->static_initializer_info : nullptr);32883289for (const KeyValue<StringName, Vector<FunctionLambdaInfo>> &old_kv : p_old_info.member_function_infos) {3290_get_function_ptr_replacements(r_replacements, old_kv.value, p_new_info != nullptr ? p_new_info->member_function_infos.getptr(old_kv.key) : nullptr);3291}3292for (int i = 0; i < p_old_info.other_function_infos.size(); ++i) {3293const FunctionLambdaInfo &old_other_info = p_old_info.other_function_infos[i];3294const FunctionLambdaInfo *new_other_info = nullptr;3295if (p_new_info != nullptr && p_new_info->other_function_infos.size() == p_old_info.other_function_infos.size()) {3296// For now only attempt if the size is the same.3297new_other_info = &p_new_info->other_function_infos[i];3298}3299// Needs to be called on all old lambdas, even if there's no replacement.3300_get_function_ptr_replacements(r_replacements, old_other_info, new_other_info);3301}3302for (const KeyValue<StringName, ScriptLambdaInfo> &old_kv : p_old_info.subclass_info) {3303const ScriptLambdaInfo &old_subinfo = old_kv.value;3304const ScriptLambdaInfo *new_subinfo = p_new_info != nullptr ? p_new_info->subclass_info.getptr(old_kv.key) : nullptr;3305_get_function_ptr_replacements(r_replacements, old_subinfo, new_subinfo);3306}3307}33083309Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) {3310err_line = -1;3311err_column = -1;3312error = "";3313parser = p_parser;3314main_script = p_script;3315const GDScriptParser::ClassNode *root = parser->get_tree();33163317source = p_script->get_path();33183319ScriptLambdaInfo old_lambda_info = _get_script_lambda_replacement_info(p_script);33203321// Create scripts for subclasses beforehand so they can be referenced3322make_scripts(p_script, root, p_keep_state);33233324main_script->_owner = nullptr;3325Error err = _prepare_compilation(main_script, parser->get_tree(), p_keep_state);33263327if (err) {3328return err;3329}33303331err = _compile_class(main_script, root, p_keep_state);3332if (err) {3333return err;3334}33353336ScriptLambdaInfo new_lambda_info = _get_script_lambda_replacement_info(p_script);33373338HashMap<GDScriptFunction *, GDScriptFunction *> func_ptr_replacements;3339_get_function_ptr_replacements(func_ptr_replacements, old_lambda_info, &new_lambda_info);3340main_script->_recurse_replace_function_ptrs(func_ptr_replacements);33413342if (has_static_data && !root->annotated_static_unload) {3343GDScriptCache::add_static_script(p_script);3344}33453346err = GDScriptCache::finish_compiling(main_script->path);3347if (err) {3348_set_error(R"(Failed to compile depended scripts.)", nullptr);3349}3350return err;3351}33523353String GDScriptCompiler::get_error() const {3354return error;3355}33563357int GDScriptCompiler::get_error_line() const {3358return err_line;3359}33603361int GDScriptCompiler::get_error_column() const {3362return err_column;3363}33643365GDScriptCompiler::GDScriptCompiler() {3366}336733683369