Debian Codegraph @

modules/gdscript/gdscript.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* gdscript.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "gdscript.h"
32
33 #include "gdscript_analyzer.h"
34 #include "gdscript_cache.h"
35 #include "gdscript_compiler.h"
36 #include "gdscript_parser.h"
37 #include "gdscript_rpc_callable.h"
38 #include "gdscript_tokenizer_buffer.h"
39 #include "gdscript_warning.h"
40
41 #ifdef TOOLS_ENABLED
42 #include "editor/gdscript_docgen.h"
43 #endif
44
45 #ifdef TESTS_ENABLED
46 #include "tests/gdscript_test_runner.h"
47 #endif
48
49 #include "core/config/engine.h"
50 #include "core/config/project_settings.h"
51 #include "core/core_constants.h"
52 #include "core/io/file_access.h"
53
54 #include "scene/resources/packed_scene.h"
55 #include "scene/scene_string_names.h"
56
57 #ifdef TOOLS_ENABLED
58 #include "core/extension/gdextension_manager.h"
59 #include "editor/file_system/editor_paths.h"
60 #endif
61
62 ///////////////////////////
63
64 GDScriptNativeClass::GDScriptNativeClass(const StringName &p_name) {
65 name = p_name;
66 }
67
68 bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
69 bool ok;
70 int64_t v = ClassDB::get_integer_constant(name, p_name, &ok);
71
72 if (ok) {
73 r_ret = v;
74 return true;
75 }
76
77 MethodBind *method = ClassDB::get_method(name, p_name);
78 if (method && method->is_static()) {
79 // Native static method.
80 r_ret = Callable(this, p_name);
81 return true;
82 }
83
84 return false;
85 }
86
87 void GDScriptNativeClass::_bind_methods() {
88 ClassDB::bind_method(D_METHOD("new"), &GDScriptNativeClass::_new);
89 }
90
91 Variant GDScriptNativeClass::_new() {
92 Object *o = instantiate();
93 ERR_FAIL_NULL_V_MSG(o, Variant(), "Class type: '" + String(name) + "' is not instantiable.");
94
95 RefCounted *rc = Object::cast_to<RefCounted>(o);
96 if (rc) {
97 return Ref<RefCounted>(rc);
98 } else {
99 return o;
100 }
101 }
102
103 Object *GDScriptNativeClass::instantiate() {
104 return ClassDB::instantiate_no_placeholders(name);
105 }
106
107 Variant GDScriptNativeClass::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
108 if (p_method == SNAME("new")) {
109 // Constructor.
110 return Object::callp(p_method, p_args, p_argcount, r_error);
111 }
112 MethodBind *method = ClassDB::get_method(name, p_method);
113 if (method && method->is_static()) {
114 // Native static method.
115 return method->call(nullptr, p_args, p_argcount, r_error);
116 }
117
118 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
119 return Variant();
120 }
121
122 GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) {
123 if (likely(p_script->valid) && p_script->initializer) {
124 return p_script->initializer;
125 } else {
126 GDScript *base_src = p_script->base.ptr();
127 if (base_src != nullptr) {
128 return _super_constructor(base_src);
129 } else {
130 return nullptr;
131 }
132 }
133 }
134
135 void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) {
136 GDScript *base_src = p_script->base.ptr();
137 if (base_src != nullptr) {
138 _super_implicit_constructor(base_src, p_instance, r_error);
139 if (r_error.error != Callable::CallError::CALL_OK) {
140 return;
141 }
142 }
143 ERR_FAIL_NULL(p_script->implicit_initializer);
144 if (likely(p_script->valid)) {
145 p_script->implicit_initializer->call(p_instance, nullptr, 0, r_error);
146 } else {
147 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
148 }
149 }
150
151 GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Callable::CallError &r_error) {
152 /* STEP 1, CREATE */
153
154 GDScriptInstance *instance = memnew(GDScriptInstance);
155 instance->members.resize(member_indices.size());
156 instance->script = Ref<GDScript>(this);
157 instance->owner = p_owner;
158 instance->owner_id = p_owner->get_instance_id();
159 #ifdef DEBUG_ENABLED
160 //needed for hot reloading
161 for (const KeyValue<StringName, MemberInfo> &E : member_indices) {
162 instance->member_indices_cache[E.key] = E.value.index;
163 }
164 #endif
165 instance->owner->set_script_instance(instance);
166
167 /* STEP 2, INITIALIZE AND CONSTRUCT */
168 {
169 MutexLock lock(GDScriptLanguage::singleton->mutex);
170 instances.insert(instance->owner);
171 }
172
173 _super_implicit_constructor(this, instance, r_error);
174 if (r_error.error != Callable::CallError::CALL_OK) {
175 String error_text = Variant::get_call_error_text(instance->owner, "@implicit_new", nullptr, 0, r_error);
176 instance->script = Ref<GDScript>();
177 instance->owner->set_script_instance(nullptr);
178 {
179 MutexLock lock(GDScriptLanguage::singleton->mutex);
180 instances.erase(p_owner);
181 }
182 ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance: " + error_text);
183 }
184
185 if (p_argcount < 0) {
186 return instance;
187 }
188
189 GDScriptFunction *applicable_initializer = _super_constructor(this);
190 if (applicable_initializer != nullptr) {
191 applicable_initializer->call(instance, p_args, p_argcount, r_error);
192 if (r_error.error != Callable::CallError::CALL_OK) {
193 String error_text = Variant::get_call_error_text(instance->owner, "_init", p_args, p_argcount, r_error);
194 instance->script = Ref<GDScript>();
195 instance->owner->set_script_instance(nullptr);
196 {
197 MutexLock lock(GDScriptLanguage::singleton->mutex);
198 instances.erase(p_owner);
199 }
200 ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance: " + error_text);
201 }
202 }
203 //@TODO make thread safe
204 return instance;
205 }
206
207 Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
208 /* STEP 1, CREATE */
209
210 if (!valid) {
211 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
212 return Variant();
213 }
214
215 r_error.error = Callable::CallError::CALL_OK;
216 Ref<RefCounted> ref;
217 Object *owner = nullptr;
218
219 GDScript *_baseptr = this;
220 while (_baseptr->base.ptr()) {
221 _baseptr = _baseptr->base.ptr();
222 }
223
224 ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant());
225 if (_baseptr->native.ptr()) {
226 owner = _baseptr->native->instantiate();
227 } else {
228 owner = memnew(RefCounted); //by default, no base means use reference
229 }
230 ERR_FAIL_NULL_V_MSG(owner, Variant(), "Can't inherit from a virtual class.");
231
232 RefCounted *r = Object::cast_to<RefCounted>(owner);
233 if (r) {
234 ref = Ref<RefCounted>(r);
235 }
236
237 GDScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r_error);
238 if (!instance) {
239 if (ref.is_null()) {
240 memdelete(owner); //no owner, sorry
241 }
242 return Variant();
243 }
244
245 if (ref.is_valid()) {
246 return ref;
247 } else {
248 return owner;
249 }
250 }
251
252 bool GDScript::can_instantiate() const {
253 #ifdef TOOLS_ENABLED
254 return valid && (tool || ScriptServer::is_scripting_enabled()) && !Engine::get_singleton()->is_recovery_mode_hint();
255 #else
256 return valid;
257 #endif
258 }
259
260 Ref<Script> GDScript::get_base_script() const {
261 return base;
262 }
263
264 StringName GDScript::get_global_name() const {
265 return global_name;
266 }
267
268 StringName GDScript::get_instance_base_type() const {
269 if (native.is_valid()) {
270 return native->get_name();
271 }
272 if (base.is_valid() && base->is_valid()) {
273 return base->get_instance_base_type();
274 }
275 return StringName();
276 }
277
278 struct _GDScriptMemberSort {
279 int index = 0;
280 StringName name;
281 _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
282 };
283
284 #ifdef TOOLS_ENABLED
285
286 void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
287 placeholders.erase(p_placeholder);
288 }
289
290 #endif
291
292 void GDScript::_get_script_method_list(List<MethodInfo> *r_list, bool p_include_base) const {
293 const GDScript *current = this;
294 while (current) {
295 for (const KeyValue<StringName, GDScriptFunction *> &E : current->member_functions) {
296 r_list->push_back(E.value->get_method_info());
297 }
298
299 if (!p_include_base) {
300 return;
301 }
302
303 current = current->base.ptr();
304 }
305 }
306
307 void GDScript::get_script_method_list(List<MethodInfo> *r_list) const {
308 _get_script_method_list(r_list, true);
309 }
310
311 void GDScript::_get_script_property_list(List<PropertyInfo> *r_list, bool p_include_base) const {
312 const GDScript *sptr = this;
313 List<PropertyInfo> props;
314
315 while (sptr) {
316 Vector<_GDScriptMemberSort> msort;
317 for (const KeyValue<StringName, MemberInfo> &E : sptr->member_indices) {
318 if (!sptr->members.has(E.key)) {
319 continue; // Skip base class members.
320 }
321 _GDScriptMemberSort ms;
322 ms.index = E.value.index;
323 ms.name = E.key;
324 msort.push_back(ms);
325 }
326
327 msort.sort();
328 msort.reverse();
329 for (int i = 0; i < msort.size(); i++) {
330 props.push_front(sptr->member_indices[msort[i].name].property_info);
331 }
332
333 #ifdef TOOLS_ENABLED
334 r_list->push_back(sptr->get_class_category());
335 #endif // TOOLS_ENABLED
336
337 for (const PropertyInfo &E : props) {
338 r_list->push_back(E);
339 }
340
341 if (!p_include_base) {
342 break;
343 }
344
345 props.clear();
346 sptr = sptr->base.ptr();
347 }
348 }
349
350 void GDScript::get_script_property_list(List<PropertyInfo> *r_list) const {
351 _get_script_property_list(r_list, true);
352 }
353
354 bool GDScript::has_method(const StringName &p_method) const {
355 return member_functions.has(p_method);
356 }
357
358 bool GDScript::has_static_method(const StringName &p_method) const {
359 return member_functions.has(p_method) && member_functions[p_method]->is_static();
360 }
361
362 int GDScript::get_script_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
363 HashMap<StringName, GDScriptFunction *>::ConstIterator E = member_functions.find(p_method);
364 if (!E) {
365 if (r_is_valid) {
366 *r_is_valid = false;
367 }
368 return 0;
369 }
370
371 if (r_is_valid) {
372 *r_is_valid = true;
373 }
374 return E->value->get_argument_count();
375 }
376
377 MethodInfo GDScript::get_method_info(const StringName &p_method) const {
378 HashMap<StringName, GDScriptFunction *>::ConstIterator E = member_functions.find(p_method);
379 if (!E) {
380 return MethodInfo();
381 }
382
383 return E->value->get_method_info();
384 }
385
386 bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
387 #ifdef TOOLS_ENABLED
388
389 HashMap<StringName, Variant>::ConstIterator E = member_default_values_cache.find(p_property);
390 if (E) {
391 r_value = E->value;
392 return true;
393 }
394
395 if (base_cache.is_valid()) {
396 return base_cache->get_property_default_value(p_property, r_value);
397 }
398 #endif
399 return false;
400 }
401
402 ScriptInstance *GDScript::instance_create(Object *p_this) {
403 ERR_FAIL_COND_V_MSG(!valid, nullptr, "Script is invalid!");
404
405 GDScript *top = this;
406 while (top->base.ptr()) {
407 top = top->base.ptr();
408 }
409
410 if (top->native.is_valid()) {
411 if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
412 if (EngineDebugger::is_active()) {
413 GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'");
414 }
415 ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type '" + p_this->get_class() + "'" + ".");
416 }
417 }
418
419 Callable::CallError unchecked_error;
420 return _create_instance(nullptr, 0, p_this, unchecked_error);
421 }
422
423 PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) {
424 #ifdef TOOLS_ENABLED
425 PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
426 placeholders.insert(si);
427 _update_exports(nullptr, false, si);
428 return si;
429 #else
430 return nullptr;
431 #endif
432 }
433
434 bool GDScript::instance_has(const Object *p_this) const {
435 MutexLock lock(GDScriptLanguage::singleton->mutex);
436
437 return instances.has((Object *)p_this);
438 }
439
440 bool GDScript::has_source_code() const {
441 return !source.is_empty();
442 }
443
444 String GDScript::get_source_code() const {
445 return source;
446 }
447
448 void GDScript::set_source_code(const String &p_code) {
449 if (source == p_code) {
450 return;
451 }
452 source = p_code;
453 #ifdef TOOLS_ENABLED
454 source_changed_cache = true;
455 #endif
456 }
457
458 #ifdef TOOLS_ENABLED
459 void GDScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
460 for (const KeyValue<StringName, Variant> &E : member_default_values_cache) {
461 values[E.key] = E.value;
462 }
463
464 for (const PropertyInfo &E : members_cache) {
465 propnames.push_back(E);
466 }
467
468 if (base_cache.is_valid()) {
469 base_cache->_update_exports_values(values, propnames);
470 }
471 }
472
473 void GDScript::_add_doc(const DocData::ClassDoc &p_doc) {
474 doc_class_name = p_doc.name;
475 if (_owner) { // Only the top-level class stores doc info.
476 _owner->_add_doc(p_doc);
477 } else { // Remove old docs, add new.
478 for (int i = 0; i < docs.size(); i++) {
479 if (docs[i].name == p_doc.name) {
480 docs.remove_at(i);
481 break;
482 }
483 }
484 docs.append(p_doc);
485 }
486 }
487
488 void GDScript::_clear_doc() {
489 doc_class_name = StringName();
490 doc = DocData::ClassDoc();
491 docs.clear();
492 }
493
494 String GDScript::get_class_icon_path() const {
495 return simplified_icon_path;
496 }
497 #endif
498
499 bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderScriptInstance *p_instance_to_update, bool p_base_exports_changed) {
500 #ifdef TOOLS_ENABLED
501
502 static Vector<GDScript *> base_caches;
503 if (!p_recursive_call) {
504 base_caches.clear();
505 }
506 base_caches.append(this);
507
508 bool changed = p_base_exports_changed;
509
510 if (source_changed_cache) {
511 source_changed_cache = false;
512 changed = true;
513
514 String basedir = path;
515
516 if (basedir.is_empty()) {
517 basedir = get_path();
518 }
519
520 if (!basedir.is_empty()) {
521 basedir = basedir.get_base_dir();
522 }
523
524 GDScriptParser parser;
525 GDScriptAnalyzer analyzer(&parser);
526 Error err = parser.parse(source, path, false);
527
528 if (err == OK && analyzer.analyze() == OK) {
529 const GDScriptParser::ClassNode *c = parser.get_tree();
530
531 if (base_cache.is_valid()) {
532 base_cache->inheriters_cache.erase(get_instance_id());
533 base_cache = Ref<GDScript>();
534 }
535
536 GDScriptParser::DataType base_type = parser.get_tree()->base_type;
537 if (base_type.kind == GDScriptParser::DataType::CLASS) {
538 Ref<GDScript> bf = GDScriptCache::get_full_script(base_type.script_path, err, path);
539 if (err == OK) {
540 bf = Ref<GDScript>(bf->find_class(base_type.class_type->fqcn));
541 if (bf.is_valid()) {
542 base_cache = bf;
543 bf->inheriters_cache.insert(get_instance_id());
544 }
545 }
546 }
547
548 members_cache.clear();
549 member_default_values_cache.clear();
550 _signals.clear();
551
552 members_cache.push_back(get_class_category());
553
554 for (int i = 0; i < c->members.size(); i++) {
555 const GDScriptParser::ClassNode::Member &member = c->members[i];
556
557 switch (member.type) {
558 case GDScriptParser::ClassNode::Member::VARIABLE: {
559 if (!member.variable->exported) {
560 continue;
561 }
562
563 members_cache.push_back(member.variable->export_info);
564 Variant default_value = analyzer.make_variable_default_value(member.variable);
565 member_default_values_cache[member.variable->identifier->name] = default_value;
566 } break;
567 case GDScriptParser::ClassNode::Member::SIGNAL: {
568 _signals[member.signal->identifier->name] = member.signal->method_info;
569 } break;
570 case GDScriptParser::ClassNode::Member::GROUP: {
571 members_cache.push_back(member.annotation->export_info);
572 } break;
573 default:
574 break; // Nothing.
575 }
576 }
577 } else {
578 placeholder_fallback_enabled = true;
579 return false;
580 }
581 } else if (placeholder_fallback_enabled) {
582 return false;
583 }
584
585 placeholder_fallback_enabled = false;
586
587 if (base_cache.is_valid() && base_cache->is_valid()) {
588 for (int i = 0; i < base_caches.size(); i++) {
589 if (base_caches[i] == base_cache.ptr()) {
590 if (r_err) {
591 *r_err = true;
592 }
593 valid = false; // to show error in the editor
594 base_cache->valid = false;
595 base_cache->inheriters_cache.clear(); // to prevent future stackoverflows
596 base_cache.unref();
597 base.unref();
598 ERR_FAIL_V_MSG(false, "Cyclic inheritance in script class.");
599 }
600 }
601 if (base_cache->_update_exports(r_err, true)) {
602 if (r_err && *r_err) {
603 return false;
604 }
605 changed = true;
606 }
607 }
608
609 if ((changed || p_instance_to_update) && placeholders.size()) { //hm :(
610
611 // update placeholders if any
612 HashMap<StringName, Variant> values;
613 List<PropertyInfo> propnames;
614 _update_exports_values(values, propnames);
615
616 if (changed) {
617 for (PlaceHolderScriptInstance *E : placeholders) {
618 E->update(propnames, values);
619 }
620 } else {
621 p_instance_to_update->update(propnames, values);
622 }
623 }
624
625 return changed;
626
627 #else
628 return false;
629 #endif
630 }
631
632 void GDScript::update_exports() {
633 #ifdef TOOLS_ENABLED
634 _update_exports_down(false);
635 #endif
636 }
637
638 #ifdef TOOLS_ENABLED
639 void GDScript::_update_exports_down(bool p_base_exports_changed) {
640 bool cyclic_error = false;
641 bool changed = _update_exports(&cyclic_error, false, nullptr, p_base_exports_changed);
642
643 if (cyclic_error) {
644 return;
645 }
646
647 HashSet<ObjectID> copy = inheriters_cache; //might get modified
648
649 for (const ObjectID &E : copy) {
650 Object *id = ObjectDB::get_instance(E);
651 GDScript *s = Object::cast_to<GDScript>(id);
652
653 if (!s) {
654 continue;
655 }
656 s->_update_exports_down(p_base_exports_changed || changed);
657 }
658 }
659 #endif
660
661 String GDScript::_get_debug_path() const {
662 if (is_built_in() && !get_name().is_empty()) {
663 return vformat("%s(%s)", get_name(), get_script_path());
664 } else {
665 return get_script_path();
666 }
667 }
668
669 Error GDScript::_static_init() {
670 if (likely(valid) && static_initializer) {
671 Callable::CallError call_err;
672 static_initializer->call(nullptr, nullptr, 0, call_err);
673 if (call_err.error != Callable::CallError::CALL_OK) {
674 return ERR_CANT_CREATE;
675 }
676 }
677 Error err = OK;
678 for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
679 err = inner.value->_static_init();
680 if (err) {
681 break;
682 }
683 }
684 return err;
685 }
686
687 void GDScript::_static_default_init() {
688 for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
689 const GDScriptDataType &type = E.value.data_type;
690 // Only initialize builtin types, which are not expected to be `null`.
691 if (type.kind != GDScriptDataType::BUILTIN) {
692 continue;
693 }
694 if (type.builtin_type == Variant::ARRAY && type.has_container_element_type(0)) {
695 const GDScriptDataType element_type = type.get_container_element_type(0);
696 Array default_value;
697 default_value.set_typed(element_type.builtin_type, element_type.native_type, element_type.script_type);
698 static_variables.write[E.value.index] = default_value;
699 } else if (type.builtin_type == Variant::DICTIONARY && type.has_container_element_types()) {
700 const GDScriptDataType key_type = type.get_container_element_type_or_variant(0);
701 const GDScriptDataType value_type = type.get_container_element_type_or_variant(1);
702 Dictionary default_value;
703 default_value.set_typed(key_type.builtin_type, key_type.native_type, key_type.script_type, value_type.builtin_type, value_type.native_type, value_type.script_type);
704 static_variables.write[E.value.index] = default_value;
705 } else {
706 Variant default_value;
707 Callable::CallError err;
708 Variant::construct(type.builtin_type, default_value, nullptr, 0, err);
709 static_variables.write[E.value.index] = default_value;
710 }
711 }
712 }
713
714 #ifdef TOOLS_ENABLED
715
716 void GDScript::_save_old_static_data() {
717 old_static_variables_indices = static_variables_indices;
718 old_static_variables = static_variables;
719 for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
720 inner.value->_save_old_static_data();
721 }
722 }
723
724 void GDScript::_restore_old_static_data() {
725 for (KeyValue<StringName, MemberInfo> &E : old_static_variables_indices) {
726 if (static_variables_indices.has(E.key)) {
727 static_variables.write[static_variables_indices[E.key].index] = old_static_variables[E.value.index];
728 }
729 }
730 old_static_variables_indices.clear();
731 old_static_variables.clear();
732 for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
733 inner.value->_restore_old_static_data();
734 }
735 }
736
737 #endif
738
739 Error GDScript::reload(bool p_keep_state) {
740 if (reloading) {
741 return OK;
742 }
743 reloading = true;
744
745 bool has_instances;
746 {
747 MutexLock lock(GDScriptLanguage::singleton->mutex);
748
749 has_instances = instances.size();
750 }
751
752 // Check condition but reset flag before early return
753 if (!p_keep_state && has_instances) {
754 reloading = false; // Reset flag before returning
755
756 ERR_FAIL_V_MSG(ERR_ALREADY_IN_USE, "Cannot reload script while instances exist.");
757 }
758
759 String basedir = path;
760
761 if (basedir.is_empty()) {
762 basedir = get_path();
763 }
764
765 if (!basedir.is_empty()) {
766 basedir = basedir.get_base_dir();
767 }
768
769 // Loading a template, don't parse.
770 #ifdef TOOLS_ENABLED
771 if (EditorPaths::get_singleton() && basedir.begins_with(EditorPaths::get_singleton()->get_project_script_templates_dir())) {
772 reloading = false;
773 return OK;
774 }
775 #endif
776
777 {
778 String source_path = path;
779 if (source_path.is_empty()) {
780 source_path = get_path();
781 }
782 if (!source_path.is_empty()) {
783 if (GDScriptCache::get_cached_script(source_path).is_null()) {
784 MutexLock lock(GDScriptCache::singleton->mutex);
785 GDScriptCache::singleton->shallow_gdscript_cache[source_path] = Ref<GDScript>(this);
786 }
787 if (GDScriptCache::has_parser(source_path)) {
788 Error err = OK;
789 Ref<GDScriptParserRef> parser_ref = GDScriptCache::get_parser(source_path, GDScriptParserRef::EMPTY, err);
790 if (parser_ref.is_valid()) {
791 uint32_t source_hash;
792 if (!binary_tokens.is_empty()) {
793 source_hash = hash_djb2_buffer(binary_tokens.ptr(), binary_tokens.size());
794 } else {
795 source_hash = source.hash();
796 }
797 if (parser_ref->get_source_hash() != source_hash) {
798 GDScriptCache::remove_parser(source_path);
799 }
800 }
801 }
802 }
803 }
804
805 bool can_run = ScriptServer::is_scripting_enabled() || is_tool();
806
807 #ifdef TOOLS_ENABLED
808 if (p_keep_state && can_run && is_valid()) {
809 _save_old_static_data();
810 }
811 #endif
812
813 valid = false;
814 GDScriptParser parser;
815 Error err;
816 if (!binary_tokens.is_empty()) {
817 err = parser.parse_binary(binary_tokens, path);
818 } else {
819 err = parser.parse(source, path, false);
820 }
821 if (err) {
822 if (EngineDebugger::is_active()) {
823 GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
824 }
825 // TODO: Show all error messages.
826 _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_errors().front()->get().line, ("Parse Error: " + parser.get_errors().front()->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
827 reloading = false;
828 return ERR_PARSE_ERROR;
829 }
830
831 GDScriptAnalyzer analyzer(&parser);
832 err = analyzer.analyze();
833
834 if (err) {
835 if (EngineDebugger::is_active()) {
836 GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
837 }
838
839 const List<GDScriptParser::ParserError>::Element *e = parser.get_errors().front();
840 while (e != nullptr) {
841 _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), e->get().line, ("Parse Error: " + e->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
842 e = e->next();
843 }
844 reloading = false;
845 return ERR_PARSE_ERROR;
846 }
847
848 can_run = ScriptServer::is_scripting_enabled() || parser.is_tool();
849
850 GDScriptCompiler compiler;
851 err = compiler.compile(&parser, this, p_keep_state);
852
853 if (err) {
854 // TODO: Provide the script function as the first argument.
855 _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
856 if (can_run) {
857 if (EngineDebugger::is_active()) {
858 GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
859 }
860 reloading = false;
861 return ERR_COMPILATION_FAILED;
862 } else {
863 reloading = false;
864 return err;
865 }
866 }
867
868 #ifdef TOOLS_ENABLED
869 // Done after compilation because it needs the GDScript object's inner class GDScript objects,
870 // which are made by calling make_scripts() within compiler.compile() above.
871 GDScriptDocGen::generate_docs(this, parser.get_tree());
872 #endif
873
874 #ifdef DEBUG_ENABLED
875 for (const GDScriptWarning &warning : parser.get_warnings()) {
876 if (EngineDebugger::is_active()) {
877 Vector<ScriptLanguage::StackInfo> si;
878 // TODO: Provide the script function as the first argument.
879 EngineDebugger::get_script_debugger()->send_error("GDScript::reload", get_script_path(), warning.start_line, warning.get_name(), warning.get_message(), false, ERR_HANDLER_WARNING, si);
880 }
881 }
882 #endif
883
884 if (can_run) {
885 err = _static_init();
886 if (err) {
887 return err;
888 }
889 }
890
891 #ifdef TOOLS_ENABLED
892 if (can_run && p_keep_state) {
893 _restore_old_static_data();
894 }
895
896 if (p_keep_state) {
897 // Update the properties in the inspector.
898 update_exports();
899 }
900 #endif
901
902 reloading = false;
903 return OK;
904 }
905
906 ScriptLanguage *GDScript::get_language() const {
907 return GDScriptLanguage::get_singleton();
908 }
909
910 void GDScript::get_constants(HashMap<StringName, Variant> *p_constants) {
911 if (p_constants) {
912 for (const KeyValue<StringName, Variant> &E : constants) {
913 (*p_constants)[E.key] = E.value;
914 }
915 }
916 }
917
918 void GDScript::get_members(HashSet<StringName> *p_members) {
919 if (p_members) {
920 for (const StringName &E : members) {
921 p_members->insert(E);
922 }
923 }
924 }
925
926 const Variant GDScript::get_rpc_config() const {
927 return rpc_config;
928 }
929
930 void GDScript::unload_static() const {
931 GDScriptCache::remove_script(fully_qualified_name);
932 }
933
934 Variant GDScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
935 GDScript *top = this;
936 while (top) {
937 if (likely(top->valid)) {
938 HashMap<StringName, GDScriptFunction *>::Iterator E = top->member_functions.find(p_method);
939 if (E) {
940 ERR_FAIL_COND_V_MSG(!E->value->is_static(), Variant(), "Can't call non-static function '" + String(p_method) + "' in script.");
941
942 return E->value->call(nullptr, p_args, p_argcount, r_error);
943 }
944 }
945 top = top->base.ptr();
946 }
947
948 //none found, regular
949
950 return Script::callp(p_method, p_args, p_argcount, r_error);
951 }
952
953 bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
954 if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
955 r_ret = get_source_code();
956 return true;
957 }
958
959 const GDScript *top = this;
960 while (top) {
961 {
962 HashMap<StringName, Variant>::ConstIterator E = top->constants.find(p_name);
963 if (E) {
964 r_ret = E->value;
965 return true;
966 }
967 }
968
969 {
970 HashMap<StringName, MemberInfo>::ConstIterator E = top->static_variables_indices.find(p_name);
971 if (E) {
972 if (likely(top->valid) && E->value.getter) {
973 Callable::CallError ce;
974 const Variant ret = const_cast<GDScript *>(this)->callp(E->value.getter, nullptr, 0, ce);
975 r_ret = (ce.error == Callable::CallError::CALL_OK) ? ret : Variant();
976 return true;
977 }
978 r_ret = top->static_variables[E->value.index];
979 return true;
980 }
981 }
982
983 if (likely(top->valid)) {
984 HashMap<StringName, GDScriptFunction *>::ConstIterator E = top->member_functions.find(p_name);
985 if (E && E->value->is_static()) {
986 if (top->rpc_config.has(p_name)) {
987 r_ret = Callable(memnew(GDScriptRPCCallable(const_cast<GDScript *>(top), E->key)));
988 } else {
989 r_ret = Callable(const_cast<GDScript *>(top), E->key);
990 }
991 return true;
992 }
993 }
994
995 {
996 HashMap<StringName, Ref<GDScript>>::ConstIterator E = top->subclasses.find(p_name);
997 if (E) {
998 r_ret = E->value;
999 return true;
1000 }
1001 }
1002
1003 top = top->base.ptr();
1004 }
1005
1006 return false;
1007 }
1008
1009 bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
1010 if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
1011 set_source_code(p_value);
1012 reload(true);
1013 return true;
1014 }
1015
1016 GDScript *top = this;
1017 while (top) {
1018 HashMap<StringName, MemberInfo>::ConstIterator E = top->static_variables_indices.find(p_name);
1019 if (E) {
1020 const MemberInfo *member = &E->value;
1021 Variant value = p_value;
1022 if (!member->data_type.is_type(value)) {
1023 const Variant *args = &p_value;
1024 Callable::CallError err;
1025 Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
1026 if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
1027 return false;
1028 }
1029 }
1030 if (likely(top->valid) && member->setter) {
1031 const Variant *args = &value;
1032 Callable::CallError err;
1033 callp(member->setter, &args, 1, err);
1034 return err.error == Callable::CallError::CALL_OK;
1035 } else {
1036 top->static_variables.write[member->index] = value;
1037 return true;
1038 }
1039 }
1040
1041 top = top->base.ptr();
1042 }
1043
1044 return false;
1045 }
1046
1047 void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
1048 p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
1049
1050 List<const GDScript *> classes;
1051 const GDScript *top = this;
1052 while (top) {
1053 classes.push_back(top);
1054 top = top->base.ptr();
1055 }
1056
1057 for (const List<const GDScript *>::Element *E = classes.back(); E; E = E->prev()) {
1058 Vector<_GDScriptMemberSort> msort;
1059 for (const KeyValue<StringName, MemberInfo> &F : E->get()->static_variables_indices) {
1060 _GDScriptMemberSort ms;
1061 ms.index = F.value.index;
1062 ms.name = F.key;
1063 msort.push_back(ms);
1064 }
1065 msort.sort();
1066
1067 for (int i = 0; i < msort.size(); i++) {
1068 p_properties->push_back(E->get()->static_variables_indices[msort[i].name].property_info);
1069 }
1070 }
1071 }
1072
1073 void GDScript::_bind_methods() {
1074 ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new"));
1075 }
1076
1077 void GDScript::set_path_cache(const String &p_path) {
1078 if (is_root_script()) {
1079 Script::set_path_cache(p_path);
1080 }
1081
1082 path = p_path;
1083 path_valid = true;
1084
1085 for (KeyValue<StringName, Ref<GDScript>> &kv : subclasses) {
1086 kv.value->set_path_cache(p_path);
1087 }
1088 }
1089
1090 void GDScript::set_path(const String &p_path, bool p_take_over) {
1091 if (is_root_script()) {
1092 Script::set_path(p_path, p_take_over);
1093 }
1094
1095 String old_path = path;
1096 path = p_path;
1097 path_valid = true;
1098 GDScriptCache::move_script(old_path, p_path);
1099
1100 for (KeyValue<StringName, Ref<GDScript>> &kv : subclasses) {
1101 kv.value->set_path(p_path, p_take_over);
1102 }
1103 }
1104
1105 String GDScript::get_script_path() const {
1106 if (!path_valid && !get_path().is_empty()) {
1107 return get_path();
1108 }
1109 return path;
1110 }
1111
1112 Error GDScript::load_source_code(const String &p_path) {
1113 if (p_path.is_empty() || p_path.begins_with("gdscript://") || ResourceLoader::get_resource_type(p_path.get_slice("::", 0)) == "PackedScene") {
1114 return OK;
1115 }
1116
1117 Vector<uint8_t> sourcef;
1118 Error err;
1119 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
1120 if (err) {
1121 const char *err_name;
1122 if (err < 0 || err >= ERR_MAX) {
1123 err_name = "(invalid error code)";
1124 } else {
1125 err_name = error_names[err];
1126 }
1127 ERR_FAIL_COND_V_MSG(err, err, "Attempt to open script '" + p_path + "' resulted in error '" + err_name + "'.");
1128 }
1129
1130 uint64_t len = f->get_length();
1131 sourcef.resize(len + 1);
1132 uint8_t *w = sourcef.ptrw();
1133 uint64_t r = f->get_buffer(w, len);
1134 ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
1135 w[len] = 0;
1136
1137 String s;
1138 if (s.append_utf8((const char *)w, len) != OK) {
1139 ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
1140 }
1141
1142 source = s;
1143 path = p_path;
1144 path_valid = true;
1145 #ifdef TOOLS_ENABLED
1146 source_changed_cache = true;
1147 set_edited(false);
1148 set_last_modified_time(FileAccess::get_modified_time(path));
1149 #endif // TOOLS_ENABLED
1150 return OK;
1151 }
1152
1153 void GDScript::set_binary_tokens_source(const Vector<uint8_t> &p_binary_tokens) {
1154 binary_tokens = p_binary_tokens;
1155 }
1156
1157 const Vector<uint8_t> &GDScript::get_binary_tokens_source() const {
1158 return binary_tokens;
1159 }
1160
1161 Vector<uint8_t> GDScript::get_as_binary_tokens() const {
1162 GDScriptTokenizerBuffer tokenizer;
1163 return tokenizer.parse_code_string(source, GDScriptTokenizerBuffer::COMPRESS_NONE);
1164 }
1165
1166 const HashMap<StringName, GDScriptFunction *> &GDScript::debug_get_member_functions() const {
1167 return member_functions;
1168 }
1169
1170 StringName GDScript::debug_get_member_by_index(int p_idx) const {
1171 for (const KeyValue<StringName, MemberInfo> &E : member_indices) {
1172 if (E.value.index == p_idx) {
1173 return E.key;
1174 }
1175 }
1176
1177 return "<error>";
1178 }
1179
1180 StringName GDScript::debug_get_static_var_by_index(int p_idx) const {
1181 for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
1182 if (E.value.index == p_idx) {
1183 return E.key;
1184 }
1185 }
1186
1187 return "<error>";
1188 }
1189
1190 Ref<GDScript> GDScript::get_base() const {
1191 return base;
1192 }
1193
1194 bool GDScript::inherits_script(const Ref<Script> &p_script) const {
1195 Ref<GDScript> gd = p_script;
1196 if (gd.is_null()) {
1197 return false;
1198 }
1199
1200 const GDScript *s = this;
1201
1202 while (s) {
1203 if (s == p_script.ptr()) {
1204 return true;
1205 }
1206 s = s->base.ptr();
1207 }
1208
1209 return false;
1210 }
1211
1212 GDScript *GDScript::find_class(const String &p_qualified_name) {
1213 String first = p_qualified_name.get_slice("::", 0);
1214
1215 Vector<String> class_names;
1216 GDScript *result = nullptr;
1217 // Empty initial name means start here.
1218 if (first.is_empty() || first == global_name) {
1219 class_names = p_qualified_name.split("::");
1220 result = this;
1221 } else if (p_qualified_name.begins_with(get_root_script()->path)) {
1222 // Script path could have a class path separator("::") in it.
1223 class_names = p_qualified_name.trim_prefix(get_root_script()->path).split("::");
1224 result = get_root_script();
1225 } else if (HashMap<StringName, Ref<GDScript>>::Iterator E = subclasses.find(first)) {
1226 class_names = p_qualified_name.split("::");
1227 result = E->value.ptr();
1228 } else if (_owner != nullptr) {
1229 // Check parent scope.
1230 return _owner->find_class(p_qualified_name);
1231 }
1232
1233 // Starts at index 1 because index 0 was handled above.
1234 for (int i = 1; result != nullptr && i < class_names.size(); i++) {
1235 if (HashMap<StringName, Ref<GDScript>>::Iterator E = result->subclasses.find(class_names[i])) {
1236 result = E->value.ptr();
1237 } else {
1238 // Couldn't find inner class.
1239 return nullptr;
1240 }
1241 }
1242
1243 return result;
1244 }
1245
1246 bool GDScript::has_class(const GDScript *p_script) {
1247 String fqn = p_script->fully_qualified_name;
1248 if (fully_qualified_name.is_empty() && fqn.get_slice("::", 0).is_empty()) {
1249 return p_script == this;
1250 } else if (fqn.begins_with(fully_qualified_name)) {
1251 return p_script == find_class(fqn.trim_prefix(fully_qualified_name));
1252 }
1253 return false;
1254 }
1255
1256 GDScript *GDScript::get_root_script() {
1257 GDScript *result = this;
1258 while (result->_owner) {
1259 result = result->_owner;
1260 }
1261 return result;
1262 }
1263
1264 bool GDScript::has_script_signal(const StringName &p_signal) const {
1265 if (_signals.has(p_signal)) {
1266 return true;
1267 }
1268 if (base.is_valid()) {
1269 return base->has_script_signal(p_signal);
1270 }
1271 #ifdef TOOLS_ENABLED
1272 else if (base_cache.is_valid()) {
1273 return base_cache->has_script_signal(p_signal);
1274 }
1275 #endif
1276 return false;
1277 }
1278
1279 void GDScript::_get_script_signal_list(List<MethodInfo> *r_list, bool p_include_base) const {
1280 for (const KeyValue<StringName, MethodInfo> &E : _signals) {
1281 r_list->push_back(E.value);
1282 }
1283
1284 if (!p_include_base) {
1285 return;
1286 }
1287
1288 if (base.is_valid()) {
1289 base->get_script_signal_list(r_list);
1290 }
1291 #ifdef TOOLS_ENABLED
1292 else if (base_cache.is_valid()) {
1293 base_cache->get_script_signal_list(r_list);
1294 }
1295 #endif
1296 }
1297
1298 void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
1299 _get_script_signal_list(r_signals, true);
1300 }
1301
1302 GDScript::GDScript() :
1303 script_list(this) {
1304 {
1305 MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
1306
1307 GDScriptLanguage::get_singleton()->script_list.add(&script_list);
1308 }
1309
1310 path = vformat("gdscript://%d.gd", get_instance_id());
1311 }
1312
1313 void GDScript::_save_orphaned_subclasses() {
1314 struct ClassRefWithName {
1315 ObjectID id;
1316 String fully_qualified_name;
1317 };
1318 Vector<ClassRefWithName> weak_subclasses;
1319 // collect subclasses ObjectID and name
1320 for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
1321 E.value->_owner = nullptr; //bye, you are no longer owned cause I died
1322 ClassRefWithName subclass;
1323 subclass.id = E.value->get_instance_id();
1324 subclass.fully_qualified_name = E.value->fully_qualified_name;
1325 weak_subclasses.push_back(subclass);
1326 }
1327
1328 // clear subclasses to allow unused subclasses to be deleted
1329 subclasses.clear();
1330 // subclasses are also held by constants, clear those as well
1331 constants.clear();
1332
1333 // keep orphan subclass only for subclasses that are still in use
1334 for (int i = 0; i < weak_subclasses.size(); i++) {
1335 ClassRefWithName subclass = weak_subclasses[i];
1336 Object *obj = ObjectDB::get_instance(subclass.id);
1337 if (!obj) {
1338 continue;
1339 }
1340 // subclass is not released
1341 GDScriptLanguage::get_singleton()->add_orphan_subclass(subclass.fully_qualified_name, subclass.id);
1342 }
1343 }
1344
1345 #ifdef DEBUG_ENABLED
1346 String GDScript::debug_get_script_name(const Ref<Script> &p_script) {
1347 if (p_script.is_valid()) {
1348 Ref<GDScript> gdscript = p_script;
1349 if (gdscript.is_valid()) {
1350 if (gdscript->get_local_name() != StringName()) {
1351 return gdscript->get_local_name();
1352 }
1353 return gdscript->get_fully_qualified_name().get_file();
1354 }
1355
1356 if (p_script->get_global_name() != StringName()) {
1357 return p_script->get_global_name();
1358 } else if (!p_script->get_path().is_empty()) {
1359 return p_script->get_path().get_file();
1360 } else if (!p_script->get_name().is_empty()) {
1361 return p_script->get_name(); // Resource name.
1362 }
1363 }
1364
1365 return "<unknown script>";
1366 }
1367 #endif
1368
1369 String GDScript::canonicalize_path(const String &p_path) {
1370 if (p_path.get_extension() == "gdc") {
1371 return p_path.get_basename() + ".gd";
1372 }
1373 return p_path;
1374 }
1375
1376 GDScript::UpdatableFuncPtr::UpdatableFuncPtr(GDScriptFunction *p_function) {
1377 if (p_function == nullptr) {
1378 return;
1379 }
1380
1381 ptr = p_function;
1382 script = ptr->get_script();
1383 ERR_FAIL_NULL(script);
1384
1385 MutexLock script_lock(script->func_ptrs_to_update_mutex);
1386 list_element = script->func_ptrs_to_update.push_back(this);
1387 }
1388
1389 GDScript::UpdatableFuncPtr::~UpdatableFuncPtr() {
1390 ERR_FAIL_NULL(script);
1391
1392 if (list_element) {
1393 MutexLock script_lock(script->func_ptrs_to_update_mutex);
1394 list_element->erase();
1395 list_element = nullptr;
1396 }
1397 }
1398
1399 void GDScript::_recurse_replace_function_ptrs(const HashMap<GDScriptFunction *, GDScriptFunction *> &p_replacements) const {
1400 MutexLock lock(func_ptrs_to_update_mutex);
1401 for (UpdatableFuncPtr *updatable : func_ptrs_to_update) {
1402 HashMap<GDScriptFunction *, GDScriptFunction *>::ConstIterator replacement = p_replacements.find(updatable->ptr);
1403 if (replacement) {
1404 updatable->ptr = replacement->value;
1405 } else {
1406 // Probably a lambda from another reload, ignore.
1407 updatable->ptr = nullptr;
1408 }
1409 }
1410
1411 for (HashMap<StringName, Ref<GDScript>>::ConstIterator subscript = subclasses.begin(); subscript; ++subscript) {
1412 subscript->value->_recurse_replace_function_ptrs(p_replacements);
1413 }
1414 }
1415
1416 void GDScript::clear() {
1417 if (clearing) {
1418 return;
1419 }
1420 clearing = true;
1421
1422 RBSet<GDScriptFunction *> functions_to_clear;
1423
1424 {
1425 MutexLock lock(func_ptrs_to_update_mutex);
1426 for (UpdatableFuncPtr *updatable : func_ptrs_to_update) {
1427 updatable->ptr = nullptr;
1428 }
1429 }
1430
1431 for (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {
1432 functions_to_clear.insert(E.value);
1433 }
1434 member_functions.clear();
1435
1436 for (KeyValue<StringName, MemberInfo> &E : member_indices) {
1437 E.value.data_type.script_type_ref = Ref<Script>();
1438 }
1439
1440 member_indices.clear();
1441 static_variables.clear();
1442 static_variables_indices.clear();
1443
1444 if (implicit_initializer) {
1445 functions_to_clear.insert(implicit_initializer);
1446 implicit_initializer = nullptr;
1447 }
1448
1449 if (implicit_ready) {
1450 functions_to_clear.insert(implicit_ready);
1451 implicit_ready = nullptr;
1452 }
1453
1454 if (static_initializer) {
1455 functions_to_clear.insert(static_initializer);
1456 static_initializer = nullptr;
1457 }
1458
1459 _save_orphaned_subclasses();
1460
1461 #ifdef TOOLS_ENABLED
1462 // Clearing inner class doc, script doc only cleared when the script source deleted.
1463 if (_owner) {
1464 _clear_doc();
1465 }
1466 #endif
1467
1468 // All dependencies have been accounted for
1469 for (GDScriptFunction *E : functions_to_clear) {
1470 memdelete(E);
1471 }
1472 functions_to_clear.clear();
1473 }
1474
1475 void GDScript::cancel_pending_functions(bool warn) {
1476 MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
1477
1478 while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
1479 // Order matters since clearing the stack may already cause
1480 // the GDScriptFunctionState to be destroyed and thus removed from the list.
1481 pending_func_states.remove(E);
1482 GDScriptFunctionState *state = E->self();
1483 #ifdef DEBUG_ENABLED
1484 if (warn) {
1485 WARN_PRINT("Canceling suspended execution of \"" + state->get_readable_function() + "\" due to a script reload.");
1486 }
1487 #endif
1488 ObjectID state_id = state->get_instance_id();
1489 state->_clear_connections();
1490 if (ObjectDB::get_instance(state_id)) {
1491 state->_clear_stack();
1492 }
1493 }
1494 }
1495
1496 GDScript::~GDScript() {
1497 if (destructing) {
1498 return;
1499 }
1500 destructing = true;
1501
1502 if (is_print_verbose_enabled()) {
1503 MutexLock lock(func_ptrs_to_update_mutex);
1504 if (!func_ptrs_to_update.is_empty()) {
1505 print_line(vformat("GDScript: %d orphaned lambdas becoming invalid at destruction of script '%s'.", func_ptrs_to_update.size(), fully_qualified_name));
1506 }
1507 }
1508
1509 clear();
1510
1511 cancel_pending_functions(false);
1512
1513 {
1514 MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
1515
1516 script_list.remove_from_list();
1517 }
1518 }
1519
1520 //////////////////////////////
1521 // INSTANCE //
1522 //////////////////////////////
1523
1524 bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
1525 {
1526 HashMap<StringName, GDScript::MemberInfo>::Iterator E = script->member_indices.find(p_name);
1527 if (E) {
1528 const GDScript::MemberInfo *member = &E->value;
1529 Variant value = p_value;
1530 if (!member->data_type.is_type(value)) {
1531 const Variant *args = &p_value;
1532 Callable::CallError err;
1533 Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
1534 if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
1535 return false;
1536 }
1537 }
1538 if (likely(script->valid) && member->setter) {
1539 const Variant *args = &value;
1540 Callable::CallError err;
1541 callp(member->setter, &args, 1, err);
1542 return err.error == Callable::CallError::CALL_OK;
1543 } else {
1544 members.write[member->index] = value;
1545 return true;
1546 }
1547 }
1548 }
1549
1550 GDScript *sptr = script.ptr();
1551 while (sptr) {
1552 {
1553 HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = sptr->static_variables_indices.find(p_name);
1554 if (E) {
1555 const GDScript::MemberInfo *member = &E->value;
1556 Variant value = p_value;
1557 if (!member->data_type.is_type(value)) {
1558 const Variant *args = &p_value;
1559 Callable::CallError err;
1560 Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
1561 if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
1562 return false;
1563 }
1564 }
1565 if (likely(sptr->valid) && member->setter) {
1566 const Variant *args = &value;
1567 Callable::CallError err;
1568 callp(member->setter, &args, 1, err);
1569 return err.error == Callable::CallError::CALL_OK;
1570 } else {
1571 sptr->static_variables.write[member->index] = value;
1572 return true;
1573 }
1574 }
1575 }
1576
1577 if (likely(sptr->valid)) {
1578 HashMap<StringName, GDScriptFunction *>::Iterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
1579 if (E) {
1580 Variant name = p_name;
1581 const Variant *args[2] = { &name, &p_value };
1582
1583 Callable::CallError err;
1584 Variant ret = E->value->call(this, (const Variant **)args, 2, err);
1585 if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
1586 return true;
1587 }
1588 }
1589 }
1590
1591 sptr = sptr->base.ptr();
1592 }
1593
1594 return false;
1595 }
1596
1597 bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
1598 {
1599 HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = script->member_indices.find(p_name);
1600 if (E) {
1601 if (likely(script->valid) && E->value.getter) {
1602 Callable::CallError err;
1603 const Variant ret = const_cast<GDScriptInstance *>(this)->callp(E->value.getter, nullptr, 0, err);
1604 r_ret = (err.error == Callable::CallError::CALL_OK) ? ret : Variant();
1605 return true;
1606 }
1607 r_ret = members[E->value.index];
1608 return true;
1609 }
1610 }
1611
1612 const GDScript *sptr = script.ptr();
1613 while (sptr) {
1614 {
1615 HashMap<StringName, Variant>::ConstIterator E = sptr->constants.find(p_name);
1616 if (E) {
1617 r_ret = E->value;
1618 return true;
1619 }
1620 }
1621
1622 {
1623 HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = sptr->static_variables_indices.find(p_name);
1624 if (E) {
1625 if (likely(sptr->valid) && E->value.getter) {
1626 Callable::CallError ce;
1627 const Variant ret = const_cast<GDScript *>(sptr)->callp(E->value.getter, nullptr, 0, ce);
1628 r_ret = (ce.error == Callable::CallError::CALL_OK) ? ret : Variant();
1629 return true;
1630 }
1631 r_ret = sptr->static_variables[E->value.index];
1632 return true;
1633 }
1634 }
1635
1636 {
1637 HashMap<StringName, MethodInfo>::ConstIterator E = sptr->_signals.find(p_name);
1638 if (E) {
1639 r_ret = Signal(owner, E->key);
1640 return true;
1641 }
1642 }
1643
1644 if (likely(sptr->valid)) {
1645 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_name);
1646 if (E) {
1647 if (sptr->rpc_config.has(p_name)) {
1648 r_ret = Callable(memnew(GDScriptRPCCallable(owner, E->key)));
1649 } else {
1650 r_ret = Callable(owner, E->key);
1651 }
1652 return true;
1653 }
1654 }
1655
1656 {
1657 HashMap<StringName, Ref<GDScript>>::ConstIterator E = sptr->subclasses.find(p_name);
1658 if (E) {
1659 r_ret = E->value;
1660 return true;
1661 }
1662 }
1663
1664 if (likely(sptr->valid)) {
1665 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
1666 if (E) {
1667 Variant name = p_name;
1668 const Variant *args[1] = { &name };
1669
1670 Callable::CallError err;
1671 Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), (const Variant **)args, 1, err);
1672 if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
1673 r_ret = ret;
1674 return true;
1675 }
1676 }
1677 }
1678 sptr = sptr->base.ptr();
1679 }
1680
1681 return false;
1682 }
1683
1684 Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
1685 if (script->member_indices.has(p_name)) {
1686 if (r_is_valid) {
1687 *r_is_valid = true;
1688 }
1689 return script->member_indices[p_name].property_info.type;
1690 }
1691
1692 if (r_is_valid) {
1693 *r_is_valid = false;
1694 }
1695 return Variant::NIL;
1696 }
1697
1698 void GDScriptInstance::validate_property(PropertyInfo &p_property) const {
1699 const GDScript *sptr = script.ptr();
1700 while (sptr) {
1701 if (likely(sptr->valid)) {
1702 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._validate_property);
1703 if (E) {
1704 Variant property = (Dictionary)p_property;
1705 const Variant *args[1] = { &property };
1706
1707 Callable::CallError err;
1708 Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
1709 if (err.error == Callable::CallError::CALL_OK) {
1710 p_property = PropertyInfo::from_dict(property);
1711 return;
1712 }
1713 }
1714 }
1715 sptr = sptr->base.ptr();
1716 }
1717 }
1718
1719 void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
1720 // exported members, not done yet!
1721
1722 const GDScript *sptr = script.ptr();
1723 List<PropertyInfo> props;
1724
1725 while (sptr) {
1726 if (likely(sptr->valid)) {
1727 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
1728 if (E) {
1729 Callable::CallError err;
1730 Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), nullptr, 0, err);
1731 if (err.error == Callable::CallError::CALL_OK) {
1732 ERR_FAIL_COND_MSG(ret.get_type() != Variant::ARRAY, "Wrong type for _get_property_list, must be an array of dictionaries.");
1733
1734 Array arr = ret;
1735 for (int i = 0; i < arr.size(); i++) {
1736 Dictionary d = arr[i];
1737 ERR_CONTINUE(!d.has("name"));
1738 ERR_CONTINUE(!d.has("type"));
1739
1740 PropertyInfo pinfo;
1741 pinfo.name = d["name"];
1742 pinfo.type = Variant::Type(d["type"].operator int());
1743 if (d.has("hint")) {
1744 pinfo.hint = PropertyHint(d["hint"].operator int());
1745 }
1746 if (d.has("hint_string")) {
1747 pinfo.hint_string = d["hint_string"];
1748 }
1749 if (d.has("usage")) {
1750 pinfo.usage = d["usage"];
1751 }
1752 if (d.has("class_name")) {
1753 pinfo.class_name = d["class_name"];
1754 }
1755
1756 ERR_CONTINUE(pinfo.name.is_empty() && (pinfo.usage & PROPERTY_USAGE_STORAGE));
1757 ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
1758
1759 props.push_back(pinfo);
1760 }
1761 }
1762 }
1763 }
1764
1765 //instance a fake script for editing the values
1766
1767 Vector<_GDScriptMemberSort> msort;
1768 for (const KeyValue<StringName, GDScript::MemberInfo> &F : sptr->member_indices) {
1769 if (!sptr->members.has(F.key)) {
1770 continue; // Skip base class members.
1771 }
1772 _GDScriptMemberSort ms;
1773 ms.index = F.value.index;
1774 ms.name = F.key;
1775 msort.push_back(ms);
1776 }
1777
1778 msort.sort();
1779 msort.reverse();
1780 for (int i = 0; i < msort.size(); i++) {
1781 props.push_front(sptr->member_indices[msort[i].name].property_info);
1782 }
1783
1784 #ifdef TOOLS_ENABLED
1785 p_properties->push_back(sptr->get_class_category());
1786 #endif // TOOLS_ENABLED
1787
1788 for (PropertyInfo &prop : props) {
1789 validate_property(prop);
1790 p_properties->push_back(prop);
1791 }
1792
1793 props.clear();
1794
1795 sptr = sptr->base.ptr();
1796 }
1797 }
1798
1799 bool GDScriptInstance::property_can_revert(const StringName &p_name) const {
1800 Variant name = p_name;
1801 const Variant *args[1] = { &name };
1802
1803 const GDScript *sptr = script.ptr();
1804 while (sptr) {
1805 if (likely(sptr->valid)) {
1806 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_can_revert);
1807 if (E) {
1808 Callable::CallError err;
1809 Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
1810 if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
1811 return true;
1812 }
1813 }
1814 }
1815 sptr = sptr->base.ptr();
1816 }
1817
1818 return false;
1819 }
1820
1821 bool GDScriptInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
1822 Variant name = p_name;
1823 const Variant *args[1] = { &name };
1824
1825 const GDScript *sptr = script.ptr();
1826 while (sptr) {
1827 if (likely(sptr->valid)) {
1828 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_get_revert);
1829 if (E) {
1830 Callable::CallError err;
1831 Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
1832 if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
1833 r_ret = ret;
1834 return true;
1835 }
1836 }
1837 }
1838 sptr = sptr->base.ptr();
1839 }
1840
1841 return false;
1842 }
1843
1844 void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
1845 const GDScript *sptr = script.ptr();
1846 while (sptr) {
1847 for (const KeyValue<StringName, GDScriptFunction *> &E : sptr->member_functions) {
1848 p_list->push_back(E.value->get_method_info());
1849 }
1850 sptr = sptr->base.ptr();
1851 }
1852 }
1853
1854 bool GDScriptInstance::has_method(const StringName &p_method) const {
1855 const GDScript *sptr = script.ptr();
1856 while (sptr) {
1857 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_method);
1858 if (E) {
1859 return true;
1860 }
1861 sptr = sptr->base.ptr();
1862 }
1863
1864 return false;
1865 }
1866
1867 int GDScriptInstance::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
1868 const GDScript *sptr = script.ptr();
1869 while (sptr) {
1870 HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_method);
1871 if (E) {
1872 if (r_is_valid) {
1873 *r_is_valid = true;
1874 }
1875 return E->value->get_argument_count();
1876 }
1877 sptr = sptr->base.ptr();
1878 }
1879
1880 if (r_is_valid) {
1881 *r_is_valid = false;
1882 }
1883 return 0;
1884 }
1885
1886 void GDScriptInstance::_call_implicit_ready_recursively(GDScript *p_script) {
1887 // Call base class first.
1888 if (p_script->base.ptr()) {
1889 _call_implicit_ready_recursively(p_script->base.ptr());
1890 }
1891 if (likely(p_script->valid) && p_script->implicit_ready) {
1892 Callable::CallError err;
1893 p_script->implicit_ready->call(this, nullptr, 0, err);
1894 }
1895 }
1896
1897 Variant GDScriptInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
1898 GDScript *sptr = script.ptr();
1899 if (unlikely(p_method == SceneStringName(_ready))) {
1900 // Call implicit ready first, including for the super classes recursively.
1901 _call_implicit_ready_recursively(sptr);
1902 }
1903 while (sptr) {
1904 if (likely(sptr->valid)) {
1905 HashMap<StringName, GDScriptFunction *>::Iterator E = sptr->member_functions.find(p_method);
1906 if (E) {
1907 return E->value->call(this, p_args, p_argcount, r_error);
1908 }
1909 }
1910 sptr = sptr->base.ptr();
1911 }
1912
1913 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
1914 return Variant();
1915 }
1916
1917 void GDScriptInstance::notification(int p_notification, bool p_reversed) {
1918 if (unlikely(!script->valid)) {
1919 return;
1920 }
1921
1922 //notification is not virtual, it gets called at ALL levels just like in C.
1923 Variant value = p_notification;
1924 const Variant *args[1] = { &value };
1925 const StringName &notification_str = GDScriptLanguage::get_singleton()->strings._notification;
1926
1927 LocalVector<GDScript *> script_stack;
1928 uint32_t script_count = 0;
1929 for (GDScript *sptr = script.ptr(); sptr; sptr = sptr->base.ptr(), ++script_count) {
1930 script_stack.push_back(sptr);
1931 }
1932
1933 const int start = p_reversed ? 0 : script_count - 1;
1934 const int end = p_reversed ? script_count : -1;
1935 const int step = p_reversed ? 1 : -1;
1936
1937 for (int idx = start; idx != end; idx += step) {
1938 GDScript *sc = script_stack[idx];
1939 if (likely(sc->valid)) {
1940 HashMap<StringName, GDScriptFunction *>::Iterator E = sc->member_functions.find(notification_str);
1941 if (E) {
1942 Callable::CallError err;
1943 E->value->call(this, args, 1, err);
1944 if (err.error != Callable::CallError::CALL_OK) {
1945 //print error about notification call
1946 }
1947 }
1948 }
1949 }
1950 }
1951
1952 String GDScriptInstance::to_string(bool *r_valid) {
1953 if (has_method(CoreStringName(_to_string))) {
1954 Callable::CallError ce;
1955 Variant ret = callp(CoreStringName(_to_string), nullptr, 0, ce);
1956 if (ce.error == Callable::CallError::CALL_OK) {
1957 if (ret.get_type() != Variant::STRING) {
1958 if (r_valid) {
1959 *r_valid = false;
1960 }
1961 ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringName(_to_string) + ", must be a String.");
1962 }
1963 if (r_valid) {
1964 *r_valid = true;
1965 }
1966 return ret.operator String();
1967 }
1968 }
1969 if (r_valid) {
1970 *r_valid = false;
1971 }
1972 return String();
1973 }
1974
1975 Ref<Script> GDScriptInstance::get_script() const {
1976 return script;
1977 }
1978
1979 ScriptLanguage *GDScriptInstance::get_language() {
1980 return GDScriptLanguage::get_singleton();
1981 }
1982
1983 const Variant GDScriptInstance::get_rpc_config() const {
1984 return script->get_rpc_config();
1985 }
1986
1987 void GDScriptInstance::reload_members() {
1988 #ifdef DEBUG_ENABLED
1989
1990 Vector<Variant> new_members;
1991 new_members.resize(script->member_indices.size());
1992
1993 //pass the values to the new indices
1994 for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
1995 if (member_indices_cache.has(E.key)) {
1996 Variant value = members[member_indices_cache[E.key]];
1997 new_members.write[E.value.index] = value;
1998 }
1999 }
2000
2001 members.resize(new_members.size()); //resize
2002
2003 //apply
2004 members = new_members;
2005
2006 //pass the values to the new indices
2007 member_indices_cache.clear();
2008 for (const KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
2009 member_indices_cache[E.key] = E.value.index;
2010 }
2011
2012 #endif
2013 }
2014
2015 GDScriptInstance::~GDScriptInstance() {
2016 MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
2017
2018 while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
2019 // Order matters since clearing the stack may already cause
2020 // the GDSCriptFunctionState to be destroyed and thus removed from the list.
2021 pending_func_states.remove(E);
2022 GDScriptFunctionState *state = E->self();
2023 ObjectID state_id = state->get_instance_id();
2024 state->_clear_connections();
2025 if (ObjectDB::get_instance(state_id)) {
2026 state->_clear_stack();
2027 }
2028 }
2029
2030 if (script.is_valid() && owner) {
2031 script->instances.erase(owner);
2032 }
2033 }
2034
2035 /************* SCRIPT LANGUAGE **************/
2036
2037 GDScriptLanguage *GDScriptLanguage::singleton = nullptr;
2038
2039 String GDScriptLanguage::get_name() const {
2040 return "GDScript";
2041 }
2042
2043 /* LANGUAGE FUNCTIONS */
2044
2045 void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
2046 if (globals.has(p_name)) {
2047 //overwrite existing
2048 global_array.write[globals[p_name]] = p_value;
2049 return;
2050 }
2051
2052 if (global_array_empty_indexes.size()) {
2053 int index = global_array_empty_indexes[global_array_empty_indexes.size() - 1];
2054 globals[p_name] = index;
2055 global_array.write[index] = p_value;
2056 global_array_empty_indexes.resize(global_array_empty_indexes.size() - 1);
2057 } else {
2058 globals[p_name] = global_array.size();
2059 global_array.push_back(p_value);
2060 _global_array = global_array.ptrw();
2061 }
2062 }
2063
2064 void GDScriptLanguage::_remove_global(const StringName &p_name) {
2065 if (!globals.has(p_name)) {
2066 return;
2067 }
2068 global_array_empty_indexes.push_back(globals[p_name]);
2069 global_array.write[globals[p_name]] = Variant::NIL;
2070 globals.erase(p_name);
2071 }
2072
2073 void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
2074 _add_global(p_variable, p_value);
2075 }
2076
2077 void GDScriptLanguage::add_named_global_constant(const StringName &p_name, const Variant &p_value) {
2078 named_globals[p_name] = p_value;
2079 }
2080
2081 Variant GDScriptLanguage::get_any_global_constant(const StringName &p_name) {
2082 if (named_globals.has(p_name)) {
2083 return named_globals[p_name];
2084 }
2085 if (globals.has(p_name)) {
2086 return _global_array[globals[p_name]];
2087 }
2088 ERR_FAIL_V_MSG(Variant(), vformat("Could not find any global constant with name: %s.", p_name));
2089 }
2090
2091 void GDScriptLanguage::remove_named_global_constant(const StringName &p_name) {
2092 ERR_FAIL_COND(!named_globals.has(p_name));
2093 named_globals.erase(p_name);
2094 }
2095
2096 void GDScriptLanguage::init() {
2097 //populate global constants
2098 int gcc = CoreConstants::get_global_constant_count();
2099 for (int i = 0; i < gcc; i++) {
2100 _add_global(StringName(CoreConstants::get_global_constant_name(i)), CoreConstants::get_global_constant_value(i));
2101 }
2102
2103 _add_global(StringName("PI"), Math::PI);
2104 _add_global(StringName("TAU"), Math::TAU);
2105 _add_global(StringName("INF"), Math::INF);
2106 _add_global(StringName("NAN"), Math::NaN);
2107
2108 //populate native classes
2109
2110 LocalVector<StringName> class_list;
2111 ClassDB::get_class_list(class_list);
2112 for (const StringName &class_name : class_list) {
2113 if (globals.has(class_name)) {
2114 continue;
2115 }
2116 Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(class_name));
2117 _add_global(class_name, nc);
2118 }
2119
2120 //populate singletons
2121
2122 List<Engine::Singleton> singletons;
2123 Engine::get_singleton()->get_singletons(&singletons);
2124 for (const Engine::Singleton &E : singletons) {
2125 _add_global(E.name, E.ptr);
2126 }
2127
2128 #ifdef TOOLS_ENABLED
2129 if (Engine::get_singleton()->is_editor_hint()) {
2130 GDExtensionManager::get_singleton()->connect("extension_loaded", callable_mp(this, &GDScriptLanguage::_extension_loaded));
2131 GDExtensionManager::get_singleton()->connect("extension_unloading", callable_mp(this, &GDScriptLanguage::_extension_unloading));
2132 }
2133 #endif // TOOLS_ENABLED
2134
2135 #ifdef DEBUG_ENABLED
2136 GDScriptParser::update_project_settings();
2137 if (!ProjectSettings::get_singleton()->is_connected("settings_changed", callable_mp_static(&GDScriptParser::update_project_settings))) {
2138 ProjectSettings::get_singleton()->connect("settings_changed", callable_mp_static(&GDScriptParser::update_project_settings));
2139 }
2140 #endif // DEBUG_ENABLED
2141
2142 #ifdef TESTS_ENABLED
2143 GDScriptTests::GDScriptTestRunner::handle_cmdline();
2144 #endif // TESTS_ENABLED
2145 }
2146
2147 #ifdef TOOLS_ENABLED
2148 void GDScriptLanguage::_extension_loaded(const Ref<GDExtension> &p_extension) {
2149 List<StringName> class_list;
2150 ClassDB::get_extension_class_list(p_extension, &class_list);
2151 for (const StringName &n : class_list) {
2152 if (globals.has(n)) {
2153 continue;
2154 }
2155 Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(n));
2156 _add_global(n, nc);
2157 }
2158 }
2159
2160 void GDScriptLanguage::_extension_unloading(const Ref<GDExtension> &p_extension) {
2161 List<StringName> class_list;
2162 ClassDB::get_extension_class_list(p_extension, &class_list);
2163 for (const StringName &n : class_list) {
2164 _remove_global(n);
2165 }
2166 }
2167 #endif
2168
2169 String GDScriptLanguage::get_type() const {
2170 return "GDScript";
2171 }
2172
2173 String GDScriptLanguage::get_extension() const {
2174 return "gd";
2175 }
2176
2177 void GDScriptLanguage::finish() {
2178 if (finishing) {
2179 return;
2180 }
2181 finishing = true;
2182
2183 // Clear the cache before parsing the script_list
2184 GDScriptCache::clear();
2185
2186 // Clear dependencies between scripts, to ensure cyclic references are broken
2187 // (to avoid leaks at exit).
2188 SelfList<GDScript> *s = script_list.first();
2189 while (s) {
2190 // This ensures the current script is not released before we can check
2191 // what's the next one in the list (we can't get the next upfront because we
2192 // don't know if the reference breaking will cause it -or any other after
2193 // it, for that matter- to be released so the next one is not the same as
2194 // before).
2195 Ref<GDScript> scr = s->self();
2196 if (scr.is_valid()) {
2197 for (KeyValue<StringName, GDScriptFunction *> &E : scr->member_functions) {
2198 GDScriptFunction *func = E.value;
2199 for (int i = 0; i < func->argument_types.size(); i++) {
2200 func->argument_types.write[i].script_type_ref = Ref<Script>();
2201 }
2202 func->return_type.script_type_ref = Ref<Script>();
2203 }
2204 for (KeyValue<StringName, GDScript::MemberInfo> &E : scr->member_indices) {
2205 E.value.data_type.script_type_ref = Ref<Script>();
2206 }
2207
2208 // Clear backup for scripts that could slip out of the cyclic reference
2209 // check
2210 scr->clear();
2211 }
2212 s = s->next();
2213 }
2214 script_list.clear();
2215 function_list.clear();
2216
2217 finishing = false;
2218 }
2219
2220 void GDScriptLanguage::profiling_start() {
2221 #ifdef DEBUG_ENABLED
2222 MutexLock lock(mutex);
2223
2224 SelfList<GDScriptFunction> *elem = function_list.first();
2225 while (elem) {
2226 elem->self()->profile.call_count.set(0);
2227 elem->self()->profile.self_time.set(0);
2228 elem->self()->profile.total_time.set(0);
2229 elem->self()->profile.frame_call_count.set(0);
2230 elem->self()->profile.frame_self_time.set(0);
2231 elem->self()->profile.frame_total_time.set(0);
2232 elem->self()->profile.last_frame_call_count = 0;
2233 elem->self()->profile.last_frame_self_time = 0;
2234 elem->self()->profile.last_frame_total_time = 0;
2235 elem->self()->profile.native_calls.clear();
2236 elem->self()->profile.last_native_calls.clear();
2237 elem = elem->next();
2238 }
2239
2240 profiling = true;
2241 #endif
2242 }
2243
2244 void GDScriptLanguage::profiling_set_save_native_calls(bool p_enable) {
2245 #ifdef DEBUG_ENABLED
2246 MutexLock lock(mutex);
2247 profile_native_calls = p_enable;
2248 #endif
2249 }
2250
2251 void GDScriptLanguage::profiling_stop() {
2252 #ifdef DEBUG_ENABLED
2253 MutexLock lock(mutex);
2254
2255 profiling = false;
2256 #endif
2257 }
2258
2259 int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
2260 int current = 0;
2261 #ifdef DEBUG_ENABLED
2262
2263 MutexLock lock(mutex);
2264
2265 profiling_collate_native_call_data(true);
2266 SelfList<GDScriptFunction> *elem = function_list.first();
2267 while (elem) {
2268 if (current >= p_info_max) {
2269 break;
2270 }
2271 int last_non_internal = current;
2272 p_info_arr[current].call_count = elem->self()->profile.call_count.get();
2273 p_info_arr[current].self_time = elem->self()->profile.self_time.get();
2274 p_info_arr[current].total_time = elem->self()->profile.total_time.get();
2275 p_info_arr[current].signature = elem->self()->profile.signature;
2276 current++;
2277
2278 int nat_time = 0;
2279 HashMap<String, GDScriptFunction::Profile::NativeProfile>::ConstIterator nat_calls = elem->self()->profile.native_calls.begin();
2280 while (nat_calls) {
2281 p_info_arr[current].call_count = nat_calls->value.call_count;
2282 p_info_arr[current].total_time = nat_calls->value.total_time;
2283 p_info_arr[current].self_time = nat_calls->value.total_time;
2284 p_info_arr[current].signature = nat_calls->value.signature;
2285 nat_time += nat_calls->value.total_time;
2286 current++;
2287 ++nat_calls;
2288 }
2289 p_info_arr[last_non_internal].internal_time = nat_time;
2290 elem = elem->next();
2291 }
2292 #endif
2293
2294 return current;
2295 }
2296
2297 int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
2298 int current = 0;
2299
2300 #ifdef DEBUG_ENABLED
2301 MutexLock lock(mutex);
2302
2303 profiling_collate_native_call_data(false);
2304 SelfList<GDScriptFunction> *elem = function_list.first();
2305 while (elem) {
2306 if (current >= p_info_max) {
2307 break;
2308 }
2309 if (elem->self()->profile.last_frame_call_count > 0) {
2310 int last_non_internal = current;
2311 p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
2312 p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
2313 p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
2314 p_info_arr[current].signature = elem->self()->profile.signature;
2315 current++;
2316
2317 int nat_time = 0;
2318 HashMap<String, GDScriptFunction::Profile::NativeProfile>::ConstIterator nat_calls = elem->self()->profile.last_native_calls.begin();
2319 while (nat_calls) {
2320 p_info_arr[current].call_count = nat_calls->value.call_count;
2321 p_info_arr[current].total_time = nat_calls->value.total_time;
2322 p_info_arr[current].self_time = nat_calls->value.total_time;
2323 p_info_arr[current].internal_time = nat_calls->value.total_time;
2324 p_info_arr[current].signature = nat_calls->value.signature;
2325 nat_time += nat_calls->value.total_time;
2326 current++;
2327 ++nat_calls;
2328 }
2329 p_info_arr[last_non_internal].internal_time = nat_time;
2330 }
2331 elem = elem->next();
2332 }
2333 #endif
2334
2335 return current;
2336 }
2337
2338 void GDScriptLanguage::profiling_collate_native_call_data(bool p_accumulated) {
2339 #ifdef DEBUG_ENABLED
2340 // The same native call can be called from multiple functions, so join them together here.
2341 // Only use the name of the function (ie signature.split[2]).
2342 HashMap<String, GDScriptFunction::Profile::NativeProfile *> seen_nat_calls;
2343 SelfList<GDScriptFunction> *elem = function_list.first();
2344 while (elem) {
2345 HashMap<String, GDScriptFunction::Profile::NativeProfile> *nat_calls = p_accumulated ? &elem->self()->profile.native_calls : &elem->self()->profile.last_native_calls;
2346 HashMap<String, GDScriptFunction::Profile::NativeProfile>::Iterator it = nat_calls->begin();
2347
2348 while (it != nat_calls->end()) {
2349 Vector<String> sig = it->value.signature.split("::");
2350 HashMap<String, GDScriptFunction::Profile::NativeProfile *>::ConstIterator already_found = seen_nat_calls.find(sig[2]);
2351 if (already_found) {
2352 already_found->value->total_time += it->value.total_time;
2353 already_found->value->call_count += it->value.call_count;
2354 elem->self()->profile.last_native_calls.remove(it);
2355 } else {
2356 seen_nat_calls.insert(sig[2], &it->value);
2357 }
2358 ++it;
2359 }
2360 elem = elem->next();
2361 }
2362 #endif
2363 }
2364
2365 struct GDScriptDepSort {
2366 //must support sorting so inheritance works properly (parent must be reloaded first)
2367 bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
2368 if (A == B) {
2369 return false; //shouldn't happen but..
2370 }
2371 const GDScript *I = B->get_base().ptr();
2372 while (I) {
2373 if (I == A.ptr()) {
2374 // A is a base of B
2375 return true;
2376 }
2377
2378 I = I->get_base().ptr();
2379 }
2380
2381 return false; //not a base
2382 }
2383 };
2384
2385 void GDScriptLanguage::reload_all_scripts() {
2386 #ifdef DEBUG_ENABLED
2387 print_verbose("GDScript: Reloading all scripts");
2388 Array scripts;
2389 {
2390 MutexLock lock(mutex);
2391
2392 SelfList<GDScript> *elem = script_list.first();
2393 while (elem) {
2394 if (elem->self()->get_path().is_resource_file()) {
2395 print_verbose("GDScript: Found: " + elem->self()->get_path());
2396 scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
2397 }
2398 elem = elem->next();
2399 }
2400
2401 #ifdef TOOLS_ENABLED
2402 if (Engine::get_singleton()->is_editor_hint()) {
2403 // Reload all pointers to existing singletons so that tool scripts can work with the reloaded extensions.
2404 List<Engine::Singleton> singletons;
2405 Engine::get_singleton()->get_singletons(&singletons);
2406 for (const Engine::Singleton &E : singletons) {
2407 if (globals.has(E.name)) {
2408 _add_global(E.name, E.ptr);
2409 }
2410 }
2411 }
2412 #endif // TOOLS_ENABLED
2413 }
2414
2415 reload_scripts(scripts, true);
2416 #endif // DEBUG_ENABLED
2417 }
2418
2419 void GDScriptLanguage::reload_scripts(const Array &p_scripts, bool p_soft_reload) {
2420 #ifdef DEBUG_ENABLED
2421
2422 List<Ref<GDScript>> scripts;
2423 {
2424 MutexLock lock(mutex);
2425
2426 SelfList<GDScript> *elem = script_list.first();
2427 while (elem) {
2428 // Scripts will reload all subclasses, so only reload root scripts.
2429 if (elem->self()->is_root_script() && !elem->self()->get_path().is_empty()) {
2430 scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
2431 }
2432 elem = elem->next();
2433 }
2434 }
2435
2436 //when someone asks you why dynamically typed languages are easier to write....
2437
2438 HashMap<Ref<GDScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> to_reload;
2439
2440 //as scripts are going to be reloaded, must proceed without locking here
2441
2442 scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
2443
2444 for (Ref<GDScript> &scr : scripts) {
2445 bool reload = p_scripts.has(scr) || to_reload.has(scr->get_base());
2446
2447 if (!reload) {
2448 continue;
2449 }
2450
2451 to_reload.insert(scr, HashMap<ObjectID, List<Pair<StringName, Variant>>>());
2452
2453 if (!p_soft_reload) {
2454 //save state and remove script from instances
2455 HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[scr];
2456
2457 while (scr->instances.front()) {
2458 Object *obj = scr->instances.front()->get();
2459 //save instance info
2460 List<Pair<StringName, Variant>> state;
2461 if (obj->get_script_instance()) {
2462 obj->get_script_instance()->get_property_state(state);
2463 map[obj->get_instance_id()] = state;
2464 obj->set_script(Variant());
2465 }
2466 }
2467
2468 //same thing for placeholders
2469 #ifdef TOOLS_ENABLED
2470
2471 while (scr->placeholders.size()) {
2472 Object *obj = (*scr->placeholders.begin())->get_owner();
2473
2474 //save instance info
2475 if (obj->get_script_instance()) {
2476 map.insert(obj->get_instance_id(), List<Pair<StringName, Variant>>());
2477 List<Pair<StringName, Variant>> &state = map[obj->get_instance_id()];
2478 obj->get_script_instance()->get_property_state(state);
2479 obj->set_script(Variant());
2480 } else {
2481 // no instance found. Let's remove it so we don't loop forever
2482 scr->placeholders.erase(*scr->placeholders.begin());
2483 }
2484 }
2485
2486 #endif // TOOLS_ENABLED
2487
2488 for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : scr->pending_reload_state) {
2489 map[F.key] = F.value; //pending to reload, use this one instead
2490 }
2491 }
2492 }
2493
2494 for (KeyValue<Ref<GDScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> &E : to_reload) {
2495 Ref<GDScript> scr = E.key;
2496 print_verbose("GDScript: Reloading: " + scr->get_path());
2497 if (scr->is_built_in()) {
2498 // TODO: It would be nice to do it more efficiently than loading the whole scene again.
2499 Ref<PackedScene> scene = ResourceLoader::load(scr->get_path().get_slice("::", 0), "", ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP);
2500 ERR_CONTINUE(scene.is_null());
2501
2502 Ref<SceneState> state = scene->get_state();
2503 Ref<GDScript> fresh = state->get_sub_resource(scr->get_path());
2504 ERR_CONTINUE(fresh.is_null());
2505
2506 scr->set_source_code(fresh->get_source_code());
2507 } else {
2508 scr->load_source_code(scr->get_path());
2509 }
2510 scr->reload(p_soft_reload);
2511
2512 //restore state if saved
2513 for (KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : E.value) {
2514 List<Pair<StringName, Variant>> &saved_state = F.value;
2515
2516 Object *obj = ObjectDB::get_instance(F.key);
2517 if (!obj) {
2518 continue;
2519 }
2520
2521 if (!p_soft_reload) {
2522 //clear it just in case (may be a pending reload state)
2523 obj->set_script(Variant());
2524 }
2525 obj->set_script(scr);
2526
2527 ScriptInstance *script_inst = obj->get_script_instance();
2528
2529 if (!script_inst) {
2530 //failed, save reload state for next time if not saved
2531 if (!scr->pending_reload_state.has(obj->get_instance_id())) {
2532 scr->pending_reload_state[obj->get_instance_id()] = saved_state;
2533 }
2534 continue;
2535 }
2536
2537 if (script_inst->is_placeholder() && scr->is_placeholder_fallback_enabled()) {
2538 PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_inst);
2539 for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
2540 placeholder->property_set_fallback(G->get().first, G->get().second);
2541 }
2542 } else {
2543 for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
2544 script_inst->set(G->get().first, G->get().second);
2545 }
2546 }
2547
2548 scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
2549 }
2550
2551 //if instance states were saved, set them!
2552 }
2553
2554 #endif // DEBUG_ENABLED
2555 }
2556
2557 void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
2558 Array scripts = { p_script };
2559 reload_scripts(scripts, p_soft_reload);
2560 }
2561
2562 void GDScriptLanguage::frame() {
2563 #ifdef DEBUG_ENABLED
2564 if (profiling) {
2565 MutexLock lock(mutex);
2566
2567 SelfList<GDScriptFunction> *elem = function_list.first();
2568 while (elem) {
2569 elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count.get();
2570 elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time.get();
2571 elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time.get();
2572 elem->self()->profile.last_native_calls = elem->self()->profile.native_calls;
2573 elem->self()->profile.frame_call_count.set(0);
2574 elem->self()->profile.frame_self_time.set(0);
2575 elem->self()->profile.frame_total_time.set(0);
2576 elem->self()->profile.native_calls.clear();
2577 elem = elem->next();
2578 }
2579 }
2580
2581 #endif
2582 }
2583
2584 /* EDITOR FUNCTIONS */
2585 Vector<String> GDScriptLanguage::get_reserved_words() const {
2586 // Please keep alphabetical order within categories.
2587 static const Vector<String> ret = {
2588 // Control flow.
2589 "break",
2590 "continue",
2591 "elif",
2592 "else",
2593 "for",
2594 "if",
2595 "match",
2596 "pass",
2597 "return",
2598 "when",
2599 "while",
2600 // Declarations.
2601 "class",
2602 "class_name",
2603 "const",
2604 "enum",
2605 "extends",
2606 "func",
2607 "namespace", // Reserved for potential future use.
2608 "signal",
2609 "static",
2610 "trait", // Reserved for potential future use.
2611 "var",
2612 // Other keywords.
2613 "await",
2614 "breakpoint",
2615 "self",
2616 "super",
2617 "yield", // Reserved for potential future use.
2618 // Operators.
2619 "and",
2620 "as",
2621 "in",
2622 "is",
2623 "not",
2624 "or",
2625 // Special values (tokenizer treats them as literals, not as tokens).
2626 "false",
2627 "null",
2628 "true",
2629 // Constants.
2630 "INF",
2631 "NAN",
2632 "PI",
2633 "TAU",
2634 // Functions (highlighter uses global function color instead).
2635 "assert",
2636 "preload",
2637 // Types (highlighter uses type color instead).
2638 "void",
2639 };
2640
2641 return ret;
2642 }
2643
2644 bool GDScriptLanguage::is_control_flow_keyword(const String &p_keyword) const {
2645 // Please keep alphabetical order.
2646 return p_keyword == "break" ||
2647 p_keyword == "continue" ||
2648 p_keyword == "elif" ||
2649 p_keyword == "else" ||
2650 p_keyword == "for" ||
2651 p_keyword == "if" ||
2652 p_keyword == "match" ||
2653 p_keyword == "pass" ||
2654 p_keyword == "return" ||
2655 p_keyword == "when" ||
2656 p_keyword == "while";
2657 }
2658
2659 bool GDScriptLanguage::handles_global_class_type(const String &p_type) const {
2660 return p_type == "GDScript";
2661 }
2662
2663 String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path, bool *r_is_abstract, bool *r_is_tool) const {
2664 LocalVector<String> r_vec;
2665 return _get_global_class_name(p_path, r_base_type, r_icon_path, r_is_abstract, r_is_tool, r_vec);
2666 }
2667
2668 String GDScriptLanguage::_get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path, bool *r_is_abstract, bool *r_is_tool, LocalVector<String> &r_visited) const {
2669 if (r_visited.has(p_path)) {
2670 return String();
2671 }
2672
2673 r_visited.push_back(p_path);
2674
2675 Error err;
2676 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
2677 if (err) {
2678 return String();
2679 }
2680
2681 String source = f->get_as_utf8_string();
2682
2683 GDScriptParser parser;
2684 err = parser.parse(source, p_path, false, false);
2685
2686 const GDScriptParser::ClassNode *c = parser.get_tree();
2687 if (!c) {
2688 return String(); // No class parsed.
2689 }
2690
2691 /* **WARNING**
2692 *
2693 * This function is written with the goal to be *extremely* error tolerant, as such
2694 * it should meet the following requirements:
2695 *
2696 * - It must not rely on the analyzer (in fact, the analyzer must not be used here),
2697 * because at the time global classes are parsed, the dependencies may not be present
2698 * yet, hence the function will fail (which is unintended).
2699 * - It must not fail even if the parsing fails, because even if the file is broken,
2700 * it should attempt its best to retrieve the inheritance metadata.
2701 *
2702 * Before changing this function, please ask the current maintainer of EditorFileSystem.
2703 */
2704
2705 if (r_base_type) {
2706 const GDScriptParser::ClassNode *subclass = c;
2707 String path = p_path;
2708 GDScriptParser subparser;
2709 while (subclass) {
2710 if (subclass->extends_used) {
2711 if (!subclass->extends_path.is_empty()) {
2712 if (subclass->extends.is_empty()) {
2713 // We only care about the referenced class_name.
2714 _ALLOW_DISCARD_ _get_global_class_name(subclass->extends_path, r_base_type, nullptr, nullptr, nullptr, r_visited);
2715 subclass = nullptr;
2716 break;
2717 } else {
2718 Vector<GDScriptParser::IdentifierNode *> extend_classes = subclass->extends;
2719
2720 Ref<FileAccess> subfile = FileAccess::open(subclass->extends_path, FileAccess::READ);
2721 if (subfile.is_null()) {
2722 break;
2723 }
2724 String subsource = subfile->get_as_utf8_string();
2725
2726 if (subsource.is_empty()) {
2727 break;
2728 }
2729 String subpath = subclass->extends_path;
2730 if (subpath.is_relative_path()) {
2731 subpath = path.get_base_dir().path_join(subpath).simplify_path();
2732 }
2733
2734 if (OK != subparser.parse(subsource, subpath, false)) {
2735 break;
2736 }
2737 path = subpath;
2738 subclass = subparser.get_tree();
2739
2740 while (extend_classes.size() > 0) {
2741 bool found = false;
2742 for (int i = 0; i < subclass->members.size(); i++) {
2743 if (subclass->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
2744 continue;
2745 }
2746
2747 const GDScriptParser::ClassNode *inner_class = subclass->members[i].m_class;
2748 if (inner_class->identifier->name == extend_classes[0]->name) {
2749 extend_classes.remove_at(0);
2750 found = true;
2751 subclass = inner_class;
2752 break;
2753 }
2754 }
2755 if (!found) {
2756 subclass = nullptr;
2757 break;
2758 }
2759 }
2760 }
2761 } else if (subclass->extends.size() == 1) {
2762 *r_base_type = subclass->extends[0]->name;
2763 subclass = nullptr;
2764 } else {
2765 break;
2766 }
2767 } else {
2768 *r_base_type = "RefCounted";
2769 subclass = nullptr;
2770 }
2771 }
2772 }
2773 if (r_icon_path) {
2774 *r_icon_path = c->simplified_icon_path;
2775 }
2776 if (r_is_abstract) {
2777 *r_is_abstract = c->is_abstract;
2778 }
2779 if (r_is_tool) {
2780 *r_is_tool = parser.is_tool();
2781 }
2782 return c->identifier != nullptr ? String(c->identifier->name) : String();
2783 }
2784
2785 thread_local GDScriptLanguage::CallLevel *GDScriptLanguage::_call_stack = nullptr;
2786 thread_local uint32_t GDScriptLanguage::_call_stack_size = 0;
2787
2788 GDScriptLanguage::CallLevel *GDScriptLanguage::_get_stack_level(uint32_t p_level) {
2789 ERR_FAIL_UNSIGNED_INDEX_V(p_level, _call_stack_size, nullptr);
2790 CallLevel *level = _call_stack; // Start from top
2791 uint32_t level_index = 0;
2792 while (p_level > level_index) {
2793 level_index++;
2794 level = level->prev;
2795 }
2796 return level;
2797 }
2798
2799 GDScriptLanguage::GDScriptLanguage() {
2800 ERR_FAIL_COND(singleton);
2801 singleton = this;
2802 strings._init = StringName("_init");
2803 strings._static_init = StringName("_static_init");
2804 strings._notification = StringName("_notification");
2805 strings._set = StringName("_set");
2806 strings._get = StringName("_get");
2807 strings._get_property_list = StringName("_get_property_list");
2808 strings._validate_property = StringName("_validate_property");
2809 strings._property_can_revert = StringName("_property_can_revert");
2810 strings._property_get_revert = StringName("_property_get_revert");
2811 strings._script_source = StringName("script/source");
2812 _debug_parse_err_line = -1;
2813 _debug_parse_err_file = "";
2814
2815 #ifdef DEBUG_ENABLED
2816 profiling = false;
2817 profile_native_calls = false;
2818 script_frame_time = 0;
2819 #endif // DEBUG_ENABLED
2820
2821 _debug_max_call_stack = GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "debug/settings/gdscript/max_call_stack", PROPERTY_HINT_RANGE, "512," + itos(GDScriptFunction::MAX_CALL_DEPTH - 1) + ",1"), 1024);
2822 track_call_stack = GLOBAL_DEF_RST("debug/settings/gdscript/always_track_call_stacks", false);
2823 track_locals = GLOBAL_DEF_RST("debug/settings/gdscript/always_track_local_variables", false);
2824
2825 #ifdef DEBUG_ENABLED
2826 track_call_stack = true;
2827 track_locals = track_locals || EngineDebugger::is_active();
2828
2829 GLOBAL_DEF("debug/gdscript/warnings/enable", true);
2830
2831 GLOBAL_DEF(PropertyInfo(Variant::DICTIONARY,
2832 "debug/gdscript/warnings/directory_rules",
2833 PROPERTY_HINT_TYPE_STRING,
2834 vformat("%d/%d:;%d/%d:Exclude,Include", Variant::STRING, PROPERTY_HINT_DIR, Variant::INT, PROPERTY_HINT_ENUM)),
2835 Dictionary({ { "res://addons", GDScriptParser::WarningDirectoryRule::DECISION_EXCLUDE } }));
2836
2837 for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
2838 const GDScriptWarning::Code code = (GDScriptWarning::Code)i;
2839 const Variant default_value = GDScriptWarning::get_default_value(code);
2840 GLOBAL_DEF(GDScriptWarning::get_property_info(code), default_value);
2841
2842 #ifndef DISABLE_DEPRECATED
2843 if (i >= GDScriptWarning::FIRST_DEPRECATED_WARNING) {
2844 const String setting_path = GDScriptWarning::get_setting_path_from_code(code);
2845 ProjectSettings::get_singleton()->set_as_internal(setting_path, true);
2846 }
2847 #endif // DISABLE_DEPRECATED
2848 }
2849
2850 // TODO: This setting has nothing to do with warnings. It should be moved at the next compatibility breakage,
2851 // if the setting is still relevant at that time.
2852 GLOBAL_DEF("debug/gdscript/warnings/renamed_in_godot_4_hint", true);
2853 #endif // DEBUG_ENABLED
2854 }
2855
2856 GDScriptLanguage::~GDScriptLanguage() {
2857 singleton = nullptr;
2858 }
2859
2860 void GDScriptLanguage::add_orphan_subclass(const String &p_qualified_name, const ObjectID &p_subclass) {
2861 orphan_subclasses[p_qualified_name] = p_subclass;
2862 }
2863
2864 Ref<GDScript> GDScriptLanguage::get_orphan_subclass(const String &p_qualified_name) {
2865 HashMap<String, ObjectID>::Iterator orphan_subclass_element = orphan_subclasses.find(p_qualified_name);
2866 if (!orphan_subclass_element) {
2867 return Ref<GDScript>();
2868 }
2869 ObjectID orphan_subclass = orphan_subclass_element->value;
2870 Object *obj = ObjectDB::get_instance(orphan_subclass);
2871 orphan_subclasses.remove(orphan_subclass_element);
2872 if (!obj) {
2873 return Ref<GDScript>();
2874 }
2875 return Ref<GDScript>(Object::cast_to<GDScript>(obj));
2876 }
2877
2878 Ref<GDScript> GDScriptLanguage::get_script_by_fully_qualified_name(const String &p_name) {
2879 {
2880 MutexLock lock(mutex);
2881
2882 SelfList<GDScript> *elem = script_list.first();
2883 while (elem) {
2884 GDScript *scr = elem->self();
2885 if (scr->fully_qualified_name == p_name) {
2886 return scr;
2887 }
2888 elem = elem->next();
2889 }
2890 }
2891
2892 Ref<GDScript> scr;
2893 scr.instantiate();
2894 scr->fully_qualified_name = p_name;
2895 return scr;
2896 }
2897
2898 /*************** RESOURCE ***************/
2899
2900 Ref<Resource> ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
2901 Error err;
2902 bool ignoring = p_cache_mode == CACHE_MODE_IGNORE || p_cache_mode == CACHE_MODE_IGNORE_DEEP;
2903 Ref<GDScript> scr = GDScriptCache::get_full_script(p_original_path, err, "", ignoring);
2904
2905 if (err && scr.is_valid()) {
2906 // If !scr.is_valid(), the error was likely from scr->load_source_code(), which already generates an error.
2907 ERR_PRINT_ED(vformat(R"(Failed to load script "%s" with error "%s".)", p_original_path, error_names[err]));
2908 }
2909
2910 if (r_error) {
2911 // Don't fail loading because of parsing error.
2912 *r_error = scr.is_valid() ? OK : err;
2913 }
2914
2915 return scr;
2916 }
2917
2918 void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
2919 p_extensions->push_back("gd");
2920 p_extensions->push_back("gdc");
2921 }
2922
2923 bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
2924 return (p_type == "Script" || p_type == "GDScript");
2925 }
2926
2927 String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
2928 String el = p_path.get_extension().to_lower();
2929 if (el == "gd" || el == "gdc") {
2930 return "GDScript";
2931 }
2932 return "";
2933 }
2934
2935 void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
2936 Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
2937 ERR_FAIL_COND_MSG(file.is_null(), "Cannot open file '" + p_path + "'.");
2938
2939 String source = file->get_as_utf8_string();
2940 if (source.is_empty()) {
2941 return;
2942 }
2943
2944 GDScriptParser parser;
2945 if (OK != parser.parse(source, p_path, false)) {
2946 return;
2947 }
2948
2949 for (const String &E : parser.get_dependencies()) {
2950 p_dependencies->push_back(E);
2951 }
2952 }
2953
2954 void ResourceFormatLoaderGDScript::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
2955 Ref<GDScript> scr = ResourceLoader::load(p_path);
2956 if (scr.is_null()) {
2957 return;
2958 }
2959
2960 const String source = scr->get_source_code();
2961 GDScriptTokenizerText tokenizer;
2962 tokenizer.set_source_code(source);
2963 GDScriptTokenizer::Token current = tokenizer.scan();
2964 while (current.type != GDScriptTokenizer::Token::TK_EOF) {
2965 if (!current.is_identifier()) {
2966 current = tokenizer.scan();
2967 continue;
2968 }
2969
2970 int insert_idx = 0;
2971 for (int i = 0; i < current.start_line - 1; i++) {
2972 insert_idx = source.find("\n", insert_idx) + 1;
2973 }
2974 // Insert the "cursor" character, needed for the lookup to work.
2975 const String source_with_cursor = source.insert(insert_idx + current.start_column, String::chr(0xFFFF));
2976
2977 ScriptLanguage::LookupResult result;
2978 if (scr->get_language()->lookup_code(source_with_cursor, current.get_identifier(), p_path, nullptr, result) == OK) {
2979 if (!result.class_name.is_empty() && ClassDB::class_exists(result.class_name)) {
2980 r_classes->insert(result.class_name);
2981 }
2982
2983 if (result.type == ScriptLanguage::LOOKUP_RESULT_CLASS_PROPERTY) {
2984 PropertyInfo prop;
2985 if (ClassDB::get_property_info(result.class_name, result.class_member, &prop)) {
2986 if (!prop.class_name.is_empty() && ClassDB::class_exists(prop.class_name)) {
2987 r_classes->insert(prop.class_name);
2988 }
2989 if (!prop.hint_string.is_empty() && ClassDB::class_exists(prop.hint_string)) {
2990 r_classes->insert(prop.hint_string);
2991 }
2992 }
2993 } else if (result.type == ScriptLanguage::LOOKUP_RESULT_CLASS_METHOD) {
2994 MethodInfo met;
2995 if (ClassDB::get_method_info(result.class_name, result.class_member, &met)) {
2996 if (!met.return_val.class_name.is_empty() && ClassDB::class_exists(met.return_val.class_name)) {
2997 r_classes->insert(met.return_val.class_name);
2998 }
2999 if (!met.return_val.hint_string.is_empty() && ClassDB::class_exists(met.return_val.hint_string)) {
3000 r_classes->insert(met.return_val.hint_string);
3001 }
3002 }
3003 }
3004 }
3005
3006 current = tokenizer.scan();
3007 }
3008 }
3009
3010 Error ResourceFormatSaverGDScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
3011 Ref<GDScript> sqscr = p_resource;
3012 ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
3013
3014 String source = sqscr->get_source_code();
3015
3016 {
3017 Error err;
3018 Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
3019
3020 ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'.");
3021
3022 file->store_string(source);
3023 if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
3024 return ERR_CANT_CREATE;
3025 }
3026 }
3027
3028 if (ScriptServer::is_reload_scripts_on_save_enabled()) {
3029 GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, true);
3030 }
3031
3032 return OK;
3033 }
3034
3035 void ResourceFormatSaverGDScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
3036 if (Object::cast_to<GDScript>(*p_resource)) {
3037 p_extensions->push_back("gd");
3038 }
3039 }
3040
3041 bool ResourceFormatSaverGDScript::recognize(const Ref<Resource> &p_resource) const {
3042 return Object::cast_to<GDScript>(*p_resource) != nullptr;
3043 }