csharp_script.cpp 98 KB

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