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