Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/mono/csharp_script.h
11351 views
1
/**************************************************************************/
2
/* csharp_script.h */
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
#pragma once
32
33
#include "mono_gc_handle.h"
34
#include "mono_gd/gd_mono.h"
35
36
#include "core/doc_data.h"
37
#include "core/io/resource_loader.h"
38
#include "core/io/resource_saver.h"
39
#include "core/object/script_language.h"
40
#include "core/templates/rb_map.h"
41
#include "core/templates/self_list.h"
42
43
#ifdef TOOLS_ENABLED
44
#include "editor/plugins/editor_plugin.h"
45
#endif
46
47
class CSharpScript;
48
class CSharpInstance;
49
class CSharpLanguage;
50
51
template <typename TScriptInstance, typename TScriptLanguage>
52
TScriptInstance *cast_script_instance(ScriptInstance *p_inst) {
53
return dynamic_cast<TScriptInstance *>(p_inst);
54
}
55
56
#define CAST_CSHARP_INSTANCE(m_inst) (cast_script_instance<CSharpInstance, CSharpLanguage>(m_inst))
57
58
class CSharpScript : public Script {
59
GDCLASS(CSharpScript, Script);
60
61
friend class CSharpInstance;
62
friend class CSharpLanguage;
63
64
public:
65
struct TypeInfo {
66
/**
67
* Name of the C# class.
68
*/
69
String class_name;
70
71
/**
72
* Name of the native class this script derives from.
73
*/
74
StringName native_base_name;
75
76
/**
77
* Path to the icon that will be used for this class by the editor.
78
*/
79
String icon_path;
80
81
/**
82
* Script is marked as tool and runs in the editor.
83
*/
84
bool is_tool = false;
85
86
/**
87
* Script is marked as global class and will be registered in the editor.
88
* Registered classes can be created using certain editor dialogs and
89
* can be referenced by name from other languages that support the feature.
90
*/
91
bool is_global_class = false;
92
93
/**
94
* Script is declared abstract.
95
*/
96
bool is_abstract = false;
97
98
/**
99
* The C# type that corresponds to this script is a constructed generic type.
100
* E.g.: `Dictionary<int, string>`
101
*/
102
bool is_constructed_generic_type = false;
103
104
/**
105
* The C# type that corresponds to this script is a generic type definition.
106
* E.g.: `Dictionary<,>`
107
*/
108
bool is_generic_type_definition = false;
109
110
/**
111
* The C# type that corresponds to this script contains generic type parameters,
112
* regardless of whether the type parameters are bound or not.
113
*/
114
bool is_generic() const {
115
return is_constructed_generic_type || is_generic_type_definition;
116
}
117
118
/**
119
* Check if the script can be instantiated.
120
* C# types can't be instantiated if they are abstract or contain generic
121
* type parameters, but a CSharpScript is still created for them.
122
*/
123
bool can_instantiate() const {
124
return !is_abstract && !is_generic_type_definition;
125
}
126
};
127
128
private:
129
/**
130
* Contains the C# type information for this script.
131
*/
132
TypeInfo type_info;
133
134
/**
135
* Scripts are valid when the corresponding C# class is found and used
136
* to extract the script info using the [update_script_class_info] method.
137
*/
138
bool valid = false;
139
/**
140
* Scripts extract info from the C# class in the reload methods but,
141
* if the reload is not invalidated, then the current extracted info
142
* is still valid and there's no need to reload again.
143
*/
144
bool reload_invalidated = false;
145
146
/**
147
* Base script that this script derives from, or null if it derives from a
148
* native Godot class.
149
*/
150
Ref<CSharpScript> base_script;
151
152
HashSet<Object *> instances;
153
154
#ifdef GD_MONO_HOT_RELOAD
155
struct StateBackup {
156
// TODO
157
// Replace with buffer containing the serialized state of managed scripts.
158
// Keep variant state backup to use only with script instance placeholders.
159
List<Pair<StringName, Variant>> properties;
160
Dictionary event_signals;
161
};
162
163
HashSet<ObjectID> pending_reload_instances;
164
RBMap<ObjectID, StateBackup> pending_reload_state;
165
166
bool was_tool_before_reload = false;
167
HashSet<ObjectID> pending_replace_placeholders;
168
#endif
169
170
/**
171
* Script source code.
172
*/
173
String source;
174
175
SelfList<CSharpScript> script_list = this;
176
177
Dictionary rpc_config;
178
179
struct EventSignalInfo {
180
StringName name; // MethodInfo stores a string...
181
MethodInfo method_info;
182
};
183
184
struct CSharpMethodInfo {
185
StringName name; // MethodInfo stores a string...
186
MethodInfo method_info;
187
};
188
189
Vector<EventSignalInfo> event_signals;
190
Vector<CSharpMethodInfo> methods;
191
192
#ifdef TOOLS_ENABLED
193
List<PropertyInfo> exported_members_cache; // members_cache
194
HashMap<StringName, Variant> exported_members_defval_cache; // member_default_values_cache
195
HashSet<PlaceHolderScriptInstance *> placeholders;
196
bool source_changed_cache = false;
197
bool placeholder_fallback_enabled = false;
198
bool exports_invalidated = true;
199
void _update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames);
200
void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
201
#endif
202
203
#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
204
HashSet<StringName> exported_members_names;
205
#endif
206
207
HashMap<StringName, PropertyInfo> member_info;
208
209
void _clear();
210
211
static void GD_CLR_STDCALL _add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count);
212
#ifdef TOOLS_ENABLED
213
static void GD_CLR_STDCALL _add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count);
214
#endif
215
bool _update_exports(PlaceHolderScriptInstance *p_instance_to_update = nullptr);
216
217
CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error);
218
Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
219
220
// Do not use unless you know what you are doing
221
static void update_script_class_info(Ref<CSharpScript> p_script);
222
223
void _get_script_signal_list(List<MethodInfo> *r_signals, bool p_include_base) const;
224
225
protected:
226
static void _bind_methods();
227
228
bool _get(const StringName &p_name, Variant &r_ret) const;
229
bool _set(const StringName &p_name, const Variant &p_value);
230
void _get_property_list(List<PropertyInfo> *p_properties) const;
231
232
public:
233
static void reload_registered_script(Ref<CSharpScript> p_script);
234
235
bool can_instantiate() const override;
236
StringName get_instance_base_type() const override;
237
ScriptInstance *instance_create(Object *p_this) override;
238
PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override;
239
bool instance_has(const Object *p_this) const override;
240
241
bool has_source_code() const override;
242
String get_source_code() const override;
243
void set_source_code(const String &p_code) override;
244
245
#ifdef TOOLS_ENABLED
246
virtual StringName get_doc_class_name() const override { return StringName(); } // TODO
247
virtual Vector<DocData::ClassDoc> get_documentation() const override {
248
// TODO
249
Vector<DocData::ClassDoc> docs;
250
return docs;
251
}
252
virtual String get_class_icon_path() const override {
253
return type_info.icon_path;
254
}
255
#endif // TOOLS_ENABLED
256
257
Error reload(bool p_keep_state = false) override;
258
259
bool has_script_signal(const StringName &p_signal) const override;
260
void get_script_signal_list(List<MethodInfo> *r_signals) const override;
261
262
bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
263
void get_script_property_list(List<PropertyInfo> *r_list) const override;
264
void update_exports() override;
265
266
void get_members(HashSet<StringName> *p_members) override;
267
268
bool is_tool() const override {
269
return type_info.is_tool;
270
}
271
bool is_valid() const override {
272
return valid;
273
}
274
bool is_abstract() const override {
275
return type_info.is_abstract;
276
}
277
278
bool inherits_script(const Ref<Script> &p_script) const override;
279
280
Ref<Script> get_base_script() const override;
281
StringName get_global_name() const override;
282
283
ScriptLanguage *get_language() const override;
284
285
void get_script_method_list(List<MethodInfo> *p_list) const override;
286
bool has_method(const StringName &p_method) const override;
287
virtual int get_script_method_argument_count(const StringName &p_method, bool *r_is_valid = nullptr) const override;
288
MethodInfo get_method_info(const StringName &p_method) const override;
289
Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
290
291
int get_member_line(const StringName &p_member) const override;
292
293
const Variant get_rpc_config() const override;
294
295
#ifdef TOOLS_ENABLED
296
bool is_placeholder_fallback_enabled() const override {
297
return placeholder_fallback_enabled;
298
}
299
#endif
300
301
Error load_source_code(const String &p_path);
302
303
CSharpScript();
304
~CSharpScript();
305
};
306
307
class CSharpInstance : public ScriptInstance {
308
friend class CSharpScript;
309
friend class CSharpLanguage;
310
311
Object *owner = nullptr;
312
bool base_ref_counted = false;
313
bool ref_dying = false;
314
bool unsafe_referenced = false;
315
bool predelete_notified = false;
316
bool destructing_script_instance = false;
317
318
Ref<CSharpScript> script;
319
MonoGCHandleData gchandle;
320
321
List<Callable> connected_event_signals;
322
323
bool _reference_owner_unsafe();
324
325
/*
326
* If true is returned, the caller must memdelete the script instance's owner.
327
*/
328
bool _unreference_owner_unsafe();
329
330
/*
331
* If false is returned, the caller must destroy the script instance by removing it from its owner.
332
*/
333
bool _internal_new_managed();
334
335
// Do not use unless you know what you are doing
336
static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle);
337
338
public:
339
_FORCE_INLINE_ bool is_destructing_script_instance() { return destructing_script_instance; }
340
341
_FORCE_INLINE_ GCHandleIntPtr get_gchandle_intptr() { return gchandle.get_intptr(); }
342
343
Object *get_owner() override;
344
345
bool set(const StringName &p_name, const Variant &p_value) override;
346
bool get(const StringName &p_name, Variant &r_ret) const override;
347
void get_property_list(List<PropertyInfo> *p_properties) const override;
348
Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override;
349
virtual void validate_property(PropertyInfo &p_property) const override;
350
351
bool property_can_revert(const StringName &p_name) const override;
352
bool property_get_revert(const StringName &p_name, Variant &r_ret) const override;
353
354
void get_method_list(List<MethodInfo> *p_list) const override;
355
bool has_method(const StringName &p_method) const override;
356
virtual int get_method_argument_count(const StringName &p_method, bool *r_is_valid = nullptr) const override;
357
Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
358
359
void mono_object_disposed(GCHandleIntPtr p_gchandle_to_free);
360
361
/*
362
* If 'r_delete_owner' is set to true, the caller must memdelete the script instance's owner. Otherwise, if
363
* 'r_remove_script_instance' is set to true, the caller must destroy the script instance by removing it from its owner.
364
*/
365
void mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance);
366
367
void connect_event_signals();
368
void disconnect_event_signals();
369
370
void refcount_incremented() override;
371
bool refcount_decremented() override;
372
373
const Variant get_rpc_config() const override;
374
375
void notification(int p_notification, bool p_reversed = false) override;
376
void _call_notification(int p_notification, bool p_reversed = false);
377
378
String to_string(bool *r_valid) override;
379
380
Ref<Script> get_script() const override;
381
382
ScriptLanguage *get_language() override;
383
384
CSharpInstance(const Ref<CSharpScript> &p_script);
385
~CSharpInstance();
386
};
387
388
struct CSharpScriptBinding {
389
bool inited = false;
390
StringName type_name;
391
MonoGCHandleData gchandle;
392
Object *owner = nullptr;
393
394
CSharpScriptBinding() {}
395
};
396
397
class ManagedCallableMiddleman : public Object {
398
GDCLASS(ManagedCallableMiddleman, Object);
399
};
400
401
class CSharpLanguage : public ScriptLanguage {
402
friend class CSharpScript;
403
friend class CSharpInstance;
404
405
static CSharpLanguage *singleton;
406
407
bool finalizing = false;
408
bool finalized = false;
409
410
GDMono *gdmono = nullptr;
411
SelfList<CSharpScript>::List script_list;
412
413
Mutex script_instances_mutex;
414
Mutex script_gchandle_release_mutex;
415
Mutex language_bind_mutex;
416
417
RBMap<Object *, CSharpScriptBinding> script_bindings;
418
419
#ifdef DEBUG_ENABLED
420
// List of unsafe object references
421
HashMap<ObjectID, int> unsafe_object_references;
422
Mutex unsafe_object_references_lock;
423
#endif
424
425
ManagedCallableMiddleman *managed_callable_middleman = memnew(ManagedCallableMiddleman);
426
427
int lang_idx = -1;
428
429
// For debug_break and debug_break_parse
430
int _debug_parse_err_line = -1;
431
String _debug_parse_err_file;
432
String _debug_error;
433
434
friend class GDMono;
435
436
#ifdef TOOLS_ENABLED
437
EditorPlugin *godotsharp_editor = nullptr;
438
439
static void _editor_init_callback();
440
#endif
441
442
static void *_instance_binding_create_callback(void *p_token, void *p_instance);
443
static void _instance_binding_free_callback(void *p_token, void *p_instance, void *p_binding);
444
static GDExtensionBool _instance_binding_reference_callback(void *p_token, void *p_binding, GDExtensionBool p_reference);
445
446
static GDExtensionInstanceBindingCallbacks _instance_binding_callbacks;
447
448
public:
449
static void *get_instance_binding(Object *p_object);
450
static void *get_existing_instance_binding(Object *p_object);
451
static void *get_instance_binding_with_setup(Object *p_object);
452
static bool has_instance_binding(Object *p_object);
453
454
const Mutex &get_language_bind_mutex() {
455
return language_bind_mutex;
456
}
457
const Mutex &get_script_instances_mutex() {
458
return script_instances_mutex;
459
}
460
461
_FORCE_INLINE_ int get_language_index() {
462
return lang_idx;
463
}
464
void set_language_index(int p_idx);
465
466
_FORCE_INLINE_ static CSharpLanguage *get_singleton() {
467
return singleton;
468
}
469
470
#ifdef TOOLS_ENABLED
471
_FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const {
472
return godotsharp_editor;
473
}
474
#endif
475
476
static void release_script_gchandle(MonoGCHandleData &p_gchandle);
477
static void release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle);
478
static void release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding);
479
480
bool debug_break(const String &p_error, bool p_allow_continue = true);
481
bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
482
483
#ifdef GD_MONO_HOT_RELOAD
484
bool is_assembly_reloading_needed();
485
void reload_assemblies(bool p_soft_reload);
486
#endif
487
488
_FORCE_INLINE_ ManagedCallableMiddleman *get_managed_callable_middleman() const {
489
return managed_callable_middleman;
490
}
491
492
String get_name() const override;
493
494
/* LANGUAGE FUNCTIONS */
495
String get_type() const override;
496
String get_extension() const override;
497
void init() override;
498
void finish() override;
499
500
void finalize();
501
502
/* EDITOR FUNCTIONS */
503
Vector<String> get_reserved_words() const override;
504
bool is_control_flow_keyword(const String &p_keyword) const override;
505
Vector<String> get_comment_delimiters() const override;
506
Vector<String> get_doc_comment_delimiters() const override;
507
Vector<String> get_string_delimiters() const override;
508
bool is_using_templates() override;
509
virtual Ref<Script> make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const override;
510
virtual Vector<ScriptTemplate> get_built_in_templates(const StringName &p_object) override;
511
/* TODO */ bool validate(const String &p_script, const String &p_path, List<String> *r_functions,
512
List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, HashSet<int> *r_safe_lines = nullptr) const override {
513
return true;
514
}
515
String validate_path(const String &p_path) const override;
516
Script *create_script() const override;
517
#ifndef DISABLE_DEPRECATED
518
virtual bool has_named_classes() const override { return false; }
519
#endif
520
bool supports_builtin_mode() const override;
521
/* TODO? */ int find_function(const String &p_function, const String &p_code) const override {
522
return -1;
523
}
524
String make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const override;
525
virtual bool can_make_function() const override { return false; }
526
virtual String _get_indentation() const;
527
/* TODO? */ void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const override {}
528
/* TODO */ void add_global_constant(const StringName &p_variable, const Variant &p_value) override {}
529
virtual ScriptNameCasing preferred_file_name_casing() const override;
530
531
/* SCRIPT GLOBAL CLASS FUNCTIONS */
532
virtual bool handles_global_class_type(const String &p_type) const override;
533
virtual String get_global_class_name(const String &p_path, String *r_base_type = nullptr, String *r_icon_path = nullptr, bool *r_is_abstract = nullptr, bool *r_is_tool = nullptr) const override;
534
535
/* DEBUGGER FUNCTIONS */
536
String debug_get_error() const override;
537
int debug_get_stack_level_count() const override;
538
int debug_get_stack_level_line(int p_level) const override;
539
String debug_get_stack_level_function(int p_level) const override;
540
String debug_get_stack_level_source(int p_level) const override;
541
/* TODO */ void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
542
/* TODO */ void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
543
/* TODO */ void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
544
/* TODO */ String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) override {
545
return "";
546
}
547
Vector<StackInfo> debug_get_current_stack_info() override;
548
549
/* PROFILING FUNCTIONS */
550
/* TODO */ void profiling_start() override {}
551
/* TODO */ void profiling_stop() override {}
552
/* TODO */ void profiling_set_save_native_calls(bool p_enable) override {}
553
/* TODO */ int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override {
554
return 0;
555
}
556
/* TODO */ int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override {
557
return 0;
558
}
559
560
void frame() override;
561
562
/* TODO? */ void get_public_functions(List<MethodInfo> *p_functions) const override {}
563
/* TODO? */ void get_public_constants(List<Pair<String, Variant>> *p_constants) const override {}
564
/* TODO? */ void get_public_annotations(List<MethodInfo> *p_annotations) const override {}
565
566
void reload_all_scripts() override;
567
void reload_scripts(const Array &p_scripts, bool p_soft_reload) override;
568
void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) override;
569
570
/* LOADER FUNCTIONS */
571
void get_recognized_extensions(List<String> *p_extensions) const override;
572
573
#ifdef TOOLS_ENABLED
574
Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) override;
575
bool overrides_external_editor() override;
576
#endif
577
578
RBMap<Object *, CSharpScriptBinding>::Element *insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding);
579
bool setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object);
580
581
static void tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted);
582
static void tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted);
583
static void tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged);
584
585
void post_unsafe_reference(Object *p_obj);
586
void pre_unsafe_unreference(Object *p_obj);
587
588
CSharpLanguage();
589
~CSharpLanguage();
590
};
591
592
class ResourceFormatLoaderCSharpScript : public ResourceFormatLoader {
593
GDSOFTCLASS(ResourceFormatLoaderCSharpScript, ResourceFormatLoader);
594
595
public:
596
Ref<Resource> load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE) override;
597
void get_recognized_extensions(List<String> *p_extensions) const override;
598
bool handles_type(const String &p_type) const override;
599
String get_resource_type(const String &p_path) const override;
600
};
601
602
class ResourceFormatSaverCSharpScript : public ResourceFormatSaver {
603
GDSOFTCLASS(ResourceFormatSaverCSharpScript, ResourceFormatSaver);
604
605
public:
606
Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0) override;
607
void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const override;
608
bool recognize(const Ref<Resource> &p_resource) const override;
609
};
610
611