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