Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

GDScript: Error when code calls `self.free()`

HolonProduction71693d64ad87
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index 5a560c5772a..29f46f748a5 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -3854,6 +3854,14 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a
}
}
+ // Emit an error if trying to call `self.free()`. While users can easily bypass this error, the risk is high enough to make this a hard error if we can detect it.
+ if (p_call->function_name == CoreStringName(free_) && p_call->get_callee_type() == GDScriptParser::Node::SUBSCRIPT) {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
+ if (subscript->base && subscript->base->type == GDScriptParser::Node::SELF) {
+ push_error(R"*(Calling "self.free()" can lead to bugs and crashes. Consider using "queue_free()" instead.)*", p_call);
+ }
+ }
+
p_call->type_constraint = call_type;
}
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/free_self.gd b/modules/gdscript/tests/scripts/analyzer/errors/free_self.gd
new file mode 100644
index 00000000000..65b030a5561
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/free_self.gd
@@ -0,0 +1,7 @@
+extends Node
+
+func test():
+ var l = func lambda():
+ self.free()
+
+ self.free()
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/free_self.out b/modules/gdscript/tests/scripts/analyzer/errors/free_self.out
new file mode 100644
index 00000000000..a56e6e26a32
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/free_self.out
@@ -0,0 +1,3 @@
+GDTEST_ANALYZER_ERROR
+>> ERROR at line 5: Calling "self.free()" can lead to bugs and crashes. Consider using "queue_free()" instead.
+>> ERROR at line 7: Calling "self.free()" can lead to bugs and crashes. Consider using "queue_free()" instead.