csharp_script.cpp 101 KB

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