csharp_script.cpp 109 KB

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