-
-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
csharp_script.cpp
2938 lines (2325 loc) · 88 KB
/
csharp_script.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* csharp_script.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "csharp_script.h"
#include "godotsharp_dirs.h"
#include "managed_callable.h"
#include "mono_gd/gd_mono_cache.h"
#include "signal_awaiter_utils.h"
#include "utils/macros.h"
#include "utils/naming_utils.h"
#include "utils/path_utils.h"
#include "utils/string_utils.h"
#ifdef DEBUG_METHODS_ENABLED
#include "class_db_api_json.h"
#endif
#ifdef TOOLS_ENABLED
#include "editor/editor_internal_calls.h"
#include "editor/script_templates/templates.gen.h"
#endif
#include "core/config/project_settings.h"
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
#include "core/io/file_access.h"
#include "core/os/mutex.h"
#include "core/os/os.h"
#include "core/os/thread.h"
#include "servers/text_server.h"
#ifdef TOOLS_ENABLED
#include "core/os/keyboard.h"
#include "editor/editor_file_system.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
#include "editor/inspector_dock.h"
#include "editor/node_dock.h"
#endif
#include <stdint.h>
// Types that will be skipped over (in favor of their base types) when setting up instance bindings.
// This must be a superset of `ignored_types` in bindings_generator.cpp.
const Vector<String> ignored_types = {};
#ifdef TOOLS_ENABLED
static bool _create_project_solution_if_needed() {
CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolutionIfNeeded");
}
#endif
CSharpLanguage *CSharpLanguage::singleton = nullptr;
GDExtensionInstanceBindingCallbacks CSharpLanguage::_instance_binding_callbacks = {
&_instance_binding_create_callback,
&_instance_binding_free_callback,
&_instance_binding_reference_callback
};
String CSharpLanguage::get_name() const {
return "C#";
}
String CSharpLanguage::get_type() const {
return "CSharpScript";
}
String CSharpLanguage::get_extension() const {
return "cs";
}
void CSharpLanguage::init() {
#ifdef TOOLS_ENABLED
if (OS::get_singleton()->get_cmdline_args().find("--generate-mono-glue")) {
print_verbose(".NET: Skipping runtime initialization because glue generation is enabled.");
return;
}
#endif
#ifdef DEBUG_METHODS_ENABLED
if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
#ifdef TOOLS_ENABLED
class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
#endif
}
#endif
GLOBAL_DEF("dotnet/project/assembly_name", "");
#ifdef TOOLS_ENABLED
GLOBAL_DEF("dotnet/project/solution_directory", "");
GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
#endif
#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(&_editor_init_callback);
#endif
gdmono = memnew(GDMono);
// Initialize only if the project uses C#.
if (gdmono->should_initialize()) {
gdmono->initialize();
}
}
void CSharpLanguage::finish() {
finalize();
}
void CSharpLanguage::finalize() {
if (finalized) {
return;
}
if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
GDMonoCache::managed_callbacks.DisposablesTracker_OnGodotShuttingDown();
}
finalizing = true;
// Make sure all script binding gchandles are released before finalizing GDMono
for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
CSharpScriptBinding &script_binding = E.value;
if (!script_binding.gchandle.is_released()) {
script_binding.gchandle.release();
script_binding.inited = false;
}
}
if (gdmono) {
memdelete(gdmono);
gdmono = nullptr;
}
// Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
script_bindings.clear();
#ifdef DEBUG_ENABLED
for (const KeyValue<ObjectID, int> &E : unsafe_object_references) {
const ObjectID &id = E.key;
Object *obj = ObjectDB::get_instance(id);
if (obj) {
ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
} else {
ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
}
}
#endif
memdelete(managed_callable_middleman);
finalizing = false;
finalized = true;
}
void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
static const char *_reserved_words[] = {
// Reserved keywords
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while",
// Contextual keywords. Not reserved words, but I guess we should include
// them because this seems to be used only for syntax highlighting.
"add",
"alias",
"ascending",
"async",
"await",
"by",
"descending",
"dynamic",
"equals",
"from",
"get",
"global",
"group",
"into",
"join",
"let",
"nameof",
"on",
"orderby",
"partial",
"remove",
"select",
"set",
"value",
"var",
"when",
"where",
"yield",
nullptr
};
const char **w = _reserved_words;
while (*w) {
p_words->push_back(*w);
w++;
}
}
bool CSharpLanguage::is_control_flow_keyword(String p_keyword) const {
return p_keyword == "break" ||
p_keyword == "case" ||
p_keyword == "catch" ||
p_keyword == "continue" ||
p_keyword == "default" ||
p_keyword == "do" ||
p_keyword == "else" ||
p_keyword == "finally" ||
p_keyword == "for" ||
p_keyword == "foreach" ||
p_keyword == "goto" ||
p_keyword == "if" ||
p_keyword == "return" ||
p_keyword == "switch" ||
p_keyword == "throw" ||
p_keyword == "try" ||
p_keyword == "while";
}
void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
p_delimiters->push_back("//"); // single-line comment
p_delimiters->push_back("/* */"); // delimited comment
}
void CSharpLanguage::get_doc_comment_delimiters(List<String> *p_delimiters) const {
p_delimiters->push_back("///"); // single-line doc comment
p_delimiters->push_back("/** */"); // delimited doc comment
}
void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
p_delimiters->push_back("' '"); // character literal
p_delimiters->push_back("\" \""); // regular string literal
p_delimiters->push_back("@\" \""); // verbatim string literal
// Generic string highlighting suffices as a workaround for now.
}
static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
String base_class = pascal_to_pascal_case(p_base_class_name);
if (p_class_name == base_class) {
base_class = "Godot." + base_class;
}
return base_class;
}
bool CSharpLanguage::is_using_templates() {
return true;
}
Ref<Script> CSharpLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
Ref<CSharpScript> scr;
scr.instantiate();
String class_name_no_spaces = p_class_name.replace(" ", "_");
String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
String processed_template = p_template;
processed_template = processed_template.replace("_BINDINGS_NAMESPACE_", BINDINGS_NAMESPACE)
.replace("_BASE_", base_class_name)
.replace("_CLASS_", class_name_no_spaces)
.replace("_TS_", _get_indentation());
scr->set_source_code(processed_template);
return scr;
}
Vector<ScriptLanguage::ScriptTemplate> CSharpLanguage::get_built_in_templates(StringName p_object) {
Vector<ScriptLanguage::ScriptTemplate> templates;
#ifdef TOOLS_ENABLED
for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
if (TEMPLATES[i].inherit == p_object) {
templates.append(TEMPLATES[i]);
}
}
#endif
return templates;
}
String CSharpLanguage::validate_path(const String &p_path) const {
String class_name = p_path.get_file().get_basename();
List<String> keywords;
get_reserved_words(&keywords);
if (keywords.find(class_name)) {
return RTR("Class name can't be a reserved keyword");
}
if (!TS->is_valid_identifier(class_name)) {
return RTR("Class name must be a valid identifier");
}
return "";
}
Script *CSharpLanguage::create_script() const {
return memnew(CSharpScript);
}
bool CSharpLanguage::supports_builtin_mode() const {
return false;
}
#ifdef TOOLS_ENABLED
struct VariantCsName {
Variant::Type variant_type;
const String cs_type;
};
static String variant_type_to_managed_name(const String &p_var_type_name) {
if (p_var_type_name.is_empty()) {
return "Variant";
}
if (ClassDB::class_exists(p_var_type_name)) {
return pascal_to_pascal_case(p_var_type_name);
}
if (p_var_type_name == Variant::get_type_name(Variant::OBJECT)) {
return "GodotObject";
}
if (p_var_type_name == Variant::get_type_name(Variant::INT)) {
return "long";
}
if (p_var_type_name == Variant::get_type_name(Variant::FLOAT)) {
return "double";
}
if (p_var_type_name == Variant::get_type_name(Variant::STRING)) {
return "string"; // I prefer this one >:[
}
if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY)) {
return "Collections.Dictionary";
}
if (p_var_type_name.begins_with(Variant::get_type_name(Variant::ARRAY) + "[")) {
String element_type = p_var_type_name.trim_prefix(Variant::get_type_name(Variant::ARRAY) + "[").trim_suffix("]");
return "Collections.Array<" + variant_type_to_managed_name(element_type) + ">";
}
if (p_var_type_name == Variant::get_type_name(Variant::ARRAY)) {
return "Collections.Array";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY)) {
return "byte[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY)) {
return "int[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY)) {
return "long[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY)) {
return "float[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY)) {
return "double[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY)) {
return "string[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY)) {
return "Vector2[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY)) {
return "Vector3[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY)) {
return "Color[]";
}
if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL)) {
return "Signal";
}
const VariantCsName var_types[] = {
{ Variant::BOOL, "bool" },
{ Variant::INT, "long" },
{ Variant::VECTOR2, "Vector2" },
{ Variant::VECTOR2I, "Vector2I" },
{ Variant::RECT2, "Rect2" },
{ Variant::RECT2I, "Rect2I" },
{ Variant::VECTOR3, "Vector3" },
{ Variant::VECTOR3I, "Vector3I" },
{ Variant::TRANSFORM2D, "Transform2D" },
{ Variant::VECTOR4, "Vector4" },
{ Variant::VECTOR4I, "Vector4I" },
{ Variant::PLANE, "Plane" },
{ Variant::QUATERNION, "Quaternion" },
{ Variant::AABB, "Aabb" },
{ Variant::BASIS, "Basis" },
{ Variant::TRANSFORM3D, "Transform3D" },
{ Variant::PROJECTION, "Projection" },
{ Variant::COLOR, "Color" },
{ Variant::STRING_NAME, "StringName" },
{ Variant::NODE_PATH, "NodePath" },
{ Variant::RID, "Rid" },
{ Variant::CALLABLE, "Callable" },
};
for (unsigned int i = 0; i < sizeof(var_types) / sizeof(VariantCsName); i++) {
if (p_var_type_name == Variant::get_type_name(var_types[i].variant_type)) {
return var_types[i].cs_type;
}
}
return "Variant";
}
String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
// FIXME
// - Due to Godot's API limitation this just appends the function to the end of the file
// - Use fully qualified name if there is ambiguity
String s = "private void " + p_name + "(";
for (int i = 0; i < p_args.size(); i++) {
const String &arg = p_args[i];
if (i > 0) {
s += ", ";
}
s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
}
s += ")\n{\n // Replace with function body.\n}\n";
return s;
}
#else
String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
return String();
}
#endif
String CSharpLanguage::_get_indentation() const {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
if (use_space_indentation) {
int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
return String(" ").repeat(indent_size);
}
}
#endif
return "\t";
}
bool CSharpLanguage::handles_global_class_type(const String &p_type) const {
return p_type == get_type();
}
String CSharpLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
Ref<CSharpScript> scr = ResourceLoader::load(p_path, get_type());
// Always assign r_base_type and r_icon_path, even if the script
// is not a global one. In the case that it is not a global script,
// return an empty string AFTER assigning the return parameters.
// See GDScriptLanguage::get_global_class_name() in modules/gdscript/gdscript.cpp
if (!scr.is_valid() || !scr->valid) {
// Invalid script.
return String();
}
if (r_icon_path) {
if (scr->icon_path.is_empty() || scr->icon_path.is_absolute_path()) {
*r_icon_path = scr->icon_path.simplify_path();
} else if (scr->icon_path.is_relative_path()) {
*r_icon_path = p_path.get_base_dir().path_join(scr->icon_path).simplify_path();
}
}
if (r_base_type) {
bool found_global_base_script = false;
const CSharpScript *top = scr->base_script.ptr();
while (top != nullptr) {
if (top->global_class) {
*r_base_type = top->class_name;
found_global_base_script = true;
break;
}
top = top->base_script.ptr();
}
if (!found_global_base_script) {
*r_base_type = scr->get_instance_base_type();
}
}
return scr->global_class ? scr->class_name : String();
}
String CSharpLanguage::debug_get_error() const {
return _debug_error;
}
int CSharpLanguage::debug_get_stack_level_count() const {
if (_debug_parse_err_line >= 0) {
return 1;
}
// TODO: StackTrace
return 1;
}
int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
if (_debug_parse_err_line >= 0) {
return _debug_parse_err_line;
}
// TODO: StackTrace
return 1;
}
String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
if (_debug_parse_err_line >= 0) {
return String();
}
// TODO: StackTrace
return String();
}
String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
if (_debug_parse_err_line >= 0) {
return _debug_parse_err_file;
}
// TODO: StackTrace
return String();
}
Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
#ifdef DEBUG_ENABLED
// Printing an error here will result in endless recursion, so we must be careful
static thread_local bool _recursion_flag_ = false;
if (_recursion_flag_) {
return Vector<StackInfo>();
}
_recursion_flag_ = true;
SCOPE_EXIT {
_recursion_flag_ = false;
};
if (!gdmono || !gdmono->is_runtime_initialized()) {
return Vector<StackInfo>();
}
Vector<StackInfo> si;
if (GDMonoCache::godot_api_cache_updated) {
GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
}
return si;
#else
return Vector<StackInfo>();
#endif
}
void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
#ifdef DEBUG_ENABLED
MutexLock lock(unsafe_object_references_lock);
ObjectID id = p_obj->get_instance_id();
unsafe_object_references[id]++;
#endif
}
void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
#ifdef DEBUG_ENABLED
MutexLock lock(unsafe_object_references_lock);
ObjectID id = p_obj->get_instance_id();
HashMap<ObjectID, int>::Iterator elem = unsafe_object_references.find(id);
ERR_FAIL_NULL(elem);
if (--elem->value == 0) {
unsafe_object_references.remove(elem);
}
#endif
}
void CSharpLanguage::frame() {
if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
}
}
struct CSharpScriptDepSort {
// Must support sorting so inheritance works properly (parent must be reloaded first)
bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
if (A == B) {
// Shouldn't happen but just in case...
return false;
}
const Script *I = B->get_base_script().ptr();
while (I) {
if (I == A.ptr()) {
// A is a base of B
return true;
}
I = I->get_base_script().ptr();
}
// A isn't a base of B
return false;
}
};
void CSharpLanguage::reload_all_scripts() {
#ifdef GD_MONO_HOT_RELOAD
if (is_assembly_reloading_needed()) {
reload_assemblies(false);
}
#endif
}
void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
(void)p_script; // UNUSED
CRASH_COND(!Engine::get_singleton()->is_editor_hint());
#ifdef TOOLS_ENABLED
get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
#endif
#ifdef GD_MONO_HOT_RELOAD
if (is_assembly_reloading_needed()) {
reload_assemblies(p_soft_reload);
}
#endif
}
#ifdef GD_MONO_HOT_RELOAD
bool CSharpLanguage::is_assembly_reloading_needed() {
ERR_FAIL_NULL_V(gdmono, false);
if (!gdmono->is_runtime_initialized()) {
return false;
}
String assembly_path = gdmono->get_project_assembly_path();
if (!assembly_path.is_empty()) {
if (!FileAccess::exists(assembly_path)) {
return false; // No assembly to load
}
if (FileAccess::get_modified_time(assembly_path) <= gdmono->get_project_assembly_modified_time()) {
return false; // Already up to date
}
} else {
String assembly_name = path::get_csharp_project_name();
assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
.path_join(assembly_name + ".dll");
assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
if (!FileAccess::exists(assembly_path)) {
return false; // No assembly to load
}
}
return true;
}
void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
ERR_FAIL_NULL(gdmono);
if (!gdmono->is_runtime_initialized()) {
return;
}
if (!Engine::get_singleton()->is_editor_hint()) {
// We disable collectible assemblies in the game player, because the limitations cause
// issues with mocking libraries. As such, we can only reload assemblies in the editor.
return;
}
print_verbose(".NET: Reloading assemblies...");
// There is no soft reloading with Mono. It's always hard reloading.
List<Ref<CSharpScript>> scripts;
{
MutexLock lock(script_instances_mutex);
for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
// Do not reload scripts with only non-collectible instances to avoid disrupting event subscriptions and such.
bool is_reloadable = elem->self()->instances.size() == 0;
for (Object *obj : elem->self()->instances) {
ERR_CONTINUE(!obj->get_script_instance());
CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
if (GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(csi->get_gchandle_intptr())) {
is_reloadable = true;
break;
}
}
if (is_reloadable) {
// Cast to CSharpScript to avoid being erased by accident.
scripts.push_back(Ref<CSharpScript>(elem->self()));
}
}
}
scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
// Serialize managed callables
{
MutexLock lock(ManagedCallable::instances_mutex);
for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
ManagedCallable *managed_callable = elem->self();
ERR_CONTINUE(managed_callable->delegate_handle.value == nullptr);
if (!GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(managed_callable->delegate_handle)) {
continue;
}
Array serialized_data;
bool success = GDMonoCache::managed_callbacks.DelegateUtils_TrySerializeDelegateWithGCHandle(
managed_callable->delegate_handle, &serialized_data);
if (success) {
ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
} else if (OS::get_singleton()->is_stdout_verbose()) {
OS::get_singleton()->print("Failed to serialize delegate\n");
}
}
}
List<Ref<CSharpScript>> to_reload;
// We need to keep reference instances alive during reloading
List<Ref<RefCounted>> rc_instances;
for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
const CSharpScriptBinding &script_binding = E.value;
RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner);
if (rc) {
rc_instances.push_back(Ref<RefCounted>(rc));
}
}
// As scripts are going to be reloaded, must proceed without locking here
for (Ref<CSharpScript> &scr : scripts) {
// If someone removes a script from a node, deletes the script, builds, adds a script to the
// same node, then builds again, the script might have no path and also no script_class. In
// that case, we can't (and don't need to) reload it.
if (scr->get_path().is_empty() && !scr->valid) {
continue;
}
to_reload.push_back(scr);
// Script::instances are deleted during managed object disposal, which happens on domain finalize.
// Only placeholders are kept. Therefore we need to keep a copy before that happens.
for (Object *obj : scr->instances) {
scr->pending_reload_instances.insert(obj->get_instance_id());
// Since this script instance wasn't a placeholder, add it to the list of placeholders
// that will have to be eventually replaced with a script instance in case it turns into one.
// This list is not cleared after the reload and the collected instances only leave
// the list if the script is instantiated or if it was a tool script but becomes a
// non-tool script in a rebuild.
scr->pending_replace_placeholders.insert(obj->get_instance_id());
RefCounted *rc = Object::cast_to<RefCounted>(obj);
if (rc) {
rc_instances.push_back(Ref<RefCounted>(rc));
}
}
#ifdef TOOLS_ENABLED
for (PlaceHolderScriptInstance *instance : scr->placeholders) {
Object *obj = instance->get_owner();
scr->pending_reload_instances.insert(obj->get_instance_id());
RefCounted *rc = Object::cast_to<RefCounted>(obj);
if (rc) {
rc_instances.push_back(Ref<RefCounted>(rc));
}
}
#endif
// Save state and remove script from instances
RBMap<ObjectID, CSharpScript::StateBackup> &owners_map = scr->pending_reload_state;
for (Object *obj : scr->instances) {
ERR_CONTINUE(!obj->get_script_instance());
CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
// Call OnBeforeSerialize and save instance info
CSharpScript::StateBackup state;
Dictionary properties;
GDMonoCache::managed_callbacks.CSharpInstanceBridge_SerializeState(
csi->get_gchandle_intptr(), &properties, &state.event_signals);
for (const Variant *s = properties.next(nullptr); s != nullptr; s = properties.next(s)) {
StringName name = *s;
Variant value = properties[*s];
state.properties.push_back(Pair<StringName, Variant>(name, value));
}
owners_map[obj->get_instance_id()] = state;
}
}
// After the state of all instances is saved, clear scripts and script instances
for (Ref<CSharpScript> &scr : scripts) {
while (scr->instances.begin()) {
Object *obj = *scr->instances.begin();
obj->set_script(Ref<RefCounted>()); // Remove script and existing script instances (placeholder are not removed before domain reload)
}
scr->was_tool_before_reload = scr->tool;
scr->_clear();
}
// Release the delegates that were serialized earlier.
{
MutexLock lock(ManagedCallable::instances_mutex);
for (KeyValue<ManagedCallable *, Array> &kv : ManagedCallable::instances_pending_reload) {
kv.key->release_delegate_handle();
}
}
// Do domain reload
if (gdmono->reload_project_assemblies() != OK) {
// Failed to reload the scripts domain
// Make sure to add the scripts back to their owners before returning
for (Ref<CSharpScript> &scr : to_reload) {
for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) {
Object *obj = ObjectDB::get_instance(F.key);
if (!obj) {
continue;
}
ObjectID obj_id = obj->get_instance_id();
// Use a placeholder for now to avoid losing the state when saving a scene
PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
obj->set_script_instance(placeholder);
#ifdef TOOLS_ENABLED
// Even though build didn't fail, this tells the placeholder to keep properties and
// it allows using property_set_fallback for restoring the state without a valid script.
scr->placeholder_fallback_enabled = true;
#endif
// Restore Variant properties state, it will be kept by the placeholder until the next script reloading
for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) {
placeholder->property_set_fallback(G.first, G.second, nullptr);
}
scr->pending_reload_state.erase(obj_id);
}
scr->pending_reload_instances.clear();
scr->pending_reload_state.clear();
}
return;
}
List<Ref<CSharpScript>> to_reload_state;
for (Ref<CSharpScript> &scr : to_reload) {
#ifdef TOOLS_ENABLED
scr->exports_invalidated = true;
#endif
if (!scr->get_path().is_empty()) {
scr->reload(p_soft_reload);
if (!scr->valid) {
scr->pending_reload_instances.clear();
scr->pending_reload_state.clear();
continue;
}
} else {
bool success = GDMonoCache::managed_callbacks.ScriptManagerBridge_TryReloadRegisteredScriptWithClass(scr.ptr());
if (!success) {
// Couldn't reload