csharp_script.cpp 83 KB

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