csharp_script.cpp 107 KB

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