csharp_script.cpp 107 KB

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