csharp_script.cpp 83 KB

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