csharp_script.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. #ifndef CSHARP_SCRIPT_H
  31. #define CSHARP_SCRIPT_H
  32. #include "mono_gc_handle.h"
  33. #include "mono_gd/gd_mono.h"
  34. #include "core/doc_data.h"
  35. #include "core/io/resource_loader.h"
  36. #include "core/io/resource_saver.h"
  37. #include "core/object/script_language.h"
  38. #include "core/templates/self_list.h"
  39. #ifdef TOOLS_ENABLED
  40. #include "editor/editor_plugin.h"
  41. #endif
  42. class CSharpScript;
  43. class CSharpInstance;
  44. class CSharpLanguage;
  45. template <typename TScriptInstance, typename TScriptLanguage>
  46. TScriptInstance *cast_script_instance(ScriptInstance *p_inst) {
  47. return dynamic_cast<TScriptInstance *>(p_inst);
  48. }
  49. #define CAST_CSHARP_INSTANCE(m_inst) (cast_script_instance<CSharpInstance, CSharpLanguage>(m_inst))
  50. class CSharpScript : public Script {
  51. GDCLASS(CSharpScript, Script);
  52. friend class CSharpInstance;
  53. friend class CSharpLanguage;
  54. bool tool = false;
  55. bool global_class = false;
  56. bool abstract_class = false;
  57. bool valid = false;
  58. bool reload_invalidated = false;
  59. Ref<CSharpScript> base_script;
  60. HashSet<Object *> instances;
  61. #ifdef GD_MONO_HOT_RELOAD
  62. struct StateBackup {
  63. // TODO
  64. // Replace with buffer containing the serialized state of managed scripts.
  65. // Keep variant state backup to use only with script instance placeholders.
  66. List<Pair<StringName, Variant>> properties;
  67. Dictionary event_signals;
  68. };
  69. HashSet<ObjectID> pending_reload_instances;
  70. RBMap<ObjectID, StateBackup> pending_reload_state;
  71. bool was_tool_before_reload = false;
  72. HashSet<ObjectID> pending_replace_placeholders;
  73. #endif
  74. String source;
  75. String class_name;
  76. String icon_path;
  77. SelfList<CSharpScript> script_list = this;
  78. Dictionary rpc_config;
  79. struct EventSignalInfo {
  80. StringName name; // MethodInfo stores a string...
  81. MethodInfo method_info;
  82. };
  83. struct CSharpMethodInfo {
  84. StringName name; // MethodInfo stores a string...
  85. MethodInfo method_info;
  86. };
  87. Vector<EventSignalInfo> event_signals;
  88. Vector<CSharpMethodInfo> methods;
  89. #ifdef TOOLS_ENABLED
  90. List<PropertyInfo> exported_members_cache; // members_cache
  91. HashMap<StringName, Variant> exported_members_defval_cache; // member_default_values_cache
  92. HashSet<PlaceHolderScriptInstance *> placeholders;
  93. bool source_changed_cache = false;
  94. bool placeholder_fallback_enabled = false;
  95. bool exports_invalidated = true;
  96. void _update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames);
  97. void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
  98. #endif
  99. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  100. HashSet<StringName> exported_members_names;
  101. #endif
  102. HashMap<StringName, PropertyInfo> member_info;
  103. void _clear();
  104. 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);
  105. #ifdef TOOLS_ENABLED
  106. static void GD_CLR_STDCALL _add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count);
  107. #endif
  108. bool _update_exports(PlaceHolderScriptInstance *p_instance_to_update = nullptr);
  109. CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error);
  110. Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
  111. // Do not use unless you know what you are doing
  112. static void update_script_class_info(Ref<CSharpScript> p_script);
  113. protected:
  114. static void _bind_methods();
  115. bool _get(const StringName &p_name, Variant &r_ret) const;
  116. bool _set(const StringName &p_name, const Variant &p_value);
  117. void _get_property_list(List<PropertyInfo> *p_properties) const;
  118. public:
  119. static void reload_registered_script(Ref<CSharpScript> p_script);
  120. bool can_instantiate() const override;
  121. StringName get_instance_base_type() const override;
  122. ScriptInstance *instance_create(Object *p_this) override;
  123. PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override;
  124. bool instance_has(const Object *p_this) const override;
  125. bool has_source_code() const override;
  126. String get_source_code() const override;
  127. void set_source_code(const String &p_code) override;
  128. #ifdef TOOLS_ENABLED
  129. virtual Vector<DocData::ClassDoc> get_documentation() const override {
  130. // TODO
  131. Vector<DocData::ClassDoc> docs;
  132. return docs;
  133. }
  134. virtual String get_class_icon_path() const override {
  135. return icon_path;
  136. }
  137. #endif // TOOLS_ENABLED
  138. Error reload(bool p_keep_state = false) override;
  139. bool has_script_signal(const StringName &p_signal) const override;
  140. void get_script_signal_list(List<MethodInfo> *r_signals) const override;
  141. Vector<EventSignalInfo> get_script_event_signals() const;
  142. bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
  143. void get_script_property_list(List<PropertyInfo> *r_list) const override;
  144. void update_exports() override;
  145. void get_members(HashSet<StringName> *p_members) override;
  146. bool is_tool() const override {
  147. return tool;
  148. }
  149. bool is_valid() const override {
  150. return valid;
  151. }
  152. bool is_abstract() const override {
  153. return abstract_class;
  154. }
  155. bool inherits_script(const Ref<Script> &p_script) const override;
  156. Ref<Script> get_base_script() const override;
  157. StringName get_global_name() const override;
  158. ScriptLanguage *get_language() const override;
  159. void get_script_method_list(List<MethodInfo> *p_list) const override;
  160. bool has_method(const StringName &p_method) const override;
  161. MethodInfo get_method_info(const StringName &p_method) const override;
  162. Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
  163. int get_member_line(const StringName &p_member) const override;
  164. const Variant get_rpc_config() const override;
  165. #ifdef TOOLS_ENABLED
  166. bool is_placeholder_fallback_enabled() const override {
  167. return placeholder_fallback_enabled;
  168. }
  169. #endif
  170. Error load_source_code(const String &p_path);
  171. CSharpScript();
  172. ~CSharpScript();
  173. };
  174. class CSharpInstance : public ScriptInstance {
  175. friend class CSharpScript;
  176. friend class CSharpLanguage;
  177. Object *owner = nullptr;
  178. bool base_ref_counted = false;
  179. bool ref_dying = false;
  180. bool unsafe_referenced = false;
  181. bool predelete_notified = false;
  182. bool destructing_script_instance = false;
  183. Ref<CSharpScript> script;
  184. MonoGCHandleData gchandle;
  185. List<Callable> connected_event_signals;
  186. bool _reference_owner_unsafe();
  187. /*
  188. * If true is returned, the caller must memdelete the script instance's owner.
  189. */
  190. bool _unreference_owner_unsafe();
  191. /*
  192. * If false is returned, the caller must destroy the script instance by removing it from its owner.
  193. */
  194. bool _internal_new_managed();
  195. // Do not use unless you know what you are doing
  196. static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle);
  197. public:
  198. _FORCE_INLINE_ bool is_destructing_script_instance() { return destructing_script_instance; }
  199. _FORCE_INLINE_ GCHandleIntPtr get_gchandle_intptr() { return gchandle.get_intptr(); }
  200. Object *get_owner() override;
  201. bool set(const StringName &p_name, const Variant &p_value) override;
  202. bool get(const StringName &p_name, Variant &r_ret) const override;
  203. void get_property_list(List<PropertyInfo> *p_properties) const override;
  204. Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override;
  205. virtual void validate_property(PropertyInfo &p_property) const override;
  206. bool property_can_revert(const StringName &p_name) const override;
  207. bool property_get_revert(const StringName &p_name, Variant &r_ret) const override;
  208. void get_method_list(List<MethodInfo> *p_list) const override;
  209. bool has_method(const StringName &p_method) const override;
  210. Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
  211. void mono_object_disposed(GCHandleIntPtr p_gchandle_to_free);
  212. /*
  213. * If 'r_delete_owner' is set to true, the caller must memdelete the script instance's owner. Otherwise, if
  214. * 'r_remove_script_instance' is set to true, the caller must destroy the script instance by removing it from its owner.
  215. */
  216. void mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance);
  217. void connect_event_signals();
  218. void disconnect_event_signals();
  219. void refcount_incremented() override;
  220. bool refcount_decremented() override;
  221. const Variant get_rpc_config() const override;
  222. void notification(int p_notification, bool p_reversed = false) override;
  223. void _call_notification(int p_notification, bool p_reversed = false);
  224. String to_string(bool *r_valid) override;
  225. Ref<Script> get_script() const override;
  226. ScriptLanguage *get_language() override;
  227. CSharpInstance(const Ref<CSharpScript> &p_script);
  228. ~CSharpInstance();
  229. };
  230. struct CSharpScriptBinding {
  231. bool inited = false;
  232. StringName type_name;
  233. MonoGCHandleData gchandle;
  234. Object *owner = nullptr;
  235. CSharpScriptBinding() {}
  236. };
  237. class ManagedCallableMiddleman : public Object {
  238. GDCLASS(ManagedCallableMiddleman, Object);
  239. };
  240. class CSharpLanguage : public ScriptLanguage {
  241. friend class CSharpScript;
  242. friend class CSharpInstance;
  243. static CSharpLanguage *singleton;
  244. bool finalizing = false;
  245. bool finalized = false;
  246. GDMono *gdmono = nullptr;
  247. SelfList<CSharpScript>::List script_list;
  248. Mutex script_instances_mutex;
  249. Mutex script_gchandle_release_mutex;
  250. Mutex language_bind_mutex;
  251. RBMap<Object *, CSharpScriptBinding> script_bindings;
  252. #ifdef DEBUG_ENABLED
  253. // List of unsafe object references
  254. HashMap<ObjectID, int> unsafe_object_references;
  255. Mutex unsafe_object_references_lock;
  256. #endif
  257. ManagedCallableMiddleman *managed_callable_middleman = memnew(ManagedCallableMiddleman);
  258. int lang_idx = -1;
  259. // For debug_break and debug_break_parse
  260. int _debug_parse_err_line = -1;
  261. String _debug_parse_err_file;
  262. String _debug_error;
  263. friend class GDMono;
  264. #ifdef TOOLS_ENABLED
  265. EditorPlugin *godotsharp_editor = nullptr;
  266. static void _editor_init_callback();
  267. #endif
  268. static void *_instance_binding_create_callback(void *p_token, void *p_instance);
  269. static void _instance_binding_free_callback(void *p_token, void *p_instance, void *p_binding);
  270. static GDExtensionBool _instance_binding_reference_callback(void *p_token, void *p_binding, GDExtensionBool p_reference);
  271. static GDExtensionInstanceBindingCallbacks _instance_binding_callbacks;
  272. public:
  273. static void *get_instance_binding(Object *p_object);
  274. static void *get_existing_instance_binding(Object *p_object);
  275. static void *get_instance_binding_with_setup(Object *p_object);
  276. static bool has_instance_binding(Object *p_object);
  277. const Mutex &get_language_bind_mutex() {
  278. return language_bind_mutex;
  279. }
  280. const Mutex &get_script_instances_mutex() {
  281. return script_instances_mutex;
  282. }
  283. _FORCE_INLINE_ int get_language_index() {
  284. return lang_idx;
  285. }
  286. void set_language_index(int p_idx);
  287. _FORCE_INLINE_ static CSharpLanguage *get_singleton() {
  288. return singleton;
  289. }
  290. #ifdef TOOLS_ENABLED
  291. _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const {
  292. return godotsharp_editor;
  293. }
  294. #endif
  295. static void release_script_gchandle(MonoGCHandleData &p_gchandle);
  296. static void release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle);
  297. static void release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding);
  298. bool debug_break(const String &p_error, bool p_allow_continue = true);
  299. bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
  300. #ifdef GD_MONO_HOT_RELOAD
  301. bool is_assembly_reloading_needed();
  302. void reload_assemblies(bool p_soft_reload);
  303. #endif
  304. _FORCE_INLINE_ ManagedCallableMiddleman *get_managed_callable_middleman() const {
  305. return managed_callable_middleman;
  306. }
  307. String get_name() const override;
  308. /* LANGUAGE FUNCTIONS */
  309. String get_type() const override;
  310. String get_extension() const override;
  311. void init() override;
  312. void finish() override;
  313. void finalize();
  314. /* EDITOR FUNCTIONS */
  315. void get_reserved_words(List<String> *p_words) const override;
  316. bool is_control_flow_keyword(String p_keyword) const override;
  317. void get_comment_delimiters(List<String> *p_delimiters) const override;
  318. void get_doc_comment_delimiters(List<String> *p_delimiters) const override;
  319. void get_string_delimiters(List<String> *p_delimiters) const override;
  320. bool is_using_templates() override;
  321. virtual Ref<Script> make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const override;
  322. virtual Vector<ScriptTemplate> get_built_in_templates(StringName p_object) override;
  323. /* TODO */ bool validate(const String &p_script, const String &p_path, List<String> *r_functions,
  324. List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, HashSet<int> *r_safe_lines = nullptr) const override {
  325. return true;
  326. }
  327. String validate_path(const String &p_path) const override;
  328. Script *create_script() const override;
  329. #ifndef DISABLE_DEPRECATED
  330. virtual bool has_named_classes() const override { return false; }
  331. #endif
  332. bool supports_builtin_mode() const override;
  333. /* TODO? */ int find_function(const String &p_function, const String &p_code) const override {
  334. return -1;
  335. }
  336. String make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const override;
  337. virtual String _get_indentation() const;
  338. /* TODO? */ void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const override {}
  339. /* TODO */ void add_global_constant(const StringName &p_variable, const Variant &p_value) override {}
  340. /* SCRIPT GLOBAL CLASS FUNCTIONS */
  341. virtual bool handles_global_class_type(const String &p_type) const override;
  342. virtual String get_global_class_name(const String &p_path, String *r_base_type = nullptr, String *r_icon_path = nullptr) const override;
  343. /* DEBUGGER FUNCTIONS */
  344. String debug_get_error() const override;
  345. int debug_get_stack_level_count() const override;
  346. int debug_get_stack_level_line(int p_level) const override;
  347. String debug_get_stack_level_function(int p_level) const override;
  348. String debug_get_stack_level_source(int p_level) const override;
  349. /* 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 {}
  350. /* 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 {}
  351. /* TODO */ void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
  352. /* TODO */ String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) override {
  353. return "";
  354. }
  355. Vector<StackInfo> debug_get_current_stack_info() override;
  356. /* PROFILING FUNCTIONS */
  357. /* TODO */ void profiling_start() override {}
  358. /* TODO */ void profiling_stop() override {}
  359. /* TODO */ int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override {
  360. return 0;
  361. }
  362. /* TODO */ int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override {
  363. return 0;
  364. }
  365. void frame() override;
  366. /* TODO? */ void get_public_functions(List<MethodInfo> *p_functions) const override {}
  367. /* TODO? */ void get_public_constants(List<Pair<String, Variant>> *p_constants) const override {}
  368. /* TODO? */ void get_public_annotations(List<MethodInfo> *p_annotations) const override {}
  369. void reload_all_scripts() override;
  370. void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) override;
  371. /* LOADER FUNCTIONS */
  372. void get_recognized_extensions(List<String> *p_extensions) const override;
  373. #ifdef TOOLS_ENABLED
  374. Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) override;
  375. bool overrides_external_editor() override;
  376. #endif
  377. RBMap<Object *, CSharpScriptBinding>::Element *insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding);
  378. bool setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object);
  379. static void tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted);
  380. static void tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted);
  381. static void tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged);
  382. void post_unsafe_reference(Object *p_obj);
  383. void pre_unsafe_unreference(Object *p_obj);
  384. CSharpLanguage();
  385. ~CSharpLanguage();
  386. };
  387. class ResourceFormatLoaderCSharpScript : public ResourceFormatLoader {
  388. public:
  389. 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;
  390. void get_recognized_extensions(List<String> *p_extensions) const override;
  391. bool handles_type(const String &p_type) const override;
  392. String get_resource_type(const String &p_path) const override;
  393. };
  394. class ResourceFormatSaverCSharpScript : public ResourceFormatSaver {
  395. public:
  396. Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0) override;
  397. void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const override;
  398. bool recognize(const Ref<Resource> &p_resource) const override;
  399. };
  400. #endif // CSHARP_SCRIPT_H