csharp_script.cpp 109 KB

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