csharp_script.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "csharp_script.h"
  31. #include <stdint.h>
  32. #include "core/config/project_settings.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/debugger/script_debugger.h"
  35. #include "core/io/file_access.h"
  36. #include "core/os/mutex.h"
  37. #include "core/os/os.h"
  38. #include "core/os/thread.h"
  39. #ifdef TOOLS_ENABLED
  40. #include "core/os/keyboard.h"
  41. #include "editor/bindings_generator.h"
  42. #include "editor/editor_internal_calls.h"
  43. #include "editor/editor_node.h"
  44. #include "editor/editor_settings.h"
  45. #include "editor/node_dock.h"
  46. #include "editor/script_templates/templates.gen.h"
  47. #endif
  48. #ifdef DEBUG_METHODS_ENABLED
  49. #include "class_db_api_json.h"
  50. #endif
  51. #include "godotsharp_dirs.h"
  52. #include "managed_callable.h"
  53. #include "mono_gd/gd_mono_cache.h"
  54. #include "signal_awaiter_utils.h"
  55. #include "utils/macros.h"
  56. #include "utils/string_utils.h"
  57. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  58. #ifdef TOOLS_ENABLED
  59. static bool _create_project_solution_if_needed() {
  60. String sln_path = GodotSharpDirs::get_project_sln_path();
  61. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  62. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  63. // A solution does not yet exist, create a new one
  64. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
  65. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
  66. }
  67. return true;
  68. }
  69. #endif
  70. CSharpLanguage *CSharpLanguage::singleton = nullptr;
  71. GDNativeInstanceBindingCallbacks CSharpLanguage::_instance_binding_callbacks = {
  72. &_instance_binding_create_callback,
  73. &_instance_binding_free_callback,
  74. &_instance_binding_reference_callback
  75. };
  76. String CSharpLanguage::get_name() const {
  77. return "C#";
  78. }
  79. String CSharpLanguage::get_type() const {
  80. return "CSharpScript";
  81. }
  82. String CSharpLanguage::get_extension() const {
  83. return "cs";
  84. }
  85. Error CSharpLanguage::execute_file(const String &p_path) {
  86. // ??
  87. return OK;
  88. }
  89. extern void *godotsharp_pinvoke_funcs[185];
  90. [[maybe_unused]] volatile void **do_not_strip_godotsharp_pinvoke_funcs;
  91. #ifdef TOOLS_ENABLED
  92. extern void *godotsharp_editor_pinvoke_funcs[30];
  93. [[maybe_unused]] volatile void **do_not_strip_godotsharp_editor_pinvoke_funcs;
  94. #endif
  95. void CSharpLanguage::init() {
  96. #ifdef DEBUG_METHODS_ENABLED
  97. if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
  98. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  99. #ifdef TOOLS_ENABLED
  100. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  101. #endif
  102. }
  103. #endif
  104. // Hopefully this will be enough for all compilers. Otherwise we could use the printf on fake getenv trick.
  105. do_not_strip_godotsharp_pinvoke_funcs = (volatile void **)godotsharp_pinvoke_funcs;
  106. #ifdef TOOLS_ENABLED
  107. do_not_strip_godotsharp_editor_pinvoke_funcs = (volatile void **)godotsharp_editor_pinvoke_funcs;
  108. #endif
  109. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  110. // Generate the bindings here, before loading assemblies. The Godot assemblies
  111. // may be missing if the glue wasn't generated yet in order to build them.
  112. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  113. BindingsGenerator::handle_cmdline_args(cmdline_args);
  114. #endif
  115. gdmono = memnew(GDMono);
  116. gdmono->initialize();
  117. #ifdef TOOLS_ENABLED
  118. if (gdmono->is_runtime_initialized()) {
  119. gdmono->initialize_load_assemblies();
  120. }
  121. EditorNode::add_init_callback(&_editor_init_callback);
  122. #endif
  123. }
  124. void CSharpLanguage::finish() {
  125. finalize();
  126. }
  127. void CSharpLanguage::finalize() {
  128. if (finalized) {
  129. return;
  130. }
  131. finalizing = true;
  132. // Make sure all script binding gchandles are released before finalizing GDMono
  133. for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  134. CSharpScriptBinding &script_binding = E.value;
  135. if (!script_binding.gchandle.is_released()) {
  136. script_binding.gchandle.release();
  137. script_binding.inited = false;
  138. }
  139. }
  140. if (gdmono) {
  141. memdelete(gdmono);
  142. gdmono = nullptr;
  143. }
  144. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  145. script_bindings.clear();
  146. #ifdef DEBUG_ENABLED
  147. for (const KeyValue<ObjectID, int> &E : unsafe_object_references) {
  148. const ObjectID &id = E.key;
  149. Object *obj = ObjectDB::get_instance(id);
  150. if (obj) {
  151. ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
  152. } else {
  153. ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
  154. }
  155. }
  156. #endif
  157. memdelete(managed_callable_middleman);
  158. finalizing = false;
  159. finalized = true;
  160. }
  161. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  162. static const char *_reserved_words[] = {
  163. // Reserved keywords
  164. "abstract",
  165. "as",
  166. "base",
  167. "bool",
  168. "break",
  169. "byte",
  170. "case",
  171. "catch",
  172. "char",
  173. "checked",
  174. "class",
  175. "const",
  176. "continue",
  177. "decimal",
  178. "default",
  179. "delegate",
  180. "do",
  181. "double",
  182. "else",
  183. "enum",
  184. "event",
  185. "explicit",
  186. "extern",
  187. "false",
  188. "finally",
  189. "fixed",
  190. "float",
  191. "for",
  192. "foreach",
  193. "goto",
  194. "if",
  195. "implicit",
  196. "in",
  197. "int",
  198. "interface",
  199. "internal",
  200. "is",
  201. "lock",
  202. "long",
  203. "namespace",
  204. "new",
  205. "null",
  206. "object",
  207. "operator",
  208. "out",
  209. "override",
  210. "params",
  211. "private",
  212. "protected",
  213. "public",
  214. "readonly",
  215. "ref",
  216. "return",
  217. "sbyte",
  218. "sealed",
  219. "short",
  220. "sizeof",
  221. "stackalloc",
  222. "static",
  223. "string",
  224. "struct",
  225. "switch",
  226. "this",
  227. "throw",
  228. "true",
  229. "try",
  230. "typeof",
  231. "uint",
  232. "ulong",
  233. "unchecked",
  234. "unsafe",
  235. "ushort",
  236. "using",
  237. "virtual",
  238. "void",
  239. "volatile",
  240. "while",
  241. // Contextual keywords. Not reserved words, but I guess we should include
  242. // them because this seems to be used only for syntax highlighting.
  243. "add",
  244. "alias",
  245. "ascending",
  246. "async",
  247. "await",
  248. "by",
  249. "descending",
  250. "dynamic",
  251. "equals",
  252. "from",
  253. "get",
  254. "global",
  255. "group",
  256. "into",
  257. "join",
  258. "let",
  259. "nameof",
  260. "on",
  261. "orderby",
  262. "partial",
  263. "remove",
  264. "select",
  265. "set",
  266. "value",
  267. "var",
  268. "when",
  269. "where",
  270. "yield",
  271. nullptr
  272. };
  273. const char **w = _reserved_words;
  274. while (*w) {
  275. p_words->push_back(*w);
  276. w++;
  277. }
  278. }
  279. bool CSharpLanguage::is_control_flow_keyword(String p_keyword) const {
  280. return p_keyword == "break" ||
  281. p_keyword == "case" ||
  282. p_keyword == "catch" ||
  283. p_keyword == "continue" ||
  284. p_keyword == "default" ||
  285. p_keyword == "do" ||
  286. p_keyword == "else" ||
  287. p_keyword == "finally" ||
  288. p_keyword == "for" ||
  289. p_keyword == "foreach" ||
  290. p_keyword == "goto" ||
  291. p_keyword == "if" ||
  292. p_keyword == "return" ||
  293. p_keyword == "switch" ||
  294. p_keyword == "throw" ||
  295. p_keyword == "try" ||
  296. p_keyword == "while";
  297. }
  298. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  299. p_delimiters->push_back("//"); // single-line comment
  300. p_delimiters->push_back("/* */"); // delimited comment
  301. }
  302. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  303. p_delimiters->push_back("' '"); // character literal
  304. p_delimiters->push_back("\" \""); // regular string literal
  305. p_delimiters->push_back("@\" \""); // verbatim string literal
  306. // Generic string highlighting suffices as a workaround for now.
  307. }
  308. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  309. String base_class = p_base_class_name;
  310. if (p_class_name == base_class) {
  311. base_class = "Godot." + base_class;
  312. }
  313. return base_class;
  314. }
  315. bool CSharpLanguage::is_using_templates() {
  316. return true;
  317. }
  318. Ref<Script> CSharpLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
  319. Ref<CSharpScript> script;
  320. script.instantiate();
  321. String class_name_no_spaces = p_class_name.replace(" ", "_");
  322. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  323. String processed_template = p_template;
  324. processed_template = processed_template.replace("_BINDINGS_NAMESPACE_", BINDINGS_NAMESPACE)
  325. .replace("_BASE_", base_class_name)
  326. .replace("_CLASS_", class_name_no_spaces)
  327. .replace("_TS_", _get_indentation());
  328. script->set_source_code(processed_template);
  329. return script;
  330. }
  331. Vector<ScriptLanguage::ScriptTemplate> CSharpLanguage::get_built_in_templates(StringName p_object) {
  332. Vector<ScriptLanguage::ScriptTemplate> templates;
  333. #ifdef TOOLS_ENABLED
  334. for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
  335. if (TEMPLATES[i].inherit == p_object) {
  336. templates.append(TEMPLATES[i]);
  337. }
  338. }
  339. #endif
  340. return templates;
  341. }
  342. String CSharpLanguage::validate_path(const String &p_path) const {
  343. String class_name = p_path.get_file().get_basename();
  344. List<String> keywords;
  345. get_reserved_words(&keywords);
  346. if (keywords.find(class_name)) {
  347. return RTR("Class name can't be a reserved keyword");
  348. }
  349. return "";
  350. }
  351. Script *CSharpLanguage::create_script() const {
  352. return memnew(CSharpScript);
  353. }
  354. bool CSharpLanguage::has_named_classes() const {
  355. return false;
  356. }
  357. bool CSharpLanguage::supports_builtin_mode() const {
  358. return false;
  359. }
  360. #ifdef TOOLS_ENABLED
  361. static String variant_type_to_managed_name(const String &p_var_type_name) {
  362. if (p_var_type_name.is_empty()) {
  363. return "object";
  364. }
  365. if (!ClassDB::class_exists(p_var_type_name)) {
  366. return p_var_type_name;
  367. }
  368. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT)) {
  369. return "Godot.Object";
  370. }
  371. if (p_var_type_name == Variant::get_type_name(Variant::FLOAT)) {
  372. #ifdef REAL_T_IS_DOUBLE
  373. return "double";
  374. #else
  375. return "float";
  376. #endif
  377. }
  378. if (p_var_type_name == Variant::get_type_name(Variant::STRING)) {
  379. return "string"; // I prefer this one >:[
  380. }
  381. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY)) {
  382. return "Collections.Dictionary";
  383. }
  384. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY)) {
  385. return "Collections.Array";
  386. }
  387. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY)) {
  388. return "byte[]";
  389. }
  390. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY)) {
  391. return "int[]";
  392. }
  393. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY)) {
  394. return "long[]";
  395. }
  396. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY)) {
  397. return "float[]";
  398. }
  399. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY)) {
  400. return "double[]";
  401. }
  402. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY)) {
  403. return "string[]";
  404. }
  405. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY)) {
  406. return "Vector2[]";
  407. }
  408. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY)) {
  409. return "Vector3[]";
  410. }
  411. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY)) {
  412. return "Color[]";
  413. }
  414. if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL)) {
  415. return "SignalInfo";
  416. }
  417. Variant::Type var_types[] = {
  418. Variant::BOOL,
  419. Variant::INT,
  420. Variant::VECTOR2,
  421. Variant::VECTOR2I,
  422. Variant::RECT2,
  423. Variant::RECT2I,
  424. Variant::VECTOR3,
  425. Variant::VECTOR3I,
  426. Variant::TRANSFORM2D,
  427. Variant::VECTOR4,
  428. Variant::VECTOR4I,
  429. Variant::PLANE,
  430. Variant::QUATERNION,
  431. Variant::AABB,
  432. Variant::BASIS,
  433. Variant::TRANSFORM3D,
  434. Variant::PROJECTION,
  435. Variant::COLOR,
  436. Variant::STRING_NAME,
  437. Variant::NODE_PATH,
  438. Variant::RID,
  439. Variant::CALLABLE
  440. };
  441. for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  442. if (p_var_type_name == Variant::get_type_name(var_types[i])) {
  443. return p_var_type_name;
  444. }
  445. }
  446. return "object";
  447. }
  448. String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
  449. // FIXME
  450. // - Due to Godot's API limitation this just appends the function to the end of the file
  451. // - Use fully qualified name if there is ambiguity
  452. String s = "private void " + p_name + "(";
  453. for (int i = 0; i < p_args.size(); i++) {
  454. const String &arg = p_args[i];
  455. if (i > 0) {
  456. s += ", ";
  457. }
  458. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  459. }
  460. s += ")\n{\n // Replace with function body.\n}\n";
  461. return s;
  462. }
  463. #else
  464. String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
  465. return String();
  466. }
  467. #endif
  468. String CSharpLanguage::_get_indentation() const {
  469. #ifdef TOOLS_ENABLED
  470. if (Engine::get_singleton()->is_editor_hint()) {
  471. bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
  472. if (use_space_indentation) {
  473. int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
  474. String space_indent = "";
  475. for (int i = 0; i < indent_size; i++) {
  476. space_indent += " ";
  477. }
  478. return space_indent;
  479. }
  480. }
  481. #endif
  482. return "\t";
  483. }
  484. String CSharpLanguage::debug_get_error() const {
  485. return _debug_error;
  486. }
  487. int CSharpLanguage::debug_get_stack_level_count() const {
  488. if (_debug_parse_err_line >= 0) {
  489. return 1;
  490. }
  491. // TODO: StackTrace
  492. return 1;
  493. }
  494. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  495. if (_debug_parse_err_line >= 0) {
  496. return _debug_parse_err_line;
  497. }
  498. // TODO: StackTrace
  499. return 1;
  500. }
  501. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  502. if (_debug_parse_err_line >= 0) {
  503. return String();
  504. }
  505. // TODO: StackTrace
  506. return String();
  507. }
  508. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  509. if (_debug_parse_err_line >= 0) {
  510. return _debug_parse_err_file;
  511. }
  512. // TODO: StackTrace
  513. return String();
  514. }
  515. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  516. #ifdef DEBUG_ENABLED
  517. // Printing an error here will result in endless recursion, so we must be careful
  518. static thread_local bool _recursion_flag_ = false;
  519. if (_recursion_flag_) {
  520. return Vector<StackInfo>();
  521. }
  522. _recursion_flag_ = true;
  523. SCOPE_EXIT {
  524. _recursion_flag_ = false;
  525. };
  526. if (!gdmono->is_runtime_initialized()) {
  527. return Vector<StackInfo>();
  528. }
  529. Vector<StackInfo> si;
  530. if (GDMonoCache::godot_api_cache_updated) {
  531. GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
  532. }
  533. return si;
  534. #else
  535. return Vector<StackInfo>();
  536. #endif
  537. }
  538. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  539. #ifdef DEBUG_ENABLED
  540. MutexLock lock(unsafe_object_references_lock);
  541. ObjectID id = p_obj->get_instance_id();
  542. unsafe_object_references[id]++;
  543. #endif
  544. }
  545. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  546. #ifdef DEBUG_ENABLED
  547. MutexLock lock(unsafe_object_references_lock);
  548. ObjectID id = p_obj->get_instance_id();
  549. HashMap<ObjectID, int>::Iterator elem = unsafe_object_references.find(id);
  550. ERR_FAIL_NULL(elem);
  551. if (--elem->value == 0) {
  552. unsafe_object_references.remove(elem);
  553. }
  554. #endif
  555. }
  556. void CSharpLanguage::frame() {
  557. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  558. GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
  559. }
  560. }
  561. void CSharpLanguage::reload_all_scripts() {
  562. #ifdef GD_MONO_HOT_RELOAD
  563. if (is_assembly_reloading_needed()) {
  564. reload_assemblies(false);
  565. }
  566. #endif
  567. }
  568. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  569. (void)p_script; // UNUSED
  570. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  571. #ifdef TOOLS_ENABLED
  572. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  573. #endif
  574. #ifdef GD_MONO_HOT_RELOAD
  575. if (is_assembly_reloading_needed()) {
  576. reload_assemblies(p_soft_reload);
  577. }
  578. #endif
  579. }
  580. #ifdef GD_MONO_HOT_RELOAD
  581. bool CSharpLanguage::is_assembly_reloading_needed() {
  582. if (!gdmono->is_runtime_initialized()) {
  583. return false;
  584. }
  585. #warning TODO
  586. #if 0
  587. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  588. String appname_safe = ProjectSettings::get_singleton()->get_safe_project_name();
  589. appname_safe += ".dll";
  590. if (proj_assembly) {
  591. String proj_asm_path = proj_assembly->get_path();
  592. if (!FileAccess::exists(proj_asm_path)) {
  593. // Maybe it wasn't loaded from the default path, so check this as well
  594. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
  595. if (!FileAccess::exists(proj_asm_path)) {
  596. return false; // No assembly to load
  597. }
  598. }
  599. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time()) {
  600. return false; // Already up to date
  601. }
  602. } else {
  603. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe))) {
  604. return false; // No assembly to load
  605. }
  606. }
  607. return true;
  608. #else
  609. return false;
  610. #endif
  611. }
  612. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  613. if (!gdmono->is_runtime_initialized()) {
  614. return;
  615. }
  616. #warning TODO ALCs after switching to .NET 6
  617. // Try to load the project assembly if it was not yet loaded
  618. // (while hot-reload is not yet implemented)
  619. gdmono->initialize_load_assemblies();
  620. {
  621. MutexLock lock(script_instances_mutex);
  622. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  623. Ref<CSharpScript> script(elem->self());
  624. script->exports_invalidated = true;
  625. if (!script->get_path().is_empty()) {
  626. script->reload(p_soft_reload);
  627. }
  628. }
  629. }
  630. #if 0
  631. // There is no soft reloading with Mono. It's always hard reloading.
  632. List<Ref<CSharpScript>> scripts;
  633. {
  634. MutexLock lock(script_instances_mutex);
  635. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  636. // Cast to CSharpScript to avoid being erased by accident
  637. scripts.push_back(Ref<CSharpScript>(elem->self()));
  638. }
  639. }
  640. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  641. // Serialize managed callables
  642. {
  643. MutexLock lock(ManagedCallable::instances_mutex);
  644. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  645. ManagedCallable *managed_callable = elem->self();
  646. Array serialized_data;
  647. MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
  648. MonoException *exc = nullptr;
  649. bool success = (bool)GDMonoCache::managed_callbacks.methodthunk_DelegateUtils_TrySerializeDelegateWithGCHandle
  650. .invoke(managed_callable->delegate_handle,
  651. managed_serialized_data, &exc);
  652. if (exc) {
  653. GDMonoUtils::debug_print_unhandled_exception(exc);
  654. continue;
  655. }
  656. if (success) {
  657. ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
  658. } else if (OS::get_singleton()->is_stdout_verbose()) {
  659. OS::get_singleton()->print("Failed to serialize delegate\n");
  660. }
  661. }
  662. }
  663. List<Ref<CSharpScript>> to_reload;
  664. // We need to keep reference instances alive during reloading
  665. List<Ref<RefCounted>> rc_instances;
  666. for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  667. const CSharpScriptBinding &script_binding = E.value;
  668. RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner);
  669. if (rc) {
  670. rc_instances.push_back(Ref<RefCounted>(rc));
  671. }
  672. }
  673. // As scripts are going to be reloaded, must proceed without locking here
  674. for (Ref<CSharpScript> &script : scripts) {
  675. // If someone removes a script from a node, deletes the script, builds, adds a script to the
  676. // same node, then builds again, the script might have no path and also no script_class. In
  677. // that case, we can't (and don't need to) reload it.
  678. if (script->get_path().is_empty() && !script->script_class) {
  679. continue;
  680. }
  681. to_reload.push_back(script);
  682. if (script->get_path().is_empty()) {
  683. script->tied_class_name_for_reload = script->script_class->get_name_for_lookup();
  684. script->tied_class_namespace_for_reload = script->script_class->get_namespace();
  685. }
  686. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  687. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  688. for (Object *obj : script->instances) {
  689. script->pending_reload_instances.insert(obj->get_instance_id());
  690. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  691. if (rc) {
  692. rc_instances.push_back(Ref<RefCounted>(rc));
  693. }
  694. }
  695. #ifdef TOOLS_ENABLED
  696. for (PlaceHolderScriptInstance *script_instance : script->placeholders) {
  697. Object *obj = script_instance->get_owner();
  698. script->pending_reload_instances.insert(obj->get_instance_id());
  699. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  700. if (rc) {
  701. rc_instances.push_back(Ref<RefCounted>(rc));
  702. }
  703. }
  704. #endif
  705. // Save state and remove script from instances
  706. RBMap<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
  707. for (Object *obj : script->instances) {
  708. ERR_CONTINUE(!obj->get_script_instance());
  709. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  710. // Call OnBeforeSerialize
  711. if (csi->script->script_class->implements_interface(GDMonoCache::cached_data.class_ISerializationListener)) {
  712. obj->get_script_instance()->call(string_names.on_before_serialize);
  713. }
  714. // Save instance info
  715. CSharpScript::StateBackup state;
  716. // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
  717. csi->get_properties_state_for_reloading(state.properties);
  718. csi->get_event_signals_state_for_reloading(state.event_signals);
  719. owners_map[obj->get_instance_id()] = state;
  720. }
  721. }
  722. // After the state of all instances is saved, clear scripts and script instances
  723. for (Ref<CSharpScript> &script : scripts) {
  724. while (script->instances.begin()) {
  725. Object *obj = *script->instances.begin();
  726. obj->set_script(Ref<RefCounted>()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  727. }
  728. script->_clear();
  729. }
  730. // Do domain reload
  731. if (gdmono->reload_scripts_domain() != OK) {
  732. // Failed to reload the scripts domain
  733. // Make sure to add the scripts back to their owners before returning
  734. for (Ref<CSharpScript> &scr : to_reload) {
  735. for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) {
  736. Object *obj = ObjectDB::get_instance(F.key);
  737. if (!obj) {
  738. continue;
  739. }
  740. ObjectID obj_id = obj->get_instance_id();
  741. // Use a placeholder for now to avoid losing the state when saving a scene
  742. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  743. obj->set_script_instance(placeholder);
  744. #ifdef TOOLS_ENABLED
  745. // Even though build didn't fail, this tells the placeholder to keep properties and
  746. // it allows using property_set_fallback for restoring the state without a valid script.
  747. scr->placeholder_fallback_enabled = true;
  748. #endif
  749. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  750. for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) {
  751. placeholder->property_set_fallback(G.first, G.second, nullptr);
  752. }
  753. scr->pending_reload_state.erase(obj_id);
  754. }
  755. }
  756. return;
  757. }
  758. List<Ref<CSharpScript>> to_reload_state;
  759. for (Ref<CSharpScript> &script : to_reload) {
  760. #ifdef TOOLS_ENABLED
  761. script->exports_invalidated = true;
  762. #endif
  763. if (!script->get_path().is_empty()) {
  764. script->reload(p_soft_reload);
  765. if (!script->valid) {
  766. script->pending_reload_instances.clear();
  767. continue;
  768. }
  769. } else {
  770. const StringName &class_namespace = script->tied_class_namespace_for_reload;
  771. const StringName &class_name = script->tied_class_name_for_reload;
  772. GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
  773. // Search in project and tools assemblies first as those are the most likely to have the class
  774. GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : nullptr);
  775. #ifdef TOOLS_ENABLED
  776. if (!script_class) {
  777. GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
  778. script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : nullptr);
  779. }
  780. #endif
  781. if (!script_class) {
  782. script_class = gdmono->get_class(class_namespace, class_name);
  783. }
  784. if (!script_class) {
  785. // The class was removed, can't reload
  786. script->pending_reload_instances.clear();
  787. continue;
  788. }
  789. bool obj_type = GDMonoCache::cached_data.class_GodotObject->is_assignable_from(script_class);
  790. if (!obj_type) {
  791. // The class no longer inherits Godot.Object, can't reload
  792. script->pending_reload_instances.clear();
  793. continue;
  794. }
  795. GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
  796. CSharpScript::reload_registered_script(script, script_class, native);
  797. }
  798. StringName native_name = NATIVE_GDMONOCLASS_NAME(script->native);
  799. {
  800. for (const ObjectID &obj_id : script->pending_reload_instances) {
  801. Object *obj = ObjectDB::get_instance(obj_id);
  802. if (!obj) {
  803. script->pending_reload_state.erase(obj_id);
  804. continue;
  805. }
  806. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  807. // No longer inherits the same compatible type, can't reload
  808. script->pending_reload_state.erase(obj_id);
  809. continue;
  810. }
  811. ScriptInstance *si = obj->get_script_instance();
  812. #ifdef TOOLS_ENABLED
  813. if (si) {
  814. // If the script instance is not null, then it must be a placeholder.
  815. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  816. CRASH_COND(!si->is_placeholder());
  817. if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
  818. // Replace placeholder with a script instance
  819. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  820. // Backup placeholder script instance state before replacing it with a script instance
  821. si->get_property_state(state_backup.properties);
  822. ScriptInstance *script_instance = script->instance_create(obj);
  823. if (script_instance) {
  824. script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  825. obj->set_script_instance(script_instance);
  826. }
  827. }
  828. continue;
  829. }
  830. #else
  831. CRASH_COND(si != nullptr);
  832. #endif
  833. // Re-create script instance
  834. obj->set_script(script); // will create the script instance as well
  835. }
  836. }
  837. to_reload_state.push_back(script);
  838. }
  839. for (Ref<CSharpScript> &script : to_reload_state) {
  840. for (const ObjectID &obj_id : script->pending_reload_instances) {
  841. Object *obj = ObjectDB::get_instance(obj_id);
  842. if (!obj) {
  843. script->pending_reload_state.erase(obj_id);
  844. continue;
  845. }
  846. ERR_CONTINUE(!obj->get_script_instance());
  847. // TODO: Restore serialized state
  848. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  849. for (const Pair<StringName, Variant> &G : state_backup.properties) {
  850. obj->get_script_instance()->set(G.first, G.second);
  851. }
  852. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  853. if (csi) {
  854. for (const Pair<StringName, Array> &G : state_backup.event_signals) {
  855. const StringName &name = G.first;
  856. const Array &serialized_data = G.second;
  857. HashMap<StringName, GDMonoField *>::Iterator match = script->event_signals.find(name);
  858. if (!match) {
  859. // The event or its signal attribute were removed
  860. continue;
  861. }
  862. GDMonoField *event_signal_field = match->value;
  863. MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
  864. MonoDelegate *delegate = nullptr;
  865. MonoException *exc = nullptr;
  866. bool success = (bool)GDMonoCache::managed_callbacks.methodthunk_DelegateUtils_TryDeserializeDelegate.invoke(managed_serialized_data, &delegate, &exc);
  867. if (exc) {
  868. GDMonoUtils::debug_print_unhandled_exception(exc);
  869. continue;
  870. }
  871. if (success) {
  872. ERR_CONTINUE(delegate == nullptr);
  873. event_signal_field->set_value(csi->get_mono_object(), (MonoObject *)delegate);
  874. } else if (OS::get_singleton()->is_stdout_verbose()) {
  875. OS::get_singleton()->print("Failed to deserialize event signal delegate\n");
  876. }
  877. }
  878. // Call OnAfterDeserialization
  879. if (csi->script->script_class->implements_interface(GDMonoCache::cached_data.class_ISerializationListener)) {
  880. obj->get_script_instance()->call(string_names.on_after_deserialize);
  881. }
  882. }
  883. }
  884. script->pending_reload_instances.clear();
  885. }
  886. // Deserialize managed callables
  887. {
  888. MutexLock lock(ManagedCallable::instances_mutex);
  889. for (const KeyValue<ManagedCallable *, Array> &elem : ManagedCallable::instances_pending_reload) {
  890. ManagedCallable *managed_callable = elem.key;
  891. const Array &serialized_data = elem.value;
  892. MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
  893. void *delegate = nullptr;
  894. MonoException *exc = nullptr;
  895. bool success = (bool)GDMonoCache::managed_callbacks.methodthunk_DelegateUtils_TryDeserializeDelegateWithGCHandle
  896. .invoke(managed_serialized_data, &delegate, &exc);
  897. if (exc) {
  898. GDMonoUtils::debug_print_unhandled_exception(exc);
  899. continue;
  900. }
  901. if (success) {
  902. ERR_CONTINUE(delegate == nullptr);
  903. managed_callable->delegate_handle = delegate;
  904. } else if (OS::get_singleton()->is_stdout_verbose()) {
  905. OS::get_singleton()->print("Failed to deserialize delegate\n");
  906. }
  907. }
  908. ManagedCallable::instances_pending_reload.clear();
  909. }
  910. #ifdef TOOLS_ENABLED
  911. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  912. if (Engine::get_singleton()->is_editor_hint()) {
  913. InspectorDock::get_inspector_singleton()->update_tree();
  914. NodeDock::get_singleton()->update_lists();
  915. }
  916. #endif
  917. #endif
  918. }
  919. #endif
  920. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  921. p_extensions->push_back("cs");
  922. }
  923. #ifdef TOOLS_ENABLED
  924. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  925. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  926. }
  927. bool CSharpLanguage::overrides_external_editor() {
  928. return get_godotsharp_editor()->call("OverridesExternalEditor");
  929. }
  930. #endif
  931. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  932. // Not a parser error in our case, but it's still used for other type of errors
  933. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  934. _debug_parse_err_line = p_line;
  935. _debug_parse_err_file = p_file;
  936. _debug_error = p_error;
  937. EngineDebugger::get_script_debugger()->debug(this, false, true);
  938. return true;
  939. } else {
  940. return false;
  941. }
  942. }
  943. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  944. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  945. _debug_parse_err_line = -1;
  946. _debug_parse_err_file = "";
  947. _debug_error = p_error;
  948. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue);
  949. return true;
  950. } else {
  951. return false;
  952. }
  953. }
  954. void CSharpLanguage::_on_scripts_domain_about_to_unload() {
  955. for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  956. CSharpScriptBinding &script_binding = E.value;
  957. script_binding.gchandle.release();
  958. script_binding.inited = false;
  959. }
  960. #ifdef GD_MONO_HOT_RELOAD
  961. {
  962. MutexLock lock(ManagedCallable::instances_mutex);
  963. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  964. ManagedCallable *managed_callable = elem->self();
  965. managed_callable->release_delegate_handle();
  966. }
  967. }
  968. #endif
  969. }
  970. #ifdef TOOLS_ENABLED
  971. void CSharpLanguage::_editor_init_callback() {
  972. // Load GodotTools and initialize GodotSharpEditor
  973. Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
  974. GodotSharpDirs::get_data_editor_tools_dir().plus_file("GodotTools.dll").utf16());
  975. CRASH_COND(editor_plugin_obj == nullptr);
  976. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);
  977. CRASH_COND(godotsharp_editor == nullptr);
  978. // Add plugin to EditorNode and enable it
  979. EditorNode::add_editor_plugin(godotsharp_editor);
  980. ED_SHORTCUT("mono/build_solution", TTR("Build Solution"), KeyModifierMask::ALT | Key::B);
  981. godotsharp_editor->enable_plugin();
  982. get_singleton()->godotsharp_editor = godotsharp_editor;
  983. }
  984. #endif
  985. void CSharpLanguage::set_language_index(int p_idx) {
  986. ERR_FAIL_COND(lang_idx != -1);
  987. lang_idx = p_idx;
  988. }
  989. void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
  990. if (!p_gchandle.is_released()) { // Do not lock unnecessarily
  991. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  992. p_gchandle.release();
  993. }
  994. }
  995. void CSharpLanguage::release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle) {
  996. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  997. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  998. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) {
  999. r_gchandle.release();
  1000. }
  1001. }
  1002. }
  1003. void CSharpLanguage::release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding) {
  1004. MonoGCHandleData &gchandle = r_script_binding.gchandle;
  1005. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  1006. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  1007. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) {
  1008. gchandle.release();
  1009. r_script_binding.inited = false; // Here too, to be thread safe
  1010. }
  1011. }
  1012. }
  1013. CSharpLanguage::CSharpLanguage() {
  1014. ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
  1015. singleton = this;
  1016. }
  1017. CSharpLanguage::~CSharpLanguage() {
  1018. finalize();
  1019. singleton = nullptr;
  1020. }
  1021. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  1022. #ifdef DEBUG_ENABLED
  1023. // I don't trust you
  1024. if (p_object->get_script_instance()) {
  1025. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  1026. CRASH_COND(csharp_instance != nullptr && !csharp_instance->is_destructing_script_instance());
  1027. }
  1028. #endif
  1029. StringName type_name = p_object->get_class_name();
  1030. // ¯\_(ツ)_/¯
  1031. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  1032. while (classinfo && !classinfo->exposed) {
  1033. classinfo = classinfo->inherits_ptr;
  1034. }
  1035. ERR_FAIL_NULL_V(classinfo, false);
  1036. type_name = classinfo->name;
  1037. bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), type_name);
  1038. ERR_FAIL_COND_V_MSG(!parent_is_object_class, false,
  1039. "Type inherits from native type '" + type_name + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
  1040. #ifdef DEBUG_ENABLED
  1041. CRASH_COND(!r_script_binding.gchandle.is_released());
  1042. #endif
  1043. GCHandleIntPtr strong_gchandle =
  1044. GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(&type_name, p_object);
  1045. ERR_FAIL_NULL_V(strong_gchandle.value, false);
  1046. r_script_binding.inited = true;
  1047. r_script_binding.type_name = type_name;
  1048. r_script_binding.gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1049. r_script_binding.owner = p_object;
  1050. // Tie managed to unmanaged
  1051. RefCounted *rc = Object::cast_to<RefCounted>(p_object);
  1052. if (rc) {
  1053. // Unsafe refcount increment. The managed instance also counts as a reference.
  1054. // This way if the unmanaged world has no references to our owner
  1055. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1056. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1057. rc->reference();
  1058. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1059. }
  1060. return true;
  1061. }
  1062. RBMap<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  1063. return script_bindings.insert(p_object, p_script_binding);
  1064. }
  1065. void *CSharpLanguage::_instance_binding_create_callback(void *, void *p_instance) {
  1066. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1067. MutexLock lock(csharp_lang->language_bind_mutex);
  1068. RBMap<Object *, CSharpScriptBinding>::Element *match = csharp_lang->script_bindings.find((Object *)p_instance);
  1069. if (match) {
  1070. return (void *)match;
  1071. }
  1072. CSharpScriptBinding script_binding;
  1073. return (void *)csharp_lang->insert_script_binding((Object *)p_instance, script_binding);
  1074. }
  1075. void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_binding) {
  1076. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1077. if (GDMono::get_singleton() == nullptr) {
  1078. #ifdef DEBUG_ENABLED
  1079. CRASH_COND(csharp_lang && !csharp_lang->script_bindings.is_empty());
  1080. #endif
  1081. // Mono runtime finalized, all the gchandle bindings were already released
  1082. return;
  1083. }
  1084. if (csharp_lang->finalizing) {
  1085. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1086. }
  1087. {
  1088. MutexLock lock(csharp_lang->language_bind_mutex);
  1089. RBMap<Object *, CSharpScriptBinding>::Element *data = (RBMap<Object *, CSharpScriptBinding>::Element *)p_binding;
  1090. CSharpScriptBinding &script_binding = data->value();
  1091. if (script_binding.inited) {
  1092. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1093. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1094. GDMonoCache::managed_callbacks.ScriptManagerBridge_SetGodotObjectPtr(
  1095. script_binding.gchandle.get_intptr(), nullptr);
  1096. script_binding.gchandle.release();
  1097. script_binding.inited = false;
  1098. }
  1099. csharp_lang->script_bindings.erase(data);
  1100. }
  1101. }
  1102. GDNativeBool CSharpLanguage::_instance_binding_reference_callback(void *p_token, void *p_binding, GDNativeBool p_reference) {
  1103. CRASH_COND(!p_binding);
  1104. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)p_binding)->get();
  1105. RefCounted *rc_owner = Object::cast_to<RefCounted>(script_binding.owner);
  1106. #ifdef DEBUG_ENABLED
  1107. CRASH_COND(!rc_owner);
  1108. #endif
  1109. MonoGCHandleData &gchandle = script_binding.gchandle;
  1110. int refcount = rc_owner->reference_get_count();
  1111. if (!script_binding.inited) {
  1112. return refcount == 0;
  1113. }
  1114. if (p_reference) {
  1115. // Refcount incremented
  1116. if (refcount > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1117. // The reference count was increased after the managed side was the only one referencing our owner.
  1118. // This means the owner is being referenced again by the unmanaged side,
  1119. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1120. // Release the current weak handle and replace it with a strong handle.
  1121. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1122. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1123. GCHandleIntPtr new_gchandle = { nullptr };
  1124. bool create_weak = false;
  1125. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1126. old_gchandle, &new_gchandle, create_weak);
  1127. if (!target_alive) {
  1128. return false; // Called after the managed side was collected, so nothing to do here
  1129. }
  1130. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1131. }
  1132. return false;
  1133. } else {
  1134. // Refcount decremented
  1135. if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1136. // If owner owner is no longer referenced by the unmanaged side,
  1137. // the managed instance takes responsibility of deleting the owner when GCed.
  1138. // Release the current strong handle and replace it with a weak handle.
  1139. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1140. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1141. GCHandleIntPtr new_gchandle = { nullptr };
  1142. bool create_weak = true;
  1143. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1144. old_gchandle, &new_gchandle, create_weak);
  1145. if (!target_alive) {
  1146. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1147. }
  1148. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1149. return false;
  1150. }
  1151. return refcount == 0;
  1152. }
  1153. }
  1154. void *CSharpLanguage::get_instance_binding(Object *p_object) {
  1155. void *binding = p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1156. // Initially this was in `_instance_binding_create_callback`. However, after the new instance
  1157. // binding re-write it was resulting in a deadlock in `_instance_binding_reference`, as
  1158. // `setup_csharp_script_binding` may call `reference()`. It was moved here outside to fix that.
  1159. if (binding) {
  1160. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1161. if (!script_binding.inited) {
  1162. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1163. if (!script_binding.inited) { // Another thread may have set it up
  1164. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, p_object);
  1165. }
  1166. }
  1167. }
  1168. return binding;
  1169. }
  1170. void *CSharpLanguage::get_existing_instance_binding(Object *p_object) {
  1171. #ifdef DEBUG_ENABLED
  1172. CRASH_COND(p_object->has_instance_binding(p_object));
  1173. #endif
  1174. return p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1175. }
  1176. void CSharpLanguage::set_instance_binding(Object *p_object, void *p_binding) {
  1177. p_object->set_instance_binding(get_singleton(), p_binding, &_instance_binding_callbacks);
  1178. }
  1179. bool CSharpLanguage::has_instance_binding(Object *p_object) {
  1180. return p_object->has_instance_binding(get_singleton());
  1181. }
  1182. void CSharpLanguage::tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
  1183. // This method should not fail
  1184. CRASH_COND(!p_unmanaged);
  1185. // All mono objects created from the managed world (e.g.: 'new Player()')
  1186. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1187. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1188. CRASH_COND(p_ref_counted != (bool)rc);
  1189. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1190. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1191. // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
  1192. // script binding instead. One of the advantages of this is that if a script is attached
  1193. // later and it's not a C# script, then the managed object won't have to be disposed.
  1194. // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
  1195. // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
  1196. CSharpScriptBinding script_binding;
  1197. script_binding.inited = true;
  1198. script_binding.type_name = *p_native_name;
  1199. script_binding.gchandle = gchandle;
  1200. script_binding.owner = p_unmanaged;
  1201. if (p_ref_counted) {
  1202. // Unsafe refcount increment. The managed instance also counts as a reference.
  1203. // This way if the unmanaged world has no references to our owner
  1204. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1205. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1206. // May not me referenced yet, so we must use init_ref() instead of reference()
  1207. if (rc->init_ref()) {
  1208. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1209. }
  1210. }
  1211. // The object was just created, no script instance binding should have been attached
  1212. CRASH_COND(CSharpLanguage::has_instance_binding(p_unmanaged));
  1213. void *data;
  1214. {
  1215. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1216. data = (void *)CSharpLanguage::get_singleton()->insert_script_binding(p_unmanaged, script_binding);
  1217. }
  1218. // Should be thread safe because the object was just created and nothing else should be referencing it
  1219. CSharpLanguage::set_instance_binding(p_unmanaged, data);
  1220. }
  1221. void CSharpLanguage::tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
  1222. // This method should not fail
  1223. Ref<CSharpScript> script = *p_script;
  1224. // We take care of destructing this reference here, so the managed code won't need to do another P/Invoke call
  1225. p_script->~Ref();
  1226. CRASH_COND(!p_unmanaged);
  1227. // All mono objects created from the managed world (e.g.: 'new Player()')
  1228. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1229. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1230. CRASH_COND(p_ref_counted != (bool)rc);
  1231. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1232. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1233. CRASH_COND(script.is_null());
  1234. CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(p_unmanaged, script.ptr(), gchandle);
  1235. p_unmanaged->set_script_and_instance(script, csharp_instance);
  1236. }
  1237. void CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
  1238. // This method should not fail
  1239. CRASH_COND(!p_unmanaged);
  1240. CSharpInstance *instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
  1241. if (!instance) {
  1242. // Native bindings don't need post-setup
  1243. return;
  1244. }
  1245. CRASH_COND(!instance->gchandle.is_released());
  1246. // Tie managed to unmanaged
  1247. instance->gchandle = MonoGCHandleData(p_gchandle_intptr, gdmono::GCHandleType::STRONG_HANDLE);
  1248. if (instance->base_ref_counted) {
  1249. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1250. }
  1251. {
  1252. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1253. // instances is a set, so it's safe to insert multiple times (e.g.: from _internal_new_managed)
  1254. instance->script->instances.insert(instance->owner);
  1255. }
  1256. }
  1257. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
  1258. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
  1259. RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
  1260. instance->base_ref_counted = rc != nullptr;
  1261. instance->owner = p_owner;
  1262. instance->gchandle = p_gchandle;
  1263. if (instance->base_ref_counted) {
  1264. instance->_reference_owner_unsafe();
  1265. }
  1266. p_script->instances.insert(p_owner);
  1267. return instance;
  1268. }
  1269. Object *CSharpInstance::get_owner() {
  1270. return owner;
  1271. }
  1272. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1273. ERR_FAIL_COND_V(!script.is_valid(), false);
  1274. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_Set(
  1275. gchandle.get_intptr(), &p_name, &p_value);
  1276. }
  1277. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1278. ERR_FAIL_COND_V(!script.is_valid(), false);
  1279. Variant ret_value;
  1280. bool ret = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Get(
  1281. gchandle.get_intptr(), &p_name, &ret_value);
  1282. if (ret) {
  1283. r_ret = ret_value;
  1284. return true;
  1285. }
  1286. return false;
  1287. }
  1288. #warning TODO
  1289. #if 0
  1290. void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state) {
  1291. List<PropertyInfo> property_list;
  1292. get_property_list(&property_list);
  1293. for (const PropertyInfo &prop_info : property_list) {
  1294. Pair<StringName, Variant> state_pair;
  1295. state_pair.first = prop_info.name;
  1296. ManagedType managedType;
  1297. GDMonoField *field = nullptr;
  1298. GDMonoClass *top = script->script_class;
  1299. while (top && top != script->native) {
  1300. field = top->get_field(state_pair.first);
  1301. if (field) {
  1302. break;
  1303. }
  1304. top = top->get_parent_class();
  1305. }
  1306. if (!field) {
  1307. continue; // Properties ignored. We get the property baking fields instead.
  1308. }
  1309. managedType = field->get_type();
  1310. if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
  1311. if (get(state_pair.first, state_pair.second)) {
  1312. r_state.push_back(state_pair);
  1313. }
  1314. }
  1315. }
  1316. }
  1317. void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state) {
  1318. MonoObject *owner_managed = get_mono_object();
  1319. ERR_FAIL_NULL(owner_managed);
  1320. for (const KeyValue<StringName, GDMonoField *> &E : script->event_signals) {
  1321. GDMonoField *event_signal_field = E.value;
  1322. MonoDelegate *delegate_field_value = (MonoDelegate *)event_signal_field->get_value(owner_managed);
  1323. if (!delegate_field_value) {
  1324. continue; // Empty
  1325. }
  1326. Array serialized_data;
  1327. MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
  1328. MonoException *exc = nullptr;
  1329. bool success = (bool)GDMonoCache::managed_callbacks.methodthunk_DelegateUtils_TrySerializeDelegate
  1330. .invoke(delegate_field_value, managed_serialized_data, &exc);
  1331. if (exc) {
  1332. GDMonoUtils::debug_print_unhandled_exception(exc);
  1333. continue;
  1334. }
  1335. if (success) {
  1336. r_state.push_back(Pair<StringName, Array>(event_signal_field->get_name(), serialized_data));
  1337. } else if (OS::get_singleton()->is_stdout_verbose()) {
  1338. OS::get_singleton()->print("Failed to serialize event signal delegate\n");
  1339. }
  1340. }
  1341. }
  1342. #endif
  1343. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1344. List<PropertyInfo> props;
  1345. script->get_script_property_list(&props);
  1346. // Call _get_property_list
  1347. ERR_FAIL_COND(!script.is_valid());
  1348. StringName method = SNAME("_get_property_list");
  1349. Variant ret;
  1350. Callable::CallError call_error;
  1351. bool ok = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1352. gchandle.get_intptr(), &method, nullptr, 0, &call_error, &ret);
  1353. // CALL_ERROR_INVALID_METHOD would simply mean it was not overridden
  1354. if (call_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) {
  1355. if (call_error.error != Callable::CallError::CALL_OK) {
  1356. ERR_PRINT("Error calling '_get_property_list': " + Variant::get_call_error_text(method, nullptr, 0, call_error));
  1357. } else if (!ok) {
  1358. ERR_PRINT("Unexpected error calling '_get_property_list'");
  1359. } else {
  1360. Array array = ret;
  1361. for (int i = 0, size = array.size(); i < size; i++) {
  1362. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1363. }
  1364. }
  1365. }
  1366. for (const PropertyInfo &prop : props) {
  1367. p_properties->push_back(prop);
  1368. }
  1369. }
  1370. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1371. if (script->member_info.has(p_name)) {
  1372. if (r_is_valid) {
  1373. *r_is_valid = true;
  1374. }
  1375. return script->member_info[p_name].type;
  1376. }
  1377. if (r_is_valid) {
  1378. *r_is_valid = false;
  1379. }
  1380. return Variant::NIL;
  1381. }
  1382. bool CSharpInstance::property_can_revert(const StringName &p_name) const {
  1383. ERR_FAIL_COND_V(!script.is_valid(), false);
  1384. Variant name_arg = p_name;
  1385. const Variant *args[1] = { &name_arg };
  1386. Variant ret;
  1387. Callable::CallError call_error;
  1388. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1389. gchandle.get_intptr(), &CACHED_STRING_NAME(_property_can_revert), args, 1, &call_error, &ret);
  1390. if (call_error.error != Callable::CallError::CALL_OK) {
  1391. return false;
  1392. }
  1393. return (bool)ret;
  1394. }
  1395. bool CSharpInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
  1396. ERR_FAIL_COND_V(!script.is_valid(), false);
  1397. Variant name_arg = p_name;
  1398. const Variant *args[1] = { &name_arg };
  1399. Variant ret;
  1400. Callable::CallError call_error;
  1401. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1402. gchandle.get_intptr(), &CACHED_STRING_NAME(_property_get_revert), args, 1, &call_error, &ret);
  1403. if (call_error.error != Callable::CallError::CALL_OK) {
  1404. return false;
  1405. }
  1406. r_ret = ret;
  1407. return true;
  1408. }
  1409. void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
  1410. #warning TODO
  1411. #if 0
  1412. if (!script->is_valid() || !script->script_class) {
  1413. return;
  1414. }
  1415. GD_MONO_SCOPE_THREAD_ATTACH;
  1416. // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
  1417. GDMonoClass *top = script->script_class;
  1418. while (top && top != script->native) {
  1419. const Vector<GDMonoMethod *> &methods = top->get_all_methods();
  1420. for (int i = 0; i < methods.size(); ++i) {
  1421. MethodInfo minfo = methods[i]->get_method_info();
  1422. if (minfo.name != CACHED_STRING_NAME(dotctor)) {
  1423. p_list->push_back(minfo);
  1424. }
  1425. }
  1426. top = top->get_parent_class();
  1427. }
  1428. #endif
  1429. }
  1430. bool CSharpInstance::has_method(const StringName &p_method) const {
  1431. if (!script.is_valid()) {
  1432. return false;
  1433. }
  1434. if (!GDMonoCache::godot_api_cache_updated) {
  1435. return false;
  1436. }
  1437. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_HasMethodUnknownParams(
  1438. gchandle.get_intptr(), &p_method);
  1439. }
  1440. Variant CSharpInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1441. ERR_FAIL_COND_V(!script.is_valid(), Variant());
  1442. Variant ret;
  1443. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1444. gchandle.get_intptr(), &p_method, p_args, p_argcount, &r_error, &ret);
  1445. return ret;
  1446. }
  1447. bool CSharpInstance::_reference_owner_unsafe() {
  1448. #ifdef DEBUG_ENABLED
  1449. CRASH_COND(!base_ref_counted);
  1450. CRASH_COND(owner == nullptr);
  1451. CRASH_COND(unsafe_referenced); // already referenced
  1452. #endif
  1453. // Unsafe refcount increment. The managed instance also counts as a reference.
  1454. // This way if the unmanaged world has no references to our owner
  1455. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1456. // See: _unreference_owner_unsafe()
  1457. // May not me referenced yet, so we must use init_ref() instead of reference()
  1458. if (static_cast<RefCounted *>(owner)->init_ref()) {
  1459. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1460. unsafe_referenced = true;
  1461. }
  1462. return unsafe_referenced;
  1463. }
  1464. bool CSharpInstance::_unreference_owner_unsafe() {
  1465. #ifdef DEBUG_ENABLED
  1466. CRASH_COND(!base_ref_counted);
  1467. CRASH_COND(owner == nullptr);
  1468. #endif
  1469. if (!unsafe_referenced) {
  1470. return false; // Already unreferenced
  1471. }
  1472. unsafe_referenced = false;
  1473. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1474. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1475. // See: _reference_owner_unsafe()
  1476. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1477. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1478. return static_cast<RefCounted *>(owner)->unreference();
  1479. }
  1480. bool CSharpInstance::_internal_new_managed() {
  1481. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1482. ERR_FAIL_NULL_V(owner, false);
  1483. ERR_FAIL_COND_V(script.is_null(), false);
  1484. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1485. script.ptr(), owner, nullptr, 0);
  1486. if (!ok) {
  1487. // Important to clear this before destroying the script instance here
  1488. script = Ref<CSharpScript>();
  1489. owner = nullptr;
  1490. return false;
  1491. }
  1492. CRASH_COND(gchandle.is_released());
  1493. return true;
  1494. }
  1495. void CSharpInstance::mono_object_disposed(GCHandleIntPtr p_gchandle_to_free) {
  1496. // Must make sure event signals are not left dangling
  1497. disconnect_event_signals();
  1498. #ifdef DEBUG_ENABLED
  1499. CRASH_COND(base_ref_counted);
  1500. CRASH_COND(gchandle.is_released());
  1501. #endif
  1502. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1503. }
  1504. void CSharpInstance::mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1505. #ifdef DEBUG_ENABLED
  1506. CRASH_COND(!base_ref_counted);
  1507. CRASH_COND(gchandle.is_released());
  1508. #endif
  1509. // Must make sure event signals are not left dangling
  1510. disconnect_event_signals();
  1511. r_remove_script_instance = false;
  1512. if (_unreference_owner_unsafe()) {
  1513. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1514. r_delete_owner = true;
  1515. } else {
  1516. r_delete_owner = false;
  1517. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1518. if (!p_is_finalizer) {
  1519. // If the native instance is still alive and Dispose() was called
  1520. // (instead of the finalizer), then we remove the script instance.
  1521. r_remove_script_instance = true;
  1522. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1523. // If the native instance is still alive and this is called from the finalizer,
  1524. // then it was referenced from another thread before the finalizer could
  1525. // unreference and delete it, so we want to keep it.
  1526. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1527. // could have already been collected. Instead we will create a new managed instance here.
  1528. if (!_internal_new_managed()) {
  1529. r_remove_script_instance = true;
  1530. }
  1531. }
  1532. }
  1533. }
  1534. void CSharpInstance::connect_event_signal(const StringName &p_event_signal) {
  1535. // TODO: Use pooling for ManagedCallable instances.
  1536. EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, p_event_signal));
  1537. Callable callable(event_signal_callable);
  1538. connected_event_signals.push_back(callable);
  1539. owner->connect(p_event_signal, callable);
  1540. }
  1541. void CSharpInstance::disconnect_event_signals() {
  1542. for (const Callable &callable : connected_event_signals) {
  1543. const EventSignalCallable *event_signal_callable = static_cast<const EventSignalCallable *>(callable.get_custom());
  1544. owner->disconnect(event_signal_callable->get_signal(), callable);
  1545. }
  1546. connected_event_signals.clear();
  1547. }
  1548. void CSharpInstance::refcount_incremented() {
  1549. #ifdef DEBUG_ENABLED
  1550. CRASH_COND(!base_ref_counted);
  1551. CRASH_COND(owner == nullptr);
  1552. #endif
  1553. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1554. if (rc_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1555. // The reference count was increased after the managed side was the only one referencing our owner.
  1556. // This means the owner is being referenced again by the unmanaged side,
  1557. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1558. // Release the current weak handle and replace it with a strong handle.
  1559. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1560. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1561. GCHandleIntPtr new_gchandle = { nullptr };
  1562. bool create_weak = false;
  1563. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1564. old_gchandle, &new_gchandle, create_weak);
  1565. if (!target_alive) {
  1566. return; // Called after the managed side was collected, so nothing to do here
  1567. }
  1568. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1569. }
  1570. }
  1571. bool CSharpInstance::refcount_decremented() {
  1572. #ifdef DEBUG_ENABLED
  1573. CRASH_COND(!base_ref_counted);
  1574. CRASH_COND(owner == nullptr);
  1575. #endif
  1576. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1577. int refcount = rc_owner->reference_get_count();
  1578. if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1579. // If owner owner is no longer referenced by the unmanaged side,
  1580. // the managed instance takes responsibility of deleting the owner when GCed.
  1581. // Release the current strong handle and replace it with a weak handle.
  1582. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1583. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1584. GCHandleIntPtr new_gchandle = { nullptr };
  1585. bool create_weak = true;
  1586. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1587. old_gchandle, &new_gchandle, create_weak);
  1588. if (!target_alive) {
  1589. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1590. }
  1591. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1592. return false;
  1593. }
  1594. ref_dying = (refcount == 0);
  1595. return ref_dying;
  1596. }
  1597. const Variant CSharpInstance::get_rpc_config() const {
  1598. return script->get_rpc_config();
  1599. }
  1600. void CSharpInstance::notification(int p_notification) {
  1601. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1602. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1603. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1604. // to be sent at least once, which happens right before the call to the destructor.
  1605. predelete_notified = true;
  1606. if (base_ref_counted) {
  1607. // It's not safe to proceed if the owner derives RefCounted and the refcount reached 0.
  1608. // At this point, Dispose() was already called (manually or from the finalizer) so
  1609. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1610. // managed side references it and Dispose() needs to be called to release it.
  1611. // However, this means C# RefCounted scripts can't receive NOTIFICATION_PREDELETE, but
  1612. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1613. return;
  1614. }
  1615. _call_notification(p_notification);
  1616. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1617. gchandle.get_intptr(), /* okIfNull */ false);
  1618. return;
  1619. }
  1620. _call_notification(p_notification);
  1621. }
  1622. void CSharpInstance::_call_notification(int p_notification) {
  1623. Variant arg = p_notification;
  1624. const Variant *args[1] = { &arg };
  1625. StringName method_name = SNAME("_notification");
  1626. Callable::CallError call_error;
  1627. Variant ret;
  1628. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1629. gchandle.get_intptr(), &method_name, args, 1, &call_error, &ret);
  1630. }
  1631. String CSharpInstance::to_string(bool *r_valid) {
  1632. String res;
  1633. bool valid;
  1634. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallToString(
  1635. gchandle.get_intptr(), &res, &valid);
  1636. if (r_valid) {
  1637. *r_valid = valid;
  1638. }
  1639. return res;
  1640. }
  1641. Ref<Script> CSharpInstance::get_script() const {
  1642. return script;
  1643. }
  1644. ScriptLanguage *CSharpInstance::get_language() {
  1645. return CSharpLanguage::get_singleton();
  1646. }
  1647. CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
  1648. script(p_script) {
  1649. }
  1650. CSharpInstance::~CSharpInstance() {
  1651. destructing_script_instance = true;
  1652. // Must make sure event signals are not left dangling
  1653. disconnect_event_signals();
  1654. if (!gchandle.is_released()) {
  1655. if (!predelete_notified && !ref_dying) {
  1656. // This destructor is not called from the owners destructor.
  1657. // This could be being called from the owner's set_script_instance method,
  1658. // meaning this script is being replaced with another one. If this is the case,
  1659. // we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
  1660. // and that would mess up with the new script instance if called later.
  1661. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1662. gchandle.get_intptr(), /* okIfNull */ true);
  1663. }
  1664. gchandle.release(); // Make sure the gchandle is released
  1665. }
  1666. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1667. if (base_ref_counted && !ref_dying && owner && unsafe_referenced) {
  1668. // The owner's script or script instance is being replaced (or removed)
  1669. // Transfer ownership to an "instance binding"
  1670. RefCounted *rc_owner = static_cast<RefCounted *>(owner);
  1671. // We will unreference the owner before referencing it again, so we need to keep it alive
  1672. Ref<RefCounted> scope_keep_owner_alive(rc_owner);
  1673. (void)scope_keep_owner_alive;
  1674. // Unreference the owner here, before the new "instance binding" references it.
  1675. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
  1676. bool die = _unreference_owner_unsafe();
  1677. CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
  1678. void *data = CSharpLanguage::get_instance_binding(owner);
  1679. CRASH_COND(data == nullptr);
  1680. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1681. CRASH_COND(!script_binding.inited);
  1682. #ifdef DEBUG_ENABLED
  1683. // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
  1684. CRASH_COND(rc_owner->reference_get_count() <= 1);
  1685. #endif
  1686. }
  1687. if (script.is_valid() && owner) {
  1688. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1689. #ifdef DEBUG_ENABLED
  1690. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1691. HashSet<Object *>::Iterator match = script->instances.find(owner);
  1692. CRASH_COND(!match);
  1693. script->instances.remove(match);
  1694. #else
  1695. script->instances.erase(owner);
  1696. #endif
  1697. }
  1698. }
  1699. #ifdef TOOLS_ENABLED
  1700. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1701. placeholders.erase(p_placeholder);
  1702. }
  1703. #endif
  1704. #ifdef TOOLS_ENABLED
  1705. void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1706. for (const KeyValue<StringName, Variant> &E : exported_members_defval_cache) {
  1707. values[E.key] = E.value;
  1708. }
  1709. for (const PropertyInfo &prop_info : exported_members_cache) {
  1710. propnames.push_back(prop_info);
  1711. }
  1712. if (base_cache.is_valid()) {
  1713. base_cache->_update_exports_values(values, propnames);
  1714. }
  1715. }
  1716. #endif
  1717. bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) {
  1718. #ifdef TOOLS_ENABLED
  1719. bool is_editor = Engine::get_singleton()->is_editor_hint();
  1720. if (is_editor) {
  1721. placeholder_fallback_enabled = true; // until proven otherwise
  1722. }
  1723. #endif
  1724. if (!valid) {
  1725. return false;
  1726. }
  1727. bool changed = false;
  1728. #ifdef TOOLS_ENABLED
  1729. if (exports_invalidated)
  1730. #endif
  1731. {
  1732. #ifdef TOOLS_ENABLED
  1733. exports_invalidated = false;
  1734. #endif
  1735. changed = true;
  1736. member_info.clear();
  1737. #ifdef TOOLS_ENABLED
  1738. exported_members_cache.clear();
  1739. exported_members_defval_cache.clear();
  1740. #endif
  1741. if (GDMonoCache::godot_api_cache_updated) {
  1742. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this,
  1743. [](CSharpScript *p_script, const String *p_current_class_name, GDMonoCache::godotsharp_property_info *p_props, int32_t p_count) {
  1744. #ifdef TOOLS_ENABLED
  1745. p_script->exported_members_cache.push_back(PropertyInfo(
  1746. Variant::NIL, *p_current_class_name, PROPERTY_HINT_NONE,
  1747. p_script->get_path(), PROPERTY_USAGE_CATEGORY));
  1748. #endif
  1749. for (int i = 0; i < p_count; i++) {
  1750. const GDMonoCache::godotsharp_property_info &prop = p_props[i];
  1751. StringName name = *reinterpret_cast<const StringName *>(&prop.name);
  1752. String hint_string = *reinterpret_cast<const String *>(&prop.hint_string);
  1753. PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage);
  1754. p_script->member_info[name] = pinfo;
  1755. if (prop.exported) {
  1756. #ifdef TOOLS_ENABLED
  1757. p_script->exported_members_cache.push_back(pinfo);
  1758. #endif
  1759. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1760. p_script->exported_members_names.insert(name);
  1761. #endif
  1762. }
  1763. }
  1764. });
  1765. #ifdef TOOLS_ENABLED
  1766. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this,
  1767. [](CSharpScript *p_script, GDMonoCache::godotsharp_property_def_val_pair *p_def_vals, int32_t p_count) {
  1768. for (int i = 0; i < p_count; i++) {
  1769. const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = p_def_vals[i];
  1770. StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name);
  1771. Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value);
  1772. p_script->exported_members_defval_cache[name] = value;
  1773. }
  1774. });
  1775. #endif
  1776. }
  1777. }
  1778. #ifdef TOOLS_ENABLED
  1779. if (is_editor) {
  1780. placeholder_fallback_enabled = false;
  1781. if ((changed || p_instance_to_update) && placeholders.size()) {
  1782. // Update placeholders if any
  1783. HashMap<StringName, Variant> values;
  1784. List<PropertyInfo> propnames;
  1785. _update_exports_values(values, propnames);
  1786. if (changed) {
  1787. for (PlaceHolderScriptInstance *script_instance : placeholders) {
  1788. script_instance->update(propnames, values);
  1789. }
  1790. } else {
  1791. p_instance_to_update->update(propnames, values);
  1792. }
  1793. }
  1794. }
  1795. #endif
  1796. return changed;
  1797. }
  1798. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1799. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1800. r_ret = get_source_code();
  1801. return true;
  1802. }
  1803. return false;
  1804. }
  1805. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1806. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1807. set_source_code(p_value);
  1808. reload();
  1809. return true;
  1810. }
  1811. return false;
  1812. }
  1813. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1814. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
  1815. }
  1816. void CSharpScript::_bind_methods() {
  1817. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  1818. }
  1819. void CSharpScript::reload_registered_script(Ref<CSharpScript> p_script) {
  1820. // IMPORTANT:
  1821. // This method must be called only after the CSharpScript and its associated type
  1822. // have been added to the script bridge map in the ScriptManagerBridge C# class.
  1823. // Other than that, it's the same as `CSharpScript::reload`.
  1824. // This method should not fail, only assertions allowed.
  1825. // Unlike `reload`, we print an error rather than silently returning,
  1826. // as we can assert this won't be called a second time until invalidated.
  1827. ERR_FAIL_COND(!p_script->reload_invalidated);
  1828. p_script->valid = true;
  1829. p_script->reload_invalidated = false;
  1830. update_script_class_info(p_script);
  1831. p_script->_update_exports();
  1832. }
  1833. // Extract information about the script using the mono class.
  1834. void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
  1835. bool tool = false;
  1836. Dictionary rpc_functions_dict;
  1837. // Destructor won't be called from C#, and I don't want to include the GDNative header
  1838. // only for this, so need to call the destructor manually before passing this to C#.
  1839. rpc_functions_dict.~Dictionary();
  1840. GDMonoCache::managed_callbacks.ScriptManagerBridge_UpdateScriptClassInfo(
  1841. p_script.ptr(), &tool, &rpc_functions_dict);
  1842. p_script->tool = tool;
  1843. p_script->rpc_config.clear();
  1844. p_script->rpc_config = rpc_functions_dict;
  1845. }
  1846. bool CSharpScript::can_instantiate() const {
  1847. #ifdef TOOLS_ENABLED
  1848. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  1849. #else
  1850. bool extra_cond = true;
  1851. #endif
  1852. // FIXME Need to think this through better.
  1853. // For tool scripts, this will never fire if the class is not found. That's because we
  1854. // don't know if it's a tool script if we can't find the class to access the attributes.
  1855. if (extra_cond && !valid) {
  1856. ERR_FAIL_V_MSG(false, "Cannot instance script because the associated class could not be found. Script: '" + get_path() + "'.");
  1857. }
  1858. return valid && extra_cond;
  1859. }
  1860. StringName CSharpScript::get_instance_base_type() const {
  1861. StringName native_name;
  1862. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1863. return native_name;
  1864. }
  1865. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
  1866. /* STEP 1, CREATE */
  1867. Ref<RefCounted> ref;
  1868. if (p_is_ref_counted) {
  1869. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  1870. ref = Ref<RefCounted>(static_cast<RefCounted *>(p_owner));
  1871. }
  1872. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  1873. if (CSharpLanguage::has_instance_binding(p_owner)) {
  1874. void *data = CSharpLanguage::get_existing_instance_binding(p_owner);
  1875. CRASH_COND(data == nullptr);
  1876. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1877. if (script_binding.inited && !script_binding.gchandle.is_released()) {
  1878. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1879. script_binding.gchandle.get_intptr(), /* okIfNull */ true);
  1880. script_binding.gchandle.release(); // Just in case
  1881. script_binding.inited = false;
  1882. }
  1883. }
  1884. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this)));
  1885. instance->base_ref_counted = p_is_ref_counted;
  1886. instance->owner = p_owner;
  1887. instance->owner->set_script_instance(instance);
  1888. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1889. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1890. this, p_owner, p_args, p_argcount);
  1891. if (!ok) {
  1892. // Important to clear this before destroying the script instance here
  1893. instance->script = Ref<CSharpScript>();
  1894. instance->owner = nullptr;
  1895. p_owner->set_script_instance(nullptr);
  1896. return nullptr;
  1897. }
  1898. CRASH_COND(instance->gchandle.is_released());
  1899. /* STEP 3, PARTY */
  1900. //@TODO make thread safe
  1901. return instance;
  1902. }
  1903. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1904. if (!valid) {
  1905. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1906. return Variant();
  1907. }
  1908. r_error.error = Callable::CallError::CALL_OK;
  1909. StringName native_name;
  1910. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1911. ERR_FAIL_COND_V(native_name == StringName(), Variant());
  1912. Object *owner = ClassDB::instantiate(native_name);
  1913. Ref<RefCounted> ref;
  1914. RefCounted *r = Object::cast_to<RefCounted>(owner);
  1915. if (r) {
  1916. ref = Ref<RefCounted>(r);
  1917. }
  1918. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
  1919. if (!instance) {
  1920. if (ref.is_null()) {
  1921. memdelete(owner); // no owner, sorry
  1922. }
  1923. return Variant();
  1924. }
  1925. if (ref.is_valid()) {
  1926. return ref;
  1927. } else {
  1928. return owner;
  1929. }
  1930. }
  1931. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1932. #ifdef DEBUG_ENABLED
  1933. CRASH_COND(!valid);
  1934. #endif
  1935. StringName native_name;
  1936. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1937. ERR_FAIL_COND_V(native_name == StringName(), nullptr);
  1938. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1939. if (EngineDebugger::is_active()) {
  1940. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
  1941. "Script inherits from native type '" + String(native_name) +
  1942. "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'");
  1943. }
  1944. ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'.");
  1945. }
  1946. Callable::CallError unchecked_error;
  1947. return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error);
  1948. }
  1949. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1950. #ifdef TOOLS_ENABLED
  1951. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1952. placeholders.insert(si);
  1953. _update_exports(si);
  1954. return si;
  1955. #else
  1956. return nullptr;
  1957. #endif
  1958. }
  1959. bool CSharpScript::instance_has(const Object *p_this) const {
  1960. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1961. return instances.has((Object *)p_this);
  1962. }
  1963. bool CSharpScript::has_source_code() const {
  1964. return !source.is_empty();
  1965. }
  1966. String CSharpScript::get_source_code() const {
  1967. return source;
  1968. }
  1969. void CSharpScript::set_source_code(const String &p_code) {
  1970. if (source == p_code) {
  1971. return;
  1972. }
  1973. source = p_code;
  1974. #ifdef TOOLS_ENABLED
  1975. source_changed_cache = true;
  1976. #endif
  1977. }
  1978. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  1979. if (!valid) {
  1980. return;
  1981. }
  1982. #warning TODO
  1983. #if 0
  1984. // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
  1985. GDMonoClass *top = script_class;
  1986. while (top && top != native) {
  1987. const Vector<GDMonoMethod *> &methods = top->get_all_methods();
  1988. for (int i = 0; i < methods.size(); ++i) {
  1989. MethodInfo minfo = methods[i]->get_method_info();
  1990. if (minfo.name != CACHED_STRING_NAME(dotctor)) {
  1991. p_list->push_back(methods[i]->get_method_info());
  1992. }
  1993. }
  1994. top = top->get_parent_class();
  1995. }
  1996. #endif
  1997. }
  1998. bool CSharpScript::has_method(const StringName &p_method) const {
  1999. // The equivalent of this will be implemented once we switch to the GDExtension system
  2000. ERR_PRINT_ONCE("CSharpScript::has_method is not implemented");
  2001. return false;
  2002. }
  2003. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2004. if (!valid) {
  2005. return MethodInfo();
  2006. }
  2007. #warning TODO
  2008. #if 0
  2009. GDMonoClass *top = script_class;
  2010. while (top && top != native) {
  2011. GDMonoMethod *params = top->get_method_unknown_params(p_method);
  2012. if (params) {
  2013. return params->get_method_info();
  2014. }
  2015. top = top->get_parent_class();
  2016. }
  2017. #endif
  2018. return MethodInfo();
  2019. }
  2020. Error CSharpScript::reload(bool p_keep_state) {
  2021. if (!reload_invalidated) {
  2022. return OK;
  2023. }
  2024. // In the case of C#, reload doesn't really do any script reloading.
  2025. // That's done separately via domain reloading.
  2026. reload_invalidated = false;
  2027. String script_path = get_path();
  2028. valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(this, &script_path);
  2029. if (valid) {
  2030. #ifdef DEBUG_ENABLED
  2031. print_verbose("Found class for script " + get_path());
  2032. #endif
  2033. update_script_class_info(this);
  2034. _update_exports();
  2035. }
  2036. return OK;
  2037. }
  2038. ScriptLanguage *CSharpScript::get_language() const {
  2039. return CSharpLanguage::get_singleton();
  2040. }
  2041. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2042. #ifdef TOOLS_ENABLED
  2043. HashMap<StringName, Variant>::ConstIterator E = exported_members_defval_cache.find(p_property);
  2044. if (E) {
  2045. r_value = E->value;
  2046. return true;
  2047. }
  2048. if (base_cache.is_valid()) {
  2049. return base_cache->get_property_default_value(p_property, r_value);
  2050. }
  2051. #endif
  2052. return false;
  2053. }
  2054. void CSharpScript::update_exports() {
  2055. #ifdef TOOLS_ENABLED
  2056. _update_exports();
  2057. #endif
  2058. }
  2059. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2060. if (!valid) {
  2061. return false;
  2062. }
  2063. if (!GDMonoCache::godot_api_cache_updated) {
  2064. return false;
  2065. }
  2066. String signal = p_signal;
  2067. return GDMonoCache::managed_callbacks.ScriptManagerBridge_HasScriptSignal(this, &signal);
  2068. }
  2069. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2070. if (!valid) {
  2071. return;
  2072. }
  2073. // Performance is not critical here as this will be replaced with source generators.
  2074. if (!GDMonoCache::godot_api_cache_updated) {
  2075. return;
  2076. }
  2077. Dictionary signals_dict;
  2078. // Destructor won't be called from C#, and I don't want to include the GDNative header
  2079. // only for this, so need to call the destructor manually before passing this to C#.
  2080. signals_dict.~Dictionary();
  2081. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptSignalList(this, &signals_dict);
  2082. for (const Variant *s = signals_dict.next(nullptr); s != nullptr; s = signals_dict.next(s)) {
  2083. MethodInfo mi;
  2084. mi.name = *s;
  2085. Array params = signals_dict[*s];
  2086. for (int i = 0; i < params.size(); i++) {
  2087. Dictionary param = params[i];
  2088. Variant::Type param_type = (Variant::Type)(int)param["type"];
  2089. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  2090. if (param_type == Variant::NIL && (bool)param["nil_is_variant"]) {
  2091. arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  2092. }
  2093. mi.arguments.push_back(arg_info);
  2094. }
  2095. r_signals->push_back(mi);
  2096. }
  2097. }
  2098. bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
  2099. Ref<CSharpScript> cs = p_script;
  2100. if (cs.is_null()) {
  2101. return false;
  2102. }
  2103. if (!valid || !cs->valid) {
  2104. return false;
  2105. }
  2106. if (!GDMonoCache::godot_api_cache_updated) {
  2107. return false;
  2108. }
  2109. return GDMonoCache::managed_callbacks.ScriptManagerBridge_ScriptIsOrInherits(this, cs.ptr());
  2110. }
  2111. Ref<Script> CSharpScript::get_base_script() const {
  2112. // TODO search in metadata file once we have it, not important any way?
  2113. return Ref<Script>();
  2114. }
  2115. void CSharpScript::get_script_property_list(List<PropertyInfo> *r_list) const {
  2116. List<PropertyInfo> props;
  2117. #ifdef TOOLS_ENABLED
  2118. for (const PropertyInfo &E : exported_members_cache) {
  2119. props.push_back(E);
  2120. }
  2121. #else
  2122. for (const KeyValue<StringName, PropertyInfo> &E : member_info) {
  2123. props.push_front(E.value);
  2124. }
  2125. #endif
  2126. for (const PropertyInfo &prop : props) {
  2127. r_list->push_back(prop);
  2128. }
  2129. }
  2130. int CSharpScript::get_member_line(const StringName &p_member) const {
  2131. // TODO omnisharp
  2132. return -1;
  2133. }
  2134. const Variant CSharpScript::get_rpc_config() const {
  2135. return rpc_config;
  2136. }
  2137. Error CSharpScript::load_source_code(const String &p_path) {
  2138. Error ferr = read_all_file_utf8(p_path, source);
  2139. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2140. ferr == ERR_INVALID_DATA
  2141. ? "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2142. " Please ensure that scripts are saved in valid UTF-8 unicode."
  2143. : "Failed to read file: '" + p_path + "'.");
  2144. #ifdef TOOLS_ENABLED
  2145. source_changed_cache = true;
  2146. #endif
  2147. return OK;
  2148. }
  2149. void CSharpScript::_clear() {
  2150. tool = false;
  2151. valid = false;
  2152. reload_invalidated = true;
  2153. }
  2154. CSharpScript::CSharpScript() {
  2155. _clear();
  2156. #ifdef DEBUG_ENABLED
  2157. {
  2158. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2159. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2160. }
  2161. #endif
  2162. }
  2163. CSharpScript::~CSharpScript() {
  2164. #ifdef DEBUG_ENABLED
  2165. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2166. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2167. #endif
  2168. if (GDMonoCache::godot_api_cache_updated) {
  2169. GDMonoCache::managed_callbacks.ScriptManagerBridge_RemoveScriptBridge(this);
  2170. }
  2171. }
  2172. void CSharpScript::get_members(HashSet<StringName> *p_members) {
  2173. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  2174. if (p_members) {
  2175. for (const StringName &member_name : exported_members_names) {
  2176. p_members->insert(member_name);
  2177. }
  2178. }
  2179. #endif
  2180. }
  2181. /*************** RESOURCE ***************/
  2182. Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  2183. if (r_error) {
  2184. *r_error = ERR_FILE_CANT_OPEN;
  2185. }
  2186. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2187. Ref<CSharpScript> script;
  2188. if (GDMonoCache::godot_api_cache_updated) {
  2189. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetOrCreateScriptBridgeForPath(&p_path, &script);
  2190. } else {
  2191. script = Ref<CSharpScript>(memnew(CSharpScript));
  2192. }
  2193. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2194. Error err = script->load_source_code(p_path);
  2195. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot load C# script file '" + p_path + "'.");
  2196. #endif
  2197. script->set_path(p_original_path);
  2198. script->reload();
  2199. if (r_error) {
  2200. *r_error = OK;
  2201. }
  2202. return script;
  2203. }
  2204. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2205. p_extensions->push_back("cs");
  2206. }
  2207. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2208. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2209. }
  2210. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2211. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2212. }
  2213. Error ResourceFormatSaverCSharpScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  2214. Ref<CSharpScript> sqscr = p_resource;
  2215. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2216. String source = sqscr->get_source_code();
  2217. #ifdef TOOLS_ENABLED
  2218. if (!FileAccess::exists(p_path)) {
  2219. // The file does not yet exist, let's assume the user just created this script. In such
  2220. // cases we need to check whether the solution and csproj were already created or not.
  2221. if (!_create_project_solution_if_needed()) {
  2222. ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
  2223. }
  2224. }
  2225. #endif
  2226. {
  2227. Error err;
  2228. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2229. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2230. file->store_string(source);
  2231. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2232. return ERR_CANT_CREATE;
  2233. }
  2234. }
  2235. #ifdef TOOLS_ENABLED
  2236. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2237. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2238. }
  2239. #endif
  2240. return OK;
  2241. }
  2242. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  2243. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2244. p_extensions->push_back("cs");
  2245. }
  2246. }
  2247. bool ResourceFormatSaverCSharpScript::recognize(const Ref<Resource> &p_resource) const {
  2248. return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
  2249. }
  2250. CSharpLanguage::StringNameCache::StringNameCache() {
  2251. _property_can_revert = StaticCString::create("_property_can_revert");
  2252. _property_get_revert = StaticCString::create("_property_get_revert");
  2253. _script_source = StaticCString::create("script/source");
  2254. on_before_serialize = StaticCString::create("OnBeforeSerialize");
  2255. on_after_deserialize = StaticCString::create("OnAfterDeserialize");
  2256. }