csharp_script.cpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978
  1. /**************************************************************************/
  2. /* csharp_script.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "csharp_script.h"
  31. #include "godotsharp_dirs.h"
  32. #include "managed_callable.h"
  33. #include "mono_gd/gd_mono_cache.h"
  34. #include "signal_awaiter_utils.h"
  35. #include "utils/macros.h"
  36. #include "utils/naming_utils.h"
  37. #include "utils/path_utils.h"
  38. #include "utils/string_utils.h"
  39. #ifdef DEBUG_ENABLED
  40. #include "class_db_api_json.h"
  41. #endif // DEBUG_ENABLED
  42. #ifdef TOOLS_ENABLED
  43. #include "editor/editor_internal_calls.h"
  44. #include "editor/script_templates/templates.gen.h"
  45. #endif
  46. #include "core/config/project_settings.h"
  47. #include "core/debugger/engine_debugger.h"
  48. #include "core/debugger/script_debugger.h"
  49. #include "core/io/file_access.h"
  50. #include "core/os/mutex.h"
  51. #include "core/os/os.h"
  52. #include "core/os/thread.h"
  53. #include "servers/text/text_server.h"
  54. #ifdef TOOLS_ENABLED
  55. #include "core/os/keyboard.h"
  56. #include "editor/docks/inspector_dock.h"
  57. #include "editor/docks/signals_dock.h"
  58. #include "editor/editor_node.h"
  59. #include "editor/file_system/editor_file_system.h"
  60. #include "editor/settings/editor_settings.h"
  61. #endif
  62. // Types that will be skipped over (in favor of their base types) when setting up instance bindings.
  63. // This must be a superset of `ignored_types` in bindings_generator.cpp.
  64. const Vector<String> ignored_types = {};
  65. #ifdef TOOLS_ENABLED
  66. static bool _create_project_solution_if_needed() {
  67. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
  68. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolutionIfNeeded");
  69. }
  70. #endif
  71. CSharpLanguage *CSharpLanguage::singleton = nullptr;
  72. GDExtensionInstanceBindingCallbacks CSharpLanguage::_instance_binding_callbacks = {
  73. &_instance_binding_create_callback,
  74. &_instance_binding_free_callback,
  75. &_instance_binding_reference_callback
  76. };
  77. String CSharpLanguage::get_name() const {
  78. return "C#";
  79. }
  80. String CSharpLanguage::get_type() const {
  81. return "CSharpScript";
  82. }
  83. String CSharpLanguage::get_extension() const {
  84. return "cs";
  85. }
  86. void CSharpLanguage::init() {
  87. #ifdef TOOLS_ENABLED
  88. if (OS::get_singleton()->get_cmdline_args().find("--generate-mono-glue")) {
  89. print_verbose(".NET: Skipping runtime initialization because glue generation is enabled.");
  90. return;
  91. }
  92. #endif
  93. #ifdef DEBUG_ENABLED
  94. if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
  95. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  96. #ifdef TOOLS_ENABLED
  97. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  98. #endif
  99. }
  100. #endif // DEBUG_ENABLED
  101. GLOBAL_DEF("dotnet/project/assembly_name", "");
  102. #ifdef TOOLS_ENABLED
  103. GLOBAL_DEF("dotnet/project/solution_directory", "");
  104. GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
  105. #endif
  106. #ifdef TOOLS_ENABLED
  107. EditorNode::add_init_callback(&_editor_init_callback);
  108. #endif
  109. gdmono = memnew(GDMono);
  110. // Initialize only if the project uses C#.
  111. if (gdmono->should_initialize()) {
  112. gdmono->initialize();
  113. }
  114. }
  115. void CSharpLanguage::finish() {
  116. finalize();
  117. }
  118. void CSharpLanguage::finalize() {
  119. if (finalized) {
  120. return;
  121. }
  122. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  123. GDMonoCache::managed_callbacks.DisposablesTracker_OnGodotShuttingDown();
  124. }
  125. finalizing = true;
  126. // Make sure all script binding gchandles are released before finalizing GDMono.
  127. for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  128. CSharpScriptBinding &script_binding = E.value;
  129. if (!script_binding.gchandle.is_released()) {
  130. script_binding.gchandle.release();
  131. script_binding.inited = false;
  132. }
  133. // Make sure we clear all the instance binding callbacks so they don't get called
  134. // after finalizing the C# language.
  135. script_binding.owner->free_instance_binding(this);
  136. }
  137. if (gdmono) {
  138. memdelete(gdmono);
  139. gdmono = nullptr;
  140. }
  141. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  142. script_bindings.clear();
  143. #ifdef DEBUG_ENABLED
  144. for (const KeyValue<ObjectID, int> &E : unsafe_object_references) {
  145. const ObjectID &id = E.key;
  146. Object *obj = ObjectDB::get_instance(id);
  147. if (obj) {
  148. ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
  149. } else {
  150. ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
  151. }
  152. }
  153. #endif // DEBUG_ENABLED
  154. memdelete(managed_callable_middleman);
  155. finalizing = false;
  156. finalized = true;
  157. }
  158. Vector<String> CSharpLanguage::get_reserved_words() const {
  159. static const Vector<String> ret = {
  160. // Reserved keywords
  161. "abstract",
  162. "as",
  163. "base",
  164. "bool",
  165. "break",
  166. "byte",
  167. "case",
  168. "catch",
  169. "char",
  170. "checked",
  171. "class",
  172. "const",
  173. "continue",
  174. "decimal",
  175. "default",
  176. "delegate",
  177. "do",
  178. "double",
  179. "else",
  180. "enum",
  181. "event",
  182. "explicit",
  183. "extern",
  184. "false",
  185. "finally",
  186. "fixed",
  187. "float",
  188. "for",
  189. "foreach",
  190. "goto",
  191. "if",
  192. "implicit",
  193. "in",
  194. "int",
  195. "interface",
  196. "internal",
  197. "is",
  198. "lock",
  199. "long",
  200. "namespace",
  201. "new",
  202. "null",
  203. "object",
  204. "operator",
  205. "out",
  206. "override",
  207. "params",
  208. "private",
  209. "protected",
  210. "public",
  211. "readonly",
  212. "ref",
  213. "return",
  214. "sbyte",
  215. "sealed",
  216. "short",
  217. "sizeof",
  218. "stackalloc",
  219. "static",
  220. "string",
  221. "struct",
  222. "switch",
  223. "this",
  224. "throw",
  225. "true",
  226. "try",
  227. "typeof",
  228. "uint",
  229. "ulong",
  230. "unchecked",
  231. "unsafe",
  232. "ushort",
  233. "using",
  234. "virtual",
  235. "void",
  236. "volatile",
  237. "while",
  238. // Contextual keywords. Not reserved words, but I guess we should include
  239. // them because this seems to be used only for syntax highlighting.
  240. "add",
  241. "alias",
  242. "ascending",
  243. "async",
  244. "await",
  245. "by",
  246. "descending",
  247. "dynamic",
  248. "equals",
  249. "from",
  250. "get",
  251. "global",
  252. "group",
  253. "into",
  254. "join",
  255. "let",
  256. "nameof",
  257. "on",
  258. "orderby",
  259. "partial",
  260. "remove",
  261. "select",
  262. "set",
  263. "value",
  264. "var",
  265. "when",
  266. "where",
  267. "yield",
  268. };
  269. return ret;
  270. }
  271. bool CSharpLanguage::is_control_flow_keyword(const String &p_keyword) const {
  272. return p_keyword == "break" ||
  273. p_keyword == "case" ||
  274. p_keyword == "catch" ||
  275. p_keyword == "continue" ||
  276. p_keyword == "default" ||
  277. p_keyword == "do" ||
  278. p_keyword == "else" ||
  279. p_keyword == "finally" ||
  280. p_keyword == "for" ||
  281. p_keyword == "foreach" ||
  282. p_keyword == "goto" ||
  283. p_keyword == "if" ||
  284. p_keyword == "return" ||
  285. p_keyword == "switch" ||
  286. p_keyword == "throw" ||
  287. p_keyword == "try" ||
  288. p_keyword == "while";
  289. }
  290. Vector<String> CSharpLanguage::get_comment_delimiters() const {
  291. static const Vector<String> delimiters = {
  292. "//", // single-line comment
  293. "/* */" // delimited comment
  294. };
  295. return delimiters;
  296. }
  297. Vector<String> CSharpLanguage::get_doc_comment_delimiters() const {
  298. static const Vector<String> delimiters = {
  299. "///", // single-line doc comment
  300. "/** */" // delimited doc comment
  301. };
  302. return delimiters;
  303. }
  304. Vector<String> CSharpLanguage::get_string_delimiters() const {
  305. static const Vector<String> delimiters = {
  306. "' '", // character literal
  307. "\" \"", // regular string literal
  308. "@\" \"" // verbatim string literal
  309. };
  310. // Generic string highlighting suffices as a workaround for now.
  311. return delimiters;
  312. }
  313. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  314. String base_class = pascal_to_pascal_case(p_base_class_name);
  315. if (p_class_name == base_class) {
  316. base_class = "Godot." + base_class;
  317. }
  318. return base_class;
  319. }
  320. bool CSharpLanguage::is_using_templates() {
  321. return true;
  322. }
  323. Ref<Script> CSharpLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
  324. Ref<CSharpScript> scr;
  325. scr.instantiate();
  326. String class_name_no_spaces = p_class_name.replace_char(' ', '_');
  327. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  328. String processed_template = p_template;
  329. processed_template = processed_template.replace("_BINDINGS_NAMESPACE_", BINDINGS_NAMESPACE)
  330. .replace("_BASE_", base_class_name)
  331. .replace("_CLASS_", class_name_no_spaces)
  332. .replace("_TS_", _get_indentation());
  333. scr->set_source_code(processed_template);
  334. return scr;
  335. }
  336. Vector<ScriptLanguage::ScriptTemplate> CSharpLanguage::get_built_in_templates(const StringName &p_object) {
  337. Vector<ScriptLanguage::ScriptTemplate> templates;
  338. #ifdef TOOLS_ENABLED
  339. for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
  340. if (TEMPLATES[i].inherit == p_object) {
  341. templates.append(TEMPLATES[i]);
  342. }
  343. }
  344. #endif
  345. return templates;
  346. }
  347. String CSharpLanguage::validate_path(const String &p_path) const {
  348. String class_name = p_path.get_file().get_basename();
  349. if (get_reserved_words().has(class_name)) {
  350. return RTR("Class name can't be a reserved keyword");
  351. }
  352. if (!TS->is_valid_identifier(class_name)) {
  353. return RTR("Class name must be a valid identifier");
  354. }
  355. return "";
  356. }
  357. Script *CSharpLanguage::create_script() const {
  358. return memnew(CSharpScript);
  359. }
  360. bool CSharpLanguage::supports_builtin_mode() const {
  361. return false;
  362. }
  363. ScriptLanguage::ScriptNameCasing CSharpLanguage::preferred_file_name_casing() const {
  364. return SCRIPT_NAME_CASING_PASCAL_CASE;
  365. }
  366. #ifdef TOOLS_ENABLED
  367. String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
  368. // The make_function() API does not work for C# scripts.
  369. // It will always append the generated function at the very end of the script. In C#, it will break compilation by
  370. // appending code after the final closing bracket (either the class' or the namespace's).
  371. // To prevent issues, we have can_make_function() returning false, and make_function() is never implemented.
  372. return String();
  373. }
  374. #else
  375. String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
  376. return String();
  377. }
  378. #endif
  379. String CSharpLanguage::_get_indentation() const {
  380. #ifdef TOOLS_ENABLED
  381. if (Engine::get_singleton()->is_editor_hint()) {
  382. bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
  383. if (use_space_indentation) {
  384. int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
  385. return String(" ").repeat(indent_size);
  386. }
  387. }
  388. #endif
  389. return "\t";
  390. }
  391. bool CSharpLanguage::handles_global_class_type(const String &p_type) const {
  392. return p_type == get_type();
  393. }
  394. String CSharpLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path, bool *r_is_abstract, bool *r_is_tool) const {
  395. String class_name;
  396. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetGlobalClassName(&p_path, r_base_type, r_icon_path, r_is_abstract, r_is_tool, &class_name);
  397. return class_name;
  398. }
  399. String CSharpLanguage::debug_get_error() const {
  400. return _debug_error;
  401. }
  402. int CSharpLanguage::debug_get_stack_level_count() const {
  403. if (_debug_parse_err_line >= 0) {
  404. return 1;
  405. }
  406. // TODO: StackTrace
  407. return 1;
  408. }
  409. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  410. if (_debug_parse_err_line >= 0) {
  411. return _debug_parse_err_line;
  412. }
  413. // TODO: StackTrace
  414. return 1;
  415. }
  416. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  417. if (_debug_parse_err_line >= 0) {
  418. return String();
  419. }
  420. // TODO: StackTrace
  421. return String();
  422. }
  423. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  424. if (_debug_parse_err_line >= 0) {
  425. return _debug_parse_err_file;
  426. }
  427. // TODO: StackTrace
  428. return String();
  429. }
  430. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  431. // Printing an error here will result in endless recursion, so we must be careful
  432. static thread_local bool _recursion_flag_ = false;
  433. if (_recursion_flag_) {
  434. return Vector<StackInfo>();
  435. }
  436. _recursion_flag_ = true;
  437. SCOPE_EXIT {
  438. _recursion_flag_ = false; // clang-format off
  439. }; // clang-format on
  440. if (!gdmono || !gdmono->is_runtime_initialized()) {
  441. return Vector<StackInfo>();
  442. }
  443. Vector<StackInfo> si;
  444. if (GDMonoCache::godot_api_cache_updated) {
  445. GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
  446. }
  447. return si;
  448. }
  449. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  450. #ifdef DEBUG_ENABLED
  451. MutexLock lock(unsafe_object_references_lock);
  452. ObjectID id = p_obj->get_instance_id();
  453. unsafe_object_references[id]++;
  454. #endif // DEBUG_ENABLED
  455. }
  456. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  457. #ifdef DEBUG_ENABLED
  458. MutexLock lock(unsafe_object_references_lock);
  459. ObjectID id = p_obj->get_instance_id();
  460. HashMap<ObjectID, int>::Iterator elem = unsafe_object_references.find(id);
  461. ERR_FAIL_NULL(elem);
  462. if (--elem->value == 0) {
  463. unsafe_object_references.remove(elem);
  464. }
  465. #endif // DEBUG_ENABLED
  466. }
  467. void CSharpLanguage::frame() {
  468. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  469. GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
  470. }
  471. #ifdef TOOLS_ENABLED
  472. _flush_filesystem_updates();
  473. #endif
  474. }
  475. struct CSharpScriptDepSort {
  476. // Must support sorting so inheritance works properly (parent must be reloaded first)
  477. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  478. if (A == B) {
  479. // Shouldn't happen but just in case...
  480. return false;
  481. }
  482. const Script *I = B->get_base_script().ptr();
  483. while (I) {
  484. if (I == A.ptr()) {
  485. // A is a base of B
  486. return true;
  487. }
  488. I = I->get_base_script().ptr();
  489. }
  490. // A isn't a base of B
  491. return false;
  492. }
  493. };
  494. void CSharpLanguage::reload_all_scripts() {
  495. #ifdef GD_MONO_HOT_RELOAD
  496. if (is_assembly_reloading_needed()) {
  497. reload_assemblies(false);
  498. }
  499. #endif
  500. }
  501. void CSharpLanguage::reload_scripts(const Array &p_scripts, bool p_soft_reload) {
  502. #ifdef GD_MONO_HOT_RELOAD
  503. if (is_assembly_reloading_needed()) {
  504. reload_assemblies(p_soft_reload);
  505. }
  506. #endif
  507. }
  508. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  509. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  510. #ifdef TOOLS_ENABLED
  511. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  512. #endif
  513. #ifdef GD_MONO_HOT_RELOAD
  514. if (is_assembly_reloading_needed()) {
  515. reload_assemblies(p_soft_reload);
  516. }
  517. #endif
  518. }
  519. #ifdef GD_MONO_HOT_RELOAD
  520. bool CSharpLanguage::is_assembly_reloading_needed() {
  521. ERR_FAIL_NULL_V(gdmono, false);
  522. if (!gdmono->is_runtime_initialized()) {
  523. return false;
  524. }
  525. String assembly_path = gdmono->get_project_assembly_path();
  526. if (!assembly_path.is_empty()) {
  527. if (!FileAccess::exists(assembly_path)) {
  528. return false; // No assembly to load
  529. }
  530. if (FileAccess::get_modified_time(assembly_path) <= gdmono->get_project_assembly_modified_time()) {
  531. return false; // Already up to date
  532. }
  533. } else {
  534. String assembly_name = Path::get_csharp_project_name();
  535. assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
  536. .path_join(assembly_name + ".dll");
  537. assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
  538. if (!FileAccess::exists(assembly_path)) {
  539. return false; // No assembly to load
  540. }
  541. }
  542. return true;
  543. }
  544. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  545. ERR_FAIL_NULL(gdmono);
  546. if (!gdmono->is_runtime_initialized()) {
  547. return;
  548. }
  549. if (!Engine::get_singleton()->is_editor_hint()) {
  550. // We disable collectible assemblies in the game player, because the limitations cause
  551. // issues with mocking libraries. As such, we can only reload assemblies in the editor.
  552. return;
  553. }
  554. print_verbose(".NET: Reloading assemblies...");
  555. // There is no soft reloading with Mono. It's always hard reloading.
  556. List<Ref<CSharpScript>> scripts;
  557. {
  558. MutexLock lock(script_instances_mutex);
  559. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  560. // Do not reload scripts with only non-collectible instances to avoid disrupting event subscriptions and such.
  561. bool is_reloadable = elem->self()->instances.is_empty();
  562. for (Object *obj : elem->self()->instances) {
  563. ERR_CONTINUE(!obj->get_script_instance());
  564. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  565. if (GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(csi->get_gchandle_intptr())) {
  566. is_reloadable = true;
  567. break;
  568. }
  569. }
  570. if (is_reloadable) {
  571. // Cast to CSharpScript to avoid being erased by accident.
  572. scripts.push_back(Ref<CSharpScript>(elem->self()));
  573. }
  574. }
  575. }
  576. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  577. // Serialize managed callables
  578. {
  579. MutexLock lock(ManagedCallable::instances_mutex);
  580. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  581. ManagedCallable *managed_callable = elem->self();
  582. ERR_CONTINUE(managed_callable->delegate_handle.value == nullptr);
  583. if (!GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(managed_callable->delegate_handle)) {
  584. continue;
  585. }
  586. Array serialized_data;
  587. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TrySerializeDelegateWithGCHandle(
  588. managed_callable->delegate_handle, &serialized_data);
  589. if (success) {
  590. ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
  591. } else {
  592. if (OS::get_singleton()->is_stdout_verbose()) {
  593. OS::get_singleton()->print("Failed to serialize delegate.\n");
  594. }
  595. // We failed to serialize the delegate but we still have to release it;
  596. // otherwise, we won't be able to unload the assembly.
  597. managed_callable->release_delegate_handle();
  598. }
  599. }
  600. }
  601. List<Ref<CSharpScript>> to_reload;
  602. // We need to keep reference instances alive during reloading
  603. List<Ref<RefCounted>> rc_instances;
  604. for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  605. const CSharpScriptBinding &script_binding = E.value;
  606. RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner);
  607. if (rc) {
  608. rc_instances.push_back(Ref<RefCounted>(rc));
  609. }
  610. }
  611. // As scripts are going to be reloaded, must proceed without locking here
  612. for (Ref<CSharpScript> &scr : scripts) {
  613. // If someone removes a script from a node, deletes the script, builds, adds a script to the
  614. // same node, then builds again, the script might have no path and also no script_class. In
  615. // that case, we can't (and don't need to) reload it.
  616. if (scr->get_path().is_empty() && !scr->valid) {
  617. continue;
  618. }
  619. to_reload.push_back(scr);
  620. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  621. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  622. for (Object *obj : scr->instances) {
  623. scr->pending_reload_instances.insert(obj->get_instance_id());
  624. // Since this script instance wasn't a placeholder, add it to the list of placeholders
  625. // that will have to be eventually replaced with a script instance in case it turns into one.
  626. // This list is not cleared after the reload and the collected instances only leave
  627. // the list if the script is instantiated or if it was a tool script but becomes a
  628. // non-tool script in a rebuild.
  629. scr->pending_replace_placeholders.insert(obj->get_instance_id());
  630. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  631. if (rc) {
  632. rc_instances.push_back(Ref<RefCounted>(rc));
  633. }
  634. }
  635. #ifdef TOOLS_ENABLED
  636. for (PlaceHolderScriptInstance *instance : scr->placeholders) {
  637. Object *obj = instance->get_owner();
  638. scr->pending_reload_instances.insert(obj->get_instance_id());
  639. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  640. if (rc) {
  641. rc_instances.push_back(Ref<RefCounted>(rc));
  642. }
  643. }
  644. #endif
  645. // Save state and remove script from instances
  646. RBMap<ObjectID, CSharpScript::StateBackup> &owners_map = scr->pending_reload_state;
  647. for (Object *obj : scr->instances) {
  648. ERR_CONTINUE(!obj->get_script_instance());
  649. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  650. // Call OnBeforeSerialize and save instance info
  651. CSharpScript::StateBackup state;
  652. Dictionary properties;
  653. GDMonoCache::managed_callbacks.CSharpInstanceBridge_SerializeState(
  654. csi->get_gchandle_intptr(), &properties, &state.event_signals);
  655. for (const Variant *s = properties.next(nullptr); s != nullptr; s = properties.next(s)) {
  656. StringName name = *s;
  657. Variant value = properties[*s];
  658. state.properties.push_back(Pair<StringName, Variant>(name, value));
  659. }
  660. owners_map[obj->get_instance_id()] = state;
  661. }
  662. }
  663. // After the state of all instances is saved, clear scripts and script instances
  664. for (Ref<CSharpScript> &scr : scripts) {
  665. while (scr->instances.begin()) {
  666. Object *obj = *scr->instances.begin();
  667. obj->set_script(Ref<RefCounted>()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  668. }
  669. scr->was_tool_before_reload = scr->type_info.is_tool;
  670. scr->_clear();
  671. }
  672. // Release the delegates that were serialized earlier.
  673. {
  674. MutexLock lock(ManagedCallable::instances_mutex);
  675. for (KeyValue<ManagedCallable *, Array> &kv : ManagedCallable::instances_pending_reload) {
  676. kv.key->release_delegate_handle();
  677. }
  678. }
  679. // Do domain reload
  680. if (gdmono->reload_project_assemblies() != OK) {
  681. // Failed to reload the scripts domain
  682. // Make sure to add the scripts back to their owners before returning
  683. for (Ref<CSharpScript> &scr : to_reload) {
  684. for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) {
  685. Object *obj = ObjectDB::get_instance(F.key);
  686. if (!obj) {
  687. continue;
  688. }
  689. ObjectID obj_id = obj->get_instance_id();
  690. // Use a placeholder for now to avoid losing the state when saving a scene
  691. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  692. obj->set_script_instance(placeholder);
  693. #ifdef TOOLS_ENABLED
  694. // Even though build didn't fail, this tells the placeholder to keep properties and
  695. // it allows using property_set_fallback for restoring the state without a valid script.
  696. scr->placeholder_fallback_enabled = true;
  697. #endif
  698. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  699. for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) {
  700. placeholder->property_set_fallback(G.first, G.second, nullptr);
  701. }
  702. scr->pending_reload_state.erase(obj_id);
  703. }
  704. scr->pending_reload_instances.clear();
  705. scr->pending_reload_state.clear();
  706. }
  707. return;
  708. }
  709. // Add all script types to script bridge before reloading exports,
  710. // so typed collections can be reconstructed correctly regardless of script load order.
  711. for (Ref<CSharpScript> &scr : to_reload) {
  712. if (!scr->get_path().is_empty() && !scr->get_path().begins_with("csharp://")) {
  713. String script_path = scr->get_path();
  714. bool valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(scr.ptr(), &script_path);
  715. if (valid) {
  716. scr->valid = true;
  717. CSharpScript::update_script_class_info(scr);
  718. // Ensure that the next call to CSharpScript::reload will refresh the exports
  719. scr->reload_invalidated = true;
  720. }
  721. }
  722. }
  723. List<Ref<CSharpScript>> to_reload_state;
  724. for (Ref<CSharpScript> &scr : to_reload) {
  725. #ifdef TOOLS_ENABLED
  726. scr->exports_invalidated = true;
  727. #endif
  728. if (!scr->get_path().is_empty() && !scr->get_path().begins_with("csharp://")) {
  729. scr->reload(p_soft_reload);
  730. if (!scr->valid) {
  731. scr->pending_reload_instances.clear();
  732. scr->pending_reload_state.clear();
  733. continue;
  734. }
  735. } else {
  736. bool success = GDMonoCache::managed_callbacks.ScriptManagerBridge_TryReloadRegisteredScriptWithClass(scr.ptr());
  737. if (!success) {
  738. // Couldn't reload
  739. scr->pending_reload_instances.clear();
  740. scr->pending_reload_state.clear();
  741. continue;
  742. }
  743. }
  744. StringName native_name = scr->get_instance_base_type();
  745. {
  746. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  747. Object *obj = ObjectDB::get_instance(obj_id);
  748. if (!obj) {
  749. scr->pending_reload_state.erase(obj_id);
  750. continue;
  751. }
  752. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  753. // No longer inherits the same compatible type, can't reload
  754. scr->pending_reload_state.erase(obj_id);
  755. continue;
  756. }
  757. ScriptInstance *si = obj->get_script_instance();
  758. // Check if the script must be instantiated or kept as a placeholder
  759. // when the script may not be a tool (see #65266)
  760. bool replace_placeholder = scr->pending_replace_placeholders.has(obj->get_instance_id());
  761. if (!scr->is_tool() && scr->was_tool_before_reload) {
  762. // The script was a tool before the rebuild so the removal was intentional.
  763. replace_placeholder = false;
  764. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  765. }
  766. #ifdef TOOLS_ENABLED
  767. if (si) {
  768. // If the script instance is not null, then it must be a placeholder.
  769. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  770. CRASH_COND(!si->is_placeholder());
  771. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  772. // Replace placeholder with a script instance.
  773. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  774. // Backup placeholder script instance state before replacing it with a script instance.
  775. si->get_property_state(state_backup.properties);
  776. ScriptInstance *instance = scr->instance_create(obj);
  777. if (instance) {
  778. scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  779. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  780. obj->set_script_instance(instance);
  781. }
  782. }
  783. continue;
  784. }
  785. #else
  786. CRASH_COND(si != nullptr);
  787. #endif
  788. // Re-create the script instance.
  789. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  790. // Create script instance or replace placeholder with a script instance.
  791. ScriptInstance *instance = scr->instance_create(obj);
  792. if (instance) {
  793. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  794. obj->set_script_instance(instance);
  795. continue;
  796. }
  797. }
  798. // The script instance could not be instantiated or wasn't in the list of placeholders to replace.
  799. obj->set_script(scr);
  800. #ifdef DEBUG_ENABLED
  801. // If we reached here, the instantiated script must be a placeholder.
  802. CRASH_COND(!obj->get_script_instance()->is_placeholder());
  803. #endif // DEBUG_ENABLED
  804. }
  805. }
  806. to_reload_state.push_back(scr);
  807. }
  808. // Deserialize managed callables.
  809. // This is done before reloading script's internal state, so potential callables invoked in properties work.
  810. {
  811. MutexLock lock(ManagedCallable::instances_mutex);
  812. for (const KeyValue<ManagedCallable *, Array> &elem : ManagedCallable::instances_pending_reload) {
  813. ManagedCallable *managed_callable = elem.key;
  814. const Array &serialized_data = elem.value;
  815. GCHandleIntPtr delegate = { nullptr };
  816. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TryDeserializeDelegateWithGCHandle(
  817. &serialized_data, &delegate);
  818. if (success) {
  819. ERR_CONTINUE(delegate.value == nullptr);
  820. managed_callable->delegate_handle = delegate;
  821. } else if (OS::get_singleton()->is_stdout_verbose()) {
  822. OS::get_singleton()->print("Failed to deserialize delegate\n");
  823. }
  824. }
  825. ManagedCallable::instances_pending_reload.clear();
  826. }
  827. for (Ref<CSharpScript> &scr : to_reload_state) {
  828. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  829. Object *obj = ObjectDB::get_instance(obj_id);
  830. if (!obj) {
  831. scr->pending_reload_state.erase(obj_id);
  832. continue;
  833. }
  834. ERR_CONTINUE(!obj->get_script_instance());
  835. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  836. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  837. if (csi) {
  838. Dictionary properties;
  839. for (const Pair<StringName, Variant> &G : state_backup.properties) {
  840. properties[G.first] = G.second;
  841. }
  842. // Restore serialized state and call OnAfterDeserialize.
  843. GDMonoCache::managed_callbacks.CSharpInstanceBridge_DeserializeState(
  844. csi->get_gchandle_intptr(), &properties, &state_backup.event_signals);
  845. }
  846. }
  847. scr->pending_reload_instances.clear();
  848. scr->pending_reload_state.clear();
  849. }
  850. #ifdef TOOLS_ENABLED
  851. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  852. if (Engine::get_singleton()->is_editor_hint()) {
  853. InspectorDock::get_inspector_singleton()->update_tree();
  854. SignalsDock::get_singleton()->update_lists();
  855. }
  856. #endif
  857. }
  858. #endif
  859. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  860. p_extensions->push_back("cs");
  861. }
  862. #ifdef TOOLS_ENABLED
  863. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  864. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  865. }
  866. bool CSharpLanguage::overrides_external_editor() {
  867. return get_godotsharp_editor()->call("OverridesExternalEditor");
  868. }
  869. #endif
  870. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  871. // Not a parser error in our case, but it's still used for other type of errors
  872. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  873. _debug_parse_err_line = p_line;
  874. _debug_parse_err_file = p_file;
  875. _debug_error = p_error;
  876. EngineDebugger::get_script_debugger()->debug(this, false, true);
  877. return true;
  878. } else {
  879. return false;
  880. }
  881. }
  882. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  883. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  884. _debug_parse_err_line = -1;
  885. _debug_parse_err_file = "";
  886. _debug_error = p_error;
  887. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue);
  888. return true;
  889. } else {
  890. return false;
  891. }
  892. }
  893. #ifdef TOOLS_ENABLED
  894. void CSharpLanguage::_queue_for_filesystem_update(String p_script_path) {
  895. if (!Engine::get_singleton()->is_editor_hint()) {
  896. return;
  897. }
  898. if (p_script_path.is_empty()) {
  899. return;
  900. }
  901. pending_file_system_update_paths.push_back(p_script_path);
  902. }
  903. void CSharpLanguage::_flush_filesystem_updates() {
  904. if (!Engine::get_singleton()->is_editor_hint()) {
  905. return;
  906. }
  907. if (pending_file_system_update_paths.is_empty()) {
  908. return;
  909. }
  910. // If the EditorFileSystem singleton is available, update the files;
  911. // otherwise, the files will be updated when the singleton becomes available.
  912. EditorFileSystem *efs = EditorFileSystem::get_singleton();
  913. if (!efs) {
  914. pending_file_system_update_paths.clear();
  915. return;
  916. }
  917. // Required to prevent EditorProgress within EditorFileSystem from calling this while it is already flushing
  918. if (is_flushing_filesystem_updates) {
  919. return;
  920. }
  921. is_flushing_filesystem_updates = true;
  922. efs->update_files(pending_file_system_update_paths);
  923. is_flushing_filesystem_updates = false;
  924. pending_file_system_update_paths.clear();
  925. }
  926. void CSharpLanguage::_editor_init_callback() {
  927. // Load GodotTools and initialize GodotSharpEditor
  928. int32_t interop_funcs_size = 0;
  929. const void **interop_funcs = godotsharp::get_editor_interop_funcs(interop_funcs_size);
  930. Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
  931. GodotSharpDirs::get_data_editor_tools_dir().path_join("GodotTools.dll").utf16().get_data(),
  932. interop_funcs, interop_funcs_size);
  933. CRASH_COND(editor_plugin_obj == nullptr);
  934. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);
  935. CRASH_COND(godotsharp_editor == nullptr);
  936. // Add plugin to EditorNode and enable it
  937. EditorNode::add_editor_plugin(godotsharp_editor);
  938. godotsharp_editor->enable_plugin();
  939. get_singleton()->godotsharp_editor = godotsharp_editor;
  940. }
  941. #endif
  942. void CSharpLanguage::set_language_index(int p_idx) {
  943. ERR_FAIL_COND(lang_idx != -1);
  944. lang_idx = p_idx;
  945. }
  946. void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
  947. if (!p_gchandle.is_released()) { // Do not lock unnecessarily
  948. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  949. p_gchandle.release();
  950. }
  951. }
  952. void CSharpLanguage::release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle) {
  953. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  954. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  955. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) {
  956. r_gchandle.release();
  957. }
  958. }
  959. }
  960. void CSharpLanguage::release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding) {
  961. MonoGCHandleData &gchandle = r_script_binding.gchandle;
  962. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  963. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  964. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) {
  965. gchandle.release();
  966. r_script_binding.inited = false; // Here too, to be thread safe
  967. }
  968. }
  969. }
  970. CSharpLanguage::CSharpLanguage() {
  971. ERR_FAIL_COND_MSG(singleton, "C# singleton already exists.");
  972. singleton = this;
  973. }
  974. CSharpLanguage::~CSharpLanguage() {
  975. finalize();
  976. singleton = nullptr;
  977. }
  978. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  979. #ifdef DEBUG_ENABLED
  980. // I don't trust you
  981. if (p_object->get_script_instance()) {
  982. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  983. CRASH_COND(csharp_instance != nullptr && !csharp_instance->is_destructing_script_instance());
  984. }
  985. #endif // DEBUG_ENABLED
  986. StringName type_name = p_object->get_class_name();
  987. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  988. // This skipping of GDExtension classes, as well as whatever classes are in this list of ignored types, is a
  989. // workaround to allow GDExtension classes to be used from C# so long as they're only used through base classes that
  990. // are registered from the engine. This will likely need to be removed whenever proper support for GDExtension
  991. // classes is added to C#. See #75955 for more details.
  992. while (classinfo && (!classinfo->exposed || classinfo->gdextension || ignored_types.has(classinfo->name))) {
  993. classinfo = classinfo->inherits_ptr;
  994. }
  995. ERR_FAIL_NULL_V(classinfo, false);
  996. type_name = classinfo->name;
  997. bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), type_name);
  998. ERR_FAIL_COND_V_MSG(!parent_is_object_class, false,
  999. "Type inherits from native type '" + type_name + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
  1000. #ifdef DEBUG_ENABLED
  1001. CRASH_COND(!r_script_binding.gchandle.is_released());
  1002. #endif // DEBUG_ENABLED
  1003. GCHandleIntPtr strong_gchandle =
  1004. GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(
  1005. &type_name, p_object);
  1006. ERR_FAIL_NULL_V(strong_gchandle.value, false);
  1007. r_script_binding.inited = true;
  1008. r_script_binding.type_name = type_name;
  1009. r_script_binding.gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1010. r_script_binding.owner = p_object;
  1011. // Tie managed to unmanaged
  1012. RefCounted *rc = Object::cast_to<RefCounted>(p_object);
  1013. if (rc) {
  1014. // Unsafe refcount increment. The managed instance also counts as a reference.
  1015. // This way if the unmanaged world has no references to our owner
  1016. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1017. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1018. rc->reference();
  1019. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1020. }
  1021. return true;
  1022. }
  1023. RBMap<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  1024. return script_bindings.insert(p_object, p_script_binding);
  1025. }
  1026. void *CSharpLanguage::_instance_binding_create_callback(void *, void *p_instance) {
  1027. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1028. MutexLock lock(csharp_lang->language_bind_mutex);
  1029. RBMap<Object *, CSharpScriptBinding>::Element *match = csharp_lang->script_bindings.find((Object *)p_instance);
  1030. if (match) {
  1031. return (void *)match;
  1032. }
  1033. CSharpScriptBinding script_binding;
  1034. return (void *)csharp_lang->insert_script_binding((Object *)p_instance, script_binding);
  1035. }
  1036. void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_binding) {
  1037. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1038. if (GDMono::get_singleton() == nullptr) {
  1039. #ifdef DEBUG_ENABLED
  1040. CRASH_COND(csharp_lang && !csharp_lang->script_bindings.is_empty());
  1041. #endif // DEBUG_ENABLED
  1042. // Mono runtime finalized, all the gchandle bindings were already released
  1043. return;
  1044. }
  1045. if (csharp_lang->finalizing) {
  1046. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1047. }
  1048. {
  1049. MutexLock lock(csharp_lang->language_bind_mutex);
  1050. RBMap<Object *, CSharpScriptBinding>::Element *data = (RBMap<Object *, CSharpScriptBinding>::Element *)p_binding;
  1051. CSharpScriptBinding &script_binding = data->value();
  1052. if (script_binding.inited) {
  1053. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1054. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1055. GDMonoCache::managed_callbacks.ScriptManagerBridge_SetGodotObjectPtr(
  1056. script_binding.gchandle.get_intptr(), nullptr);
  1057. script_binding.gchandle.release();
  1058. script_binding.inited = false;
  1059. }
  1060. csharp_lang->script_bindings.erase(data);
  1061. }
  1062. }
  1063. GDExtensionBool CSharpLanguage::_instance_binding_reference_callback(void *p_token, void *p_binding, GDExtensionBool p_reference) {
  1064. // Instance bindings callbacks can only be called if the C# language is available.
  1065. // Failing this assert usually means that we didn't clear the instance binding in some Object
  1066. // and the C# language has already been finalized.
  1067. DEV_ASSERT(CSharpLanguage::get_singleton() != nullptr);
  1068. CRASH_COND(!p_binding);
  1069. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)p_binding)->get();
  1070. RefCounted *rc_owner = Object::cast_to<RefCounted>(script_binding.owner);
  1071. #ifdef DEBUG_ENABLED
  1072. CRASH_COND(!rc_owner);
  1073. #endif // DEBUG_ENABLED
  1074. MonoGCHandleData &gchandle = script_binding.gchandle;
  1075. int refcount = rc_owner->get_reference_count();
  1076. if (!script_binding.inited) {
  1077. return refcount == 0;
  1078. }
  1079. if (p_reference) {
  1080. // Refcount incremented
  1081. if (refcount > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1082. // The reference count was increased after the managed side was the only one referencing our owner.
  1083. // This means the owner is being referenced again by the unmanaged side,
  1084. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1085. // Release the current weak handle and replace it with a strong handle.
  1086. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1087. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1088. GCHandleIntPtr new_gchandle = { nullptr };
  1089. bool create_weak = false;
  1090. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1091. old_gchandle, &new_gchandle, create_weak);
  1092. if (!target_alive) {
  1093. return false; // Called after the managed side was collected, so nothing to do here
  1094. }
  1095. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1096. }
  1097. return false;
  1098. } else {
  1099. // Refcount decremented
  1100. if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1101. // If owner owner is no longer referenced by the unmanaged side,
  1102. // the managed instance takes responsibility of deleting the owner when GCed.
  1103. // Release the current strong handle and replace it with a weak handle.
  1104. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1105. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1106. GCHandleIntPtr new_gchandle = { nullptr };
  1107. bool create_weak = true;
  1108. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1109. old_gchandle, &new_gchandle, create_weak);
  1110. if (!target_alive) {
  1111. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1112. }
  1113. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1114. return false;
  1115. }
  1116. return refcount == 0;
  1117. }
  1118. }
  1119. void *CSharpLanguage::get_instance_binding(Object *p_object) {
  1120. return p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1121. }
  1122. void *CSharpLanguage::get_instance_binding_with_setup(Object *p_object) {
  1123. void *binding = get_instance_binding(p_object);
  1124. // Initially this was in `_instance_binding_create_callback`. However, after the new instance
  1125. // binding re-write it was resulting in a deadlock in `_instance_binding_reference`, as
  1126. // `setup_csharp_script_binding` may call `reference()`. It was moved here outside to fix that.
  1127. if (binding) {
  1128. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1129. if (!script_binding.inited) {
  1130. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1131. if (!script_binding.inited) { // Another thread may have set it up
  1132. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, p_object);
  1133. }
  1134. }
  1135. }
  1136. return binding;
  1137. }
  1138. void *CSharpLanguage::get_existing_instance_binding(Object *p_object) {
  1139. #ifdef DEBUG_ENABLED
  1140. CRASH_COND(p_object->has_instance_binding(p_object));
  1141. #endif // DEBUG_ENABLED
  1142. return get_instance_binding(p_object);
  1143. }
  1144. bool CSharpLanguage::has_instance_binding(Object *p_object) {
  1145. return p_object->has_instance_binding(get_singleton());
  1146. }
  1147. void CSharpLanguage::tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
  1148. // This method should not fail
  1149. CRASH_COND(!p_unmanaged);
  1150. // All mono objects created from the managed world (e.g.: 'new Player()')
  1151. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1152. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1153. CRASH_COND(p_ref_counted != (bool)rc);
  1154. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1155. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1156. // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
  1157. // script binding instead. One of the advantages of this is that if a script is attached
  1158. // later and it's not a C# script, then the managed object won't have to be disposed.
  1159. // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
  1160. // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
  1161. if (p_ref_counted) {
  1162. // Unsafe refcount increment. The managed instance also counts as a reference.
  1163. // This way if the unmanaged world has no references to our owner
  1164. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1165. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1166. // May not me referenced yet, so we must use init_ref() instead of reference()
  1167. if (rc->init_ref()) {
  1168. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1169. }
  1170. }
  1171. // The object was just created, no script instance binding should have been attached
  1172. CRASH_COND(CSharpLanguage::has_instance_binding(p_unmanaged));
  1173. void *binding = CSharpLanguage::get_singleton()->get_instance_binding(p_unmanaged);
  1174. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1175. script_binding.inited = true;
  1176. script_binding.type_name = *p_native_name;
  1177. script_binding.gchandle = gchandle;
  1178. script_binding.owner = p_unmanaged;
  1179. }
  1180. void CSharpLanguage::tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
  1181. // This method should not fail
  1182. Ref<CSharpScript> script = *p_script;
  1183. // We take care of destructing this reference here, so the managed code won't need to do another P/Invoke call
  1184. p_script->~Ref();
  1185. CRASH_COND(!p_unmanaged);
  1186. // All mono objects created from the managed world (e.g.: 'new Player()')
  1187. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1188. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1189. CRASH_COND(p_ref_counted != (bool)rc);
  1190. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1191. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1192. CRASH_COND(script.is_null());
  1193. CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(p_unmanaged, script.ptr(), gchandle);
  1194. p_unmanaged->set_script_instance(csharp_instance);
  1195. csharp_instance->connect_event_signals();
  1196. }
  1197. void CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
  1198. // This method should not fail
  1199. CRASH_COND(!p_unmanaged);
  1200. CSharpInstance *instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
  1201. if (!instance) {
  1202. // Native bindings don't need post-setup
  1203. return;
  1204. }
  1205. CRASH_COND(!instance->gchandle.is_released());
  1206. // Tie managed to unmanaged
  1207. instance->gchandle = MonoGCHandleData(p_gchandle_intptr, gdmono::GCHandleType::STRONG_HANDLE);
  1208. if (instance->base_ref_counted) {
  1209. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1210. }
  1211. {
  1212. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1213. // instances is a set, so it's safe to insert multiple times (e.g.: from _internal_new_managed)
  1214. instance->script->instances.insert(instance->owner);
  1215. }
  1216. instance->connect_event_signals();
  1217. }
  1218. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
  1219. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
  1220. RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
  1221. instance->base_ref_counted = rc != nullptr;
  1222. instance->owner = p_owner;
  1223. instance->gchandle = p_gchandle;
  1224. if (instance->base_ref_counted) {
  1225. instance->_reference_owner_unsafe();
  1226. }
  1227. {
  1228. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1229. p_script->instances.insert(p_owner);
  1230. }
  1231. return instance;
  1232. }
  1233. Object *CSharpInstance::get_owner() {
  1234. return owner;
  1235. }
  1236. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1237. ERR_FAIL_COND_V(script.is_null(), false);
  1238. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_Set(
  1239. gchandle.get_intptr(), &p_name, &p_value);
  1240. }
  1241. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1242. ERR_FAIL_COND_V(script.is_null(), false);
  1243. Variant ret_value;
  1244. bool ret = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Get(
  1245. gchandle.get_intptr(), &p_name, &ret_value);
  1246. if (ret) {
  1247. r_ret = ret_value;
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1253. List<PropertyInfo> props;
  1254. ERR_FAIL_COND(script.is_null());
  1255. #ifdef TOOLS_ENABLED
  1256. for (const PropertyInfo &prop : script->exported_members_cache) {
  1257. props.push_back(prop);
  1258. }
  1259. #else
  1260. for (const KeyValue<StringName, PropertyInfo> &E : script->member_info) {
  1261. props.push_front(E.value);
  1262. }
  1263. #endif
  1264. for (PropertyInfo &prop : props) {
  1265. validate_property(prop);
  1266. p_properties->push_back(prop);
  1267. }
  1268. // Call _get_property_list
  1269. StringName method = SNAME("_get_property_list");
  1270. Variant ret;
  1271. Callable::CallError call_error;
  1272. bool ok = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1273. gchandle.get_intptr(), &method, nullptr, 0, &call_error, &ret);
  1274. // CALL_ERROR_INVALID_METHOD would simply mean it was not overridden
  1275. if (call_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) {
  1276. if (call_error.error != Callable::CallError::CALL_OK) {
  1277. ERR_PRINT("Error calling '_get_property_list': " + Variant::get_call_error_text(method, nullptr, 0, call_error));
  1278. } else if (!ok) {
  1279. ERR_PRINT("Unexpected error calling '_get_property_list'");
  1280. } else {
  1281. Array array = ret;
  1282. for (int i = 0, size = array.size(); i < size; i++) {
  1283. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1284. }
  1285. }
  1286. }
  1287. CSharpScript *top = script.ptr()->base_script.ptr();
  1288. while (top != nullptr) {
  1289. props.clear();
  1290. #ifdef TOOLS_ENABLED
  1291. for (const PropertyInfo &prop : top->exported_members_cache) {
  1292. props.push_back(prop);
  1293. }
  1294. #else
  1295. for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
  1296. props.push_front(E.value);
  1297. }
  1298. #endif
  1299. for (PropertyInfo &prop : props) {
  1300. validate_property(prop);
  1301. p_properties->push_back(prop);
  1302. }
  1303. top = top->base_script.ptr();
  1304. }
  1305. }
  1306. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1307. if (script->member_info.has(p_name)) {
  1308. if (r_is_valid) {
  1309. *r_is_valid = true;
  1310. }
  1311. return script->member_info[p_name].type;
  1312. }
  1313. if (r_is_valid) {
  1314. *r_is_valid = false;
  1315. }
  1316. return Variant::NIL;
  1317. }
  1318. bool CSharpInstance::property_can_revert(const StringName &p_name) const {
  1319. ERR_FAIL_COND_V(script.is_null(), false);
  1320. Variant name_arg = p_name;
  1321. const Variant *args[1] = { &name_arg };
  1322. Variant ret;
  1323. Callable::CallError call_error;
  1324. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1325. gchandle.get_intptr(), &SNAME("_property_can_revert"), args, 1, &call_error, &ret);
  1326. if (call_error.error != Callable::CallError::CALL_OK) {
  1327. return false;
  1328. }
  1329. return (bool)ret;
  1330. }
  1331. void CSharpInstance::validate_property(PropertyInfo &p_property) const {
  1332. ERR_FAIL_COND(script.is_null());
  1333. Variant property_arg = (Dictionary)p_property;
  1334. const Variant *args[1] = { &property_arg };
  1335. Variant ret;
  1336. Callable::CallError call_error;
  1337. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1338. gchandle.get_intptr(), &SNAME("_validate_property"), args, 1, &call_error, &ret);
  1339. if (call_error.error != Callable::CallError::CALL_OK) {
  1340. return;
  1341. }
  1342. p_property = PropertyInfo::from_dict(property_arg);
  1343. }
  1344. bool CSharpInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
  1345. ERR_FAIL_COND_V(script.is_null(), false);
  1346. Variant name_arg = p_name;
  1347. const Variant *args[1] = { &name_arg };
  1348. Variant ret;
  1349. Callable::CallError call_error;
  1350. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1351. gchandle.get_intptr(), &SNAME("_property_get_revert"), args, 1, &call_error, &ret);
  1352. if (call_error.error != Callable::CallError::CALL_OK) {
  1353. return false;
  1354. }
  1355. r_ret = ret;
  1356. return true;
  1357. }
  1358. void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
  1359. if (!script->is_valid() || !script->valid) {
  1360. return;
  1361. }
  1362. script->get_script_method_list(p_list);
  1363. }
  1364. bool CSharpInstance::has_method(const StringName &p_method) const {
  1365. if (script.is_null()) {
  1366. return false;
  1367. }
  1368. if (!GDMonoCache::godot_api_cache_updated) {
  1369. return false;
  1370. }
  1371. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_HasMethodUnknownParams(
  1372. gchandle.get_intptr(), &p_method);
  1373. }
  1374. int CSharpInstance::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  1375. if (!script->is_valid() || !script->valid) {
  1376. if (r_is_valid) {
  1377. *r_is_valid = false;
  1378. }
  1379. return 0;
  1380. }
  1381. const CSharpScript *top = script.ptr();
  1382. while (top != nullptr) {
  1383. for (const CSharpScript::CSharpMethodInfo &E : top->methods) {
  1384. if (E.name == p_method) {
  1385. if (r_is_valid) {
  1386. *r_is_valid = true;
  1387. }
  1388. return E.method_info.arguments.size();
  1389. }
  1390. }
  1391. top = top->base_script.ptr();
  1392. }
  1393. if (r_is_valid) {
  1394. *r_is_valid = false;
  1395. }
  1396. return 0;
  1397. }
  1398. Variant CSharpInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1399. ERR_FAIL_COND_V(script.is_null(), Variant());
  1400. Variant ret;
  1401. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1402. gchandle.get_intptr(), &p_method, p_args, p_argcount, &r_error, &ret);
  1403. return ret;
  1404. }
  1405. bool CSharpInstance::_reference_owner_unsafe() {
  1406. #ifdef DEBUG_ENABLED
  1407. CRASH_COND(!base_ref_counted);
  1408. CRASH_COND(owner == nullptr);
  1409. CRASH_COND(unsafe_referenced); // already referenced
  1410. #endif // DEBUG_ENABLED
  1411. // Unsafe refcount increment. The managed instance also counts as a reference.
  1412. // This way if the unmanaged world has no references to our owner
  1413. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1414. // See: _unreference_owner_unsafe()
  1415. // May not be referenced yet, so we must use init_ref() instead of reference()
  1416. if (static_cast<RefCounted *>(owner)->init_ref()) {
  1417. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1418. unsafe_referenced = true;
  1419. }
  1420. return unsafe_referenced;
  1421. }
  1422. bool CSharpInstance::_unreference_owner_unsafe() {
  1423. #ifdef DEBUG_ENABLED
  1424. CRASH_COND(!base_ref_counted);
  1425. CRASH_COND(owner == nullptr);
  1426. #endif // DEBUG_ENABLED
  1427. if (!unsafe_referenced) {
  1428. return false; // Already unreferenced
  1429. }
  1430. unsafe_referenced = false;
  1431. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1432. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1433. // See: _reference_owner_unsafe()
  1434. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1435. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1436. return static_cast<RefCounted *>(owner)->unreference();
  1437. }
  1438. bool CSharpInstance::_internal_new_managed() {
  1439. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1440. ERR_FAIL_NULL_V(owner, false);
  1441. ERR_FAIL_COND_V(script.is_null(), false);
  1442. ERR_FAIL_COND_V(!script->can_instantiate(), false);
  1443. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1444. script.ptr(), owner, nullptr, 0);
  1445. if (!ok) {
  1446. // Important to clear this before destroying the script instance here
  1447. script = Ref<CSharpScript>();
  1448. owner = nullptr;
  1449. return false;
  1450. }
  1451. CRASH_COND(gchandle.is_released());
  1452. return true;
  1453. }
  1454. void CSharpInstance::mono_object_disposed(GCHandleIntPtr p_gchandle_to_free) {
  1455. // Must make sure event signals are not left dangling
  1456. disconnect_event_signals();
  1457. #ifdef DEBUG_ENABLED
  1458. CRASH_COND(base_ref_counted);
  1459. CRASH_COND(gchandle.is_released());
  1460. #endif // DEBUG_ENABLED
  1461. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1462. }
  1463. void CSharpInstance::mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1464. #ifdef DEBUG_ENABLED
  1465. CRASH_COND(!base_ref_counted);
  1466. CRASH_COND(gchandle.is_released());
  1467. #endif // DEBUG_ENABLED
  1468. // Must make sure event signals are not left dangling
  1469. disconnect_event_signals();
  1470. r_remove_script_instance = false;
  1471. if (_unreference_owner_unsafe()) {
  1472. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1473. r_delete_owner = true;
  1474. } else {
  1475. r_delete_owner = false;
  1476. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1477. if (!p_is_finalizer) {
  1478. // If the native instance is still alive and Dispose() was called
  1479. // (instead of the finalizer), then we remove the script instance.
  1480. r_remove_script_instance = true;
  1481. // TODO: Last usage of 'is_finalizing_scripts_domain'. It should be replaced with a check to determine if the load context is being unloaded.
  1482. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1483. // If the native instance is still alive and this is called from the finalizer,
  1484. // then it was referenced from another thread before the finalizer could
  1485. // unreference and delete it, so we want to keep it.
  1486. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1487. // could have already been collected. Instead we will create a new managed instance here.
  1488. if (!_internal_new_managed()) {
  1489. r_remove_script_instance = true;
  1490. }
  1491. }
  1492. }
  1493. }
  1494. void CSharpInstance::connect_event_signals() {
  1495. const CSharpScript *top = script.ptr();
  1496. while (top != nullptr && top->valid) {
  1497. for (const CSharpScript::EventSignalInfo &signal : top->event_signals) {
  1498. String signal_name = signal.name;
  1499. // TODO: Use pooling for ManagedCallable instances.
  1500. EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, signal_name));
  1501. Callable callable(event_signal_callable);
  1502. connected_event_signals.push_back(callable);
  1503. owner->connect(signal_name, callable);
  1504. }
  1505. top = top->base_script.ptr();
  1506. }
  1507. }
  1508. void CSharpInstance::disconnect_event_signals() {
  1509. for (const Callable &callable : connected_event_signals) {
  1510. const EventSignalCallable *event_signal_callable = static_cast<const EventSignalCallable *>(callable.get_custom());
  1511. owner->disconnect(event_signal_callable->get_signal(), callable);
  1512. }
  1513. connected_event_signals.clear();
  1514. }
  1515. void CSharpInstance::refcount_incremented() {
  1516. #ifdef DEBUG_ENABLED
  1517. CRASH_COND(!base_ref_counted);
  1518. CRASH_COND(owner == nullptr);
  1519. #endif // DEBUG_ENABLED
  1520. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1521. if (rc_owner->get_reference_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1522. // The reference count was increased after the managed side was the only one referencing our owner.
  1523. // This means the owner is being referenced again by the unmanaged side,
  1524. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1525. // Release the current weak handle and replace it with a strong handle.
  1526. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1527. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1528. GCHandleIntPtr new_gchandle = { nullptr };
  1529. bool create_weak = false;
  1530. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1531. old_gchandle, &new_gchandle, create_weak);
  1532. if (!target_alive) {
  1533. return; // Called after the managed side was collected, so nothing to do here
  1534. }
  1535. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1536. }
  1537. }
  1538. bool CSharpInstance::refcount_decremented() {
  1539. #ifdef DEBUG_ENABLED
  1540. CRASH_COND(!base_ref_counted);
  1541. CRASH_COND(owner == nullptr);
  1542. #endif // DEBUG_ENABLED
  1543. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1544. int refcount = rc_owner->get_reference_count();
  1545. if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1546. // If owner owner is no longer referenced by the unmanaged side,
  1547. // the managed instance takes responsibility of deleting the owner when GCed.
  1548. // Release the current strong handle and replace it with a weak handle.
  1549. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1550. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1551. GCHandleIntPtr new_gchandle = { nullptr };
  1552. bool create_weak = true;
  1553. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1554. old_gchandle, &new_gchandle, create_weak);
  1555. if (!target_alive) {
  1556. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1557. }
  1558. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1559. return false;
  1560. }
  1561. ref_dying = (refcount == 0);
  1562. return ref_dying;
  1563. }
  1564. const Variant CSharpInstance::get_rpc_config() const {
  1565. return script->get_rpc_config();
  1566. }
  1567. void CSharpInstance::notification(int p_notification, bool p_reversed) {
  1568. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1569. if (base_ref_counted) {
  1570. // At this point, Dispose() was already called (manually or from the finalizer).
  1571. // The RefCounted wouldn't have reached 0 otherwise, since the managed side
  1572. // references it and Dispose() needs to be called to release it.
  1573. // However, this means C# RefCounted scripts can't receive NOTIFICATION_PREDELETE, but
  1574. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1575. return;
  1576. }
  1577. } else if (p_notification == Object::NOTIFICATION_PREDELETE_CLEANUP) {
  1578. // When NOTIFICATION_PREDELETE_CLEANUP is sent, we also take the chance to call Dispose().
  1579. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE_CLEANUP is guaranteed
  1580. // to be sent at least once, which happens right before the call to the destructor.
  1581. predelete_notified = true;
  1582. if (base_ref_counted) {
  1583. // At this point, Dispose() was already called (manually or from the finalizer).
  1584. // The RefCounted wouldn't have reached 0 otherwise, since the managed side
  1585. // references it and Dispose() needs to be called to release it.
  1586. return;
  1587. }
  1588. // NOTIFICATION_PREDELETE_CLEANUP is not sent to scripts.
  1589. // After calling Dispose() the C# instance can no longer be used,
  1590. // so it should be the last thing we do.
  1591. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1592. gchandle.get_intptr(), /* okIfNull */ false);
  1593. return;
  1594. }
  1595. _call_notification(p_notification, p_reversed);
  1596. }
  1597. void CSharpInstance::_call_notification(int p_notification, bool p_reversed) {
  1598. Variant arg = p_notification;
  1599. const Variant *args[1] = { &arg };
  1600. Variant ret;
  1601. Callable::CallError call_error;
  1602. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1603. gchandle.get_intptr(), &SNAME("_notification"), args, 1, &call_error, &ret);
  1604. }
  1605. String CSharpInstance::to_string(bool *r_valid) {
  1606. String res;
  1607. bool valid;
  1608. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallToString(
  1609. gchandle.get_intptr(), &res, &valid);
  1610. if (r_valid) {
  1611. *r_valid = valid;
  1612. }
  1613. return res;
  1614. }
  1615. Ref<Script> CSharpInstance::get_script() const {
  1616. return script;
  1617. }
  1618. ScriptLanguage *CSharpInstance::get_language() {
  1619. return CSharpLanguage::get_singleton();
  1620. }
  1621. CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
  1622. script(p_script) {
  1623. }
  1624. CSharpInstance::~CSharpInstance() {
  1625. destructing_script_instance = true;
  1626. // Must make sure event signals are not left dangling
  1627. disconnect_event_signals();
  1628. if (!gchandle.is_released()) {
  1629. if (!predelete_notified && !ref_dying) {
  1630. // This destructor is not called from the owners destructor.
  1631. // This could be being called from the owner's set_script_instance method,
  1632. // meaning this script is being replaced with another one. If this is the case,
  1633. // we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
  1634. // and that would mess up with the new script instance if called later.
  1635. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1636. gchandle.get_intptr(), /* okIfNull */ true);
  1637. }
  1638. gchandle.release(); // Make sure the gchandle is released
  1639. }
  1640. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1641. if (base_ref_counted && !ref_dying && owner && unsafe_referenced) {
  1642. // The owner's script or script instance is being replaced (or removed)
  1643. // Transfer ownership to an "instance binding"
  1644. RefCounted *rc_owner = static_cast<RefCounted *>(owner);
  1645. // We will unreference the owner before referencing it again, so we need to keep it alive
  1646. Ref<RefCounted> scope_keep_owner_alive(rc_owner);
  1647. (void)scope_keep_owner_alive;
  1648. // Unreference the owner here, before the new "instance binding" references it.
  1649. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
  1650. bool die = _unreference_owner_unsafe();
  1651. CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
  1652. void *data = CSharpLanguage::get_instance_binding_with_setup(owner);
  1653. CRASH_COND(data == nullptr);
  1654. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1655. CRASH_COND(!script_binding.inited);
  1656. #ifdef DEBUG_ENABLED
  1657. // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
  1658. CRASH_COND(rc_owner->get_reference_count() <= 1);
  1659. #endif // DEBUG_ENABLED
  1660. }
  1661. if (script.is_valid() && owner) {
  1662. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1663. #ifdef DEBUG_ENABLED
  1664. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1665. HashSet<Object *>::Iterator match = script->instances.find(owner);
  1666. CRASH_COND(!match);
  1667. script->instances.remove(match);
  1668. #else
  1669. script->instances.erase(owner);
  1670. #endif // DEBUG_ENABLED
  1671. }
  1672. }
  1673. #ifdef TOOLS_ENABLED
  1674. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1675. placeholders.erase(p_placeholder);
  1676. }
  1677. #endif
  1678. #ifdef TOOLS_ENABLED
  1679. void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1680. for (const KeyValue<StringName, Variant> &E : exported_members_defval_cache) {
  1681. values[E.key] = E.value;
  1682. }
  1683. for (const PropertyInfo &prop_info : exported_members_cache) {
  1684. propnames.push_back(prop_info);
  1685. }
  1686. if (base_script.is_valid()) {
  1687. base_script->_update_exports_values(values, propnames);
  1688. }
  1689. }
  1690. #endif
  1691. void GD_CLR_STDCALL CSharpScript::_add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count) {
  1692. GDMonoCache::godotsharp_property_info *props = (GDMonoCache::godotsharp_property_info *)p_props;
  1693. #ifdef TOOLS_ENABLED
  1694. p_script->exported_members_cache.push_back(PropertyInfo(
  1695. Variant::NIL, p_script->type_info.class_name, PROPERTY_HINT_NONE,
  1696. p_script->get_path(), PROPERTY_USAGE_CATEGORY));
  1697. #endif
  1698. for (int i = 0; i < p_count; i++) {
  1699. const GDMonoCache::godotsharp_property_info &prop = props[i];
  1700. StringName name = *reinterpret_cast<const StringName *>(&prop.name);
  1701. String hint_string = *reinterpret_cast<const String *>(&prop.hint_string);
  1702. PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage);
  1703. p_script->member_info[name] = pinfo;
  1704. if (prop.exported) {
  1705. #ifdef TOOLS_ENABLED
  1706. p_script->exported_members_cache.push_back(pinfo);
  1707. #endif
  1708. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1709. p_script->exported_members_names.insert(name);
  1710. #endif // DEBUG_ENABLED
  1711. }
  1712. }
  1713. }
  1714. #ifdef TOOLS_ENABLED
  1715. void GD_CLR_STDCALL CSharpScript::_add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count) {
  1716. GDMonoCache::godotsharp_property_def_val_pair *def_vals = (GDMonoCache::godotsharp_property_def_val_pair *)p_def_vals;
  1717. for (int i = 0; i < p_count; i++) {
  1718. const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = def_vals[i];
  1719. StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name);
  1720. Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value);
  1721. p_script->exported_members_defval_cache[name] = value;
  1722. }
  1723. }
  1724. #endif
  1725. bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) {
  1726. #ifdef TOOLS_ENABLED
  1727. bool is_editor = Engine::get_singleton()->is_editor_hint();
  1728. if (is_editor) {
  1729. placeholder_fallback_enabled = true; // until proven otherwise
  1730. }
  1731. #endif
  1732. if (!valid) {
  1733. return false;
  1734. }
  1735. bool changed = false;
  1736. #ifdef TOOLS_ENABLED
  1737. if (exports_invalidated)
  1738. #endif
  1739. {
  1740. #ifdef TOOLS_ENABLED
  1741. exports_invalidated = false;
  1742. #endif
  1743. changed = true;
  1744. member_info.clear();
  1745. #ifdef TOOLS_ENABLED
  1746. exported_members_cache.clear();
  1747. exported_members_defval_cache.clear();
  1748. #endif
  1749. if (GDMonoCache::godot_api_cache_updated) {
  1750. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this, &_add_property_info_list_callback);
  1751. #ifdef TOOLS_ENABLED
  1752. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this, &_add_property_default_values_callback);
  1753. #endif
  1754. }
  1755. }
  1756. #ifdef TOOLS_ENABLED
  1757. if (is_editor) {
  1758. placeholder_fallback_enabled = false;
  1759. if ((changed || p_instance_to_update) && placeholders.size()) {
  1760. // Update placeholders if any
  1761. HashMap<StringName, Variant> values;
  1762. List<PropertyInfo> propnames;
  1763. _update_exports_values(values, propnames);
  1764. if (changed) {
  1765. for (PlaceHolderScriptInstance *instance : placeholders) {
  1766. instance->update(propnames, values);
  1767. }
  1768. } else {
  1769. p_instance_to_update->update(propnames, values);
  1770. }
  1771. } else if (placeholders.size()) {
  1772. uint64_t script_modified_time = FileAccess::get_modified_time(get_path());
  1773. uint64_t last_valid_build_time = GDMono::get_singleton()->get_project_assembly_modified_time();
  1774. if (script_modified_time > last_valid_build_time) {
  1775. for (PlaceHolderScriptInstance *instance : placeholders) {
  1776. Object *owner = instance->get_owner();
  1777. if (owner->get_script_instance() == instance) {
  1778. owner->notify_property_list_changed();
  1779. }
  1780. }
  1781. }
  1782. }
  1783. }
  1784. #endif
  1785. return changed;
  1786. }
  1787. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1788. if (p_name == SNAME("script/source")) {
  1789. r_ret = get_source_code();
  1790. return true;
  1791. }
  1792. return false;
  1793. }
  1794. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1795. if (p_name == SNAME("script/source")) {
  1796. set_source_code(p_value);
  1797. reload();
  1798. return true;
  1799. }
  1800. return false;
  1801. }
  1802. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1803. p_properties->push_back(PropertyInfo(Variant::STRING, SNAME("script/source"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
  1804. }
  1805. void CSharpScript::_bind_methods() {
  1806. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  1807. }
  1808. void CSharpScript::reload_registered_script(Ref<CSharpScript> p_script) {
  1809. // IMPORTANT:
  1810. // This method must be called only after the CSharpScript and its associated type
  1811. // have been added to the script bridge map in the ScriptManagerBridge C# class.
  1812. // Other than that, it's the same as `CSharpScript::reload`.
  1813. // This method should not fail, only assertions allowed.
  1814. // Unlike `reload`, we print an error rather than silently returning,
  1815. // as we can assert this won't be called a second time until invalidated.
  1816. ERR_FAIL_COND(!p_script->reload_invalidated);
  1817. p_script->valid = true;
  1818. p_script->reload_invalidated = false;
  1819. update_script_class_info(p_script);
  1820. p_script->_update_exports();
  1821. #ifdef TOOLS_ENABLED
  1822. CSharpLanguage::get_singleton()->_queue_for_filesystem_update(p_script->get_path());
  1823. #endif
  1824. }
  1825. // Extract information about the script using the mono class.
  1826. void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
  1827. TypeInfo type_info;
  1828. // TODO: Use GDExtension godot_dictionary
  1829. Array methods_array;
  1830. methods_array.~Array();
  1831. Dictionary rpc_functions_dict;
  1832. rpc_functions_dict.~Dictionary();
  1833. Dictionary signals_dict;
  1834. signals_dict.~Dictionary();
  1835. Ref<CSharpScript> base_script;
  1836. GDMonoCache::managed_callbacks.ScriptManagerBridge_UpdateScriptClassInfo(
  1837. p_script.ptr(), &type_info,
  1838. &methods_array, &rpc_functions_dict, &signals_dict, &base_script);
  1839. p_script->type_info = type_info;
  1840. p_script->rpc_config.clear();
  1841. p_script->rpc_config = rpc_functions_dict;
  1842. // Methods
  1843. p_script->methods.clear();
  1844. p_script->methods.resize(methods_array.size());
  1845. int push_index = 0;
  1846. for (int i = 0; i < methods_array.size(); i++) {
  1847. Dictionary method_info_dict = methods_array[i];
  1848. StringName name = method_info_dict["name"];
  1849. MethodInfo mi;
  1850. mi.name = name;
  1851. mi.return_val = PropertyInfo::from_dict(method_info_dict["return_val"]);
  1852. Array params = method_info_dict["params"];
  1853. for (int j = 0; j < params.size(); j++) {
  1854. Dictionary param = params[j];
  1855. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1856. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1857. arg_info.usage = (uint32_t)param["usage"];
  1858. if (param.has("class_name")) {
  1859. arg_info.class_name = (StringName)param["class_name"];
  1860. }
  1861. mi.arguments.push_back(arg_info);
  1862. }
  1863. mi.flags = (uint32_t)method_info_dict["flags"];
  1864. p_script->methods.set(push_index++, CSharpMethodInfo{ name, mi });
  1865. }
  1866. // Event signals
  1867. // Performance is not critical here as this will be replaced with source generators.
  1868. p_script->event_signals.clear();
  1869. // Sigh... can't we just have capacity?
  1870. p_script->event_signals.resize(signals_dict.size());
  1871. push_index = 0;
  1872. for (const Variant *s = signals_dict.next(nullptr); s != nullptr; s = signals_dict.next(s)) {
  1873. StringName name = *s;
  1874. MethodInfo mi;
  1875. mi.name = name;
  1876. Array params = signals_dict[*s];
  1877. for (int i = 0; i < params.size(); i++) {
  1878. Dictionary param = params[i];
  1879. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1880. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1881. arg_info.usage = (uint32_t)param["usage"];
  1882. if (param.has("class_name")) {
  1883. arg_info.class_name = (StringName)param["class_name"];
  1884. }
  1885. mi.arguments.push_back(arg_info);
  1886. }
  1887. p_script->event_signals.set(push_index++, EventSignalInfo{ name, mi });
  1888. }
  1889. p_script->base_script = base_script;
  1890. }
  1891. bool CSharpScript::can_instantiate() const {
  1892. #ifdef TOOLS_ENABLED
  1893. bool extra_cond = (type_info.is_tool || ScriptServer::is_scripting_enabled()) && !Engine::get_singleton()->is_recovery_mode_hint();
  1894. #else
  1895. bool extra_cond = true;
  1896. #endif
  1897. // FIXME Need to think this through better.
  1898. // For tool scripts, this will never fire if the class is not found. That's because we
  1899. // don't know if it's a tool script if we can't find the class to access the attributes.
  1900. if (extra_cond && !valid) {
  1901. ERR_FAIL_V_MSG(false, "Cannot instantiate C# script because the associated class could not be found. Script: '" + get_path() + "'. Make sure the script exists and contains a class definition with a name that matches the filename of the script exactly (it's case-sensitive).");
  1902. }
  1903. return valid && type_info.can_instantiate() && extra_cond;
  1904. }
  1905. StringName CSharpScript::get_instance_base_type() const {
  1906. return type_info.native_base_name;
  1907. }
  1908. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
  1909. ERR_FAIL_COND_V_MSG(!type_info.can_instantiate(), nullptr, "Cannot instantiate C# script. Script: '" + get_path() + "'.");
  1910. /* STEP 1, CREATE */
  1911. Ref<RefCounted> ref;
  1912. if (p_is_ref_counted) {
  1913. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  1914. ref = Ref<RefCounted>(static_cast<RefCounted *>(p_owner));
  1915. }
  1916. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  1917. if (CSharpLanguage::has_instance_binding(p_owner)) {
  1918. void *data = CSharpLanguage::get_existing_instance_binding(p_owner);
  1919. CRASH_COND(data == nullptr);
  1920. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1921. if (script_binding.inited && !script_binding.gchandle.is_released()) {
  1922. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1923. script_binding.gchandle.get_intptr(), /* okIfNull */ true);
  1924. script_binding.gchandle.release(); // Just in case
  1925. script_binding.inited = false;
  1926. }
  1927. }
  1928. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this)));
  1929. instance->base_ref_counted = p_is_ref_counted;
  1930. instance->owner = p_owner;
  1931. instance->owner->set_script_instance(instance);
  1932. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1933. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1934. this, p_owner, p_args, p_argcount);
  1935. if (!ok) {
  1936. // Important to clear this before destroying the script instance here
  1937. instance->script = Ref<CSharpScript>();
  1938. p_owner->set_script_instance(nullptr);
  1939. instance->owner = nullptr;
  1940. return nullptr;
  1941. }
  1942. CRASH_COND(instance->gchandle.is_released());
  1943. /* STEP 3, PARTY */
  1944. //@TODO make thread safe
  1945. return instance;
  1946. }
  1947. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1948. if (!valid) {
  1949. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1950. return Variant();
  1951. }
  1952. r_error.error = Callable::CallError::CALL_OK;
  1953. StringName native_name;
  1954. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1955. ERR_FAIL_COND_V(native_name == StringName(), Variant());
  1956. Object *owner = ClassDB::instantiate(native_name);
  1957. Ref<RefCounted> ref;
  1958. RefCounted *r = Object::cast_to<RefCounted>(owner);
  1959. if (r) {
  1960. ref = Ref<RefCounted>(r);
  1961. }
  1962. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
  1963. if (!instance) {
  1964. if (ref.is_null()) {
  1965. memdelete(owner); // no owner, sorry
  1966. }
  1967. return Variant();
  1968. }
  1969. if (ref.is_valid()) {
  1970. return ref;
  1971. } else {
  1972. return owner;
  1973. }
  1974. }
  1975. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1976. #ifdef DEBUG_ENABLED
  1977. CRASH_COND(!valid);
  1978. #endif // DEBUG_ENABLED
  1979. StringName native_name;
  1980. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1981. ERR_FAIL_COND_V(native_name == StringName(), nullptr);
  1982. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1983. if (EngineDebugger::is_active()) {
  1984. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
  1985. "Script inherits from native type '" + String(native_name) +
  1986. "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'");
  1987. }
  1988. ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'.");
  1989. }
  1990. Callable::CallError unchecked_error;
  1991. return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error);
  1992. }
  1993. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1994. #ifdef TOOLS_ENABLED
  1995. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1996. placeholders.insert(si);
  1997. _update_exports(si);
  1998. return si;
  1999. #else
  2000. return nullptr;
  2001. #endif
  2002. }
  2003. bool CSharpScript::instance_has(const Object *p_this) const {
  2004. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2005. return instances.has((Object *)p_this);
  2006. }
  2007. bool CSharpScript::has_source_code() const {
  2008. return !source.is_empty();
  2009. }
  2010. String CSharpScript::get_source_code() const {
  2011. return source;
  2012. }
  2013. void CSharpScript::set_source_code(const String &p_code) {
  2014. if (source == p_code) {
  2015. return;
  2016. }
  2017. source = p_code;
  2018. #ifdef TOOLS_ENABLED
  2019. source_changed_cache = true;
  2020. #endif
  2021. }
  2022. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  2023. if (!valid) {
  2024. return;
  2025. }
  2026. const CSharpScript *top = this;
  2027. while (top != nullptr) {
  2028. for (const CSharpMethodInfo &E : top->methods) {
  2029. p_list->push_back(E.method_info);
  2030. }
  2031. top = top->base_script.ptr();
  2032. }
  2033. }
  2034. bool CSharpScript::has_method(const StringName &p_method) const {
  2035. if (!valid) {
  2036. return false;
  2037. }
  2038. for (const CSharpMethodInfo &E : methods) {
  2039. if (E.name == p_method) {
  2040. return true;
  2041. }
  2042. }
  2043. return false;
  2044. }
  2045. int CSharpScript::get_script_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  2046. if (!valid) {
  2047. if (r_is_valid) {
  2048. *r_is_valid = false;
  2049. }
  2050. return 0;
  2051. }
  2052. for (const CSharpMethodInfo &E : methods) {
  2053. if (E.name == p_method) {
  2054. if (r_is_valid) {
  2055. *r_is_valid = true;
  2056. }
  2057. return E.method_info.arguments.size();
  2058. }
  2059. }
  2060. if (r_is_valid) {
  2061. *r_is_valid = false;
  2062. }
  2063. return 0;
  2064. }
  2065. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2066. if (!valid) {
  2067. return MethodInfo();
  2068. }
  2069. MethodInfo mi;
  2070. for (const CSharpMethodInfo &E : methods) {
  2071. if (E.name == p_method) {
  2072. if (mi.name == p_method) {
  2073. // We already found a method with the same name before so
  2074. // that means this method has overloads, the best we can do
  2075. // is return an empty MethodInfo.
  2076. return MethodInfo();
  2077. }
  2078. mi = E.method_info;
  2079. }
  2080. }
  2081. return mi;
  2082. }
  2083. Variant CSharpScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  2084. if (valid) {
  2085. Variant ret;
  2086. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CallStatic(this, &p_method, p_args, p_argcount, &r_error, &ret);
  2087. if (ok) {
  2088. return ret;
  2089. }
  2090. }
  2091. return Script::callp(p_method, p_args, p_argcount, r_error);
  2092. }
  2093. Error CSharpScript::reload(bool p_keep_state) {
  2094. if (!reload_invalidated) {
  2095. return OK;
  2096. }
  2097. // In the case of C#, reload doesn't really do any script reloading.
  2098. // That's done separately via domain reloading.
  2099. reload_invalidated = false;
  2100. String script_path = get_path();
  2101. valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(this, &script_path);
  2102. if (valid) {
  2103. #ifdef DEBUG_ENABLED
  2104. print_verbose("Found class for script " + get_path());
  2105. #endif // DEBUG_ENABLED
  2106. update_script_class_info(this);
  2107. _update_exports();
  2108. #ifdef TOOLS_ENABLED
  2109. CSharpLanguage::get_singleton()->_queue_for_filesystem_update(script_path);
  2110. #endif
  2111. }
  2112. return OK;
  2113. }
  2114. ScriptLanguage *CSharpScript::get_language() const {
  2115. return CSharpLanguage::get_singleton();
  2116. }
  2117. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2118. #ifdef TOOLS_ENABLED
  2119. HashMap<StringName, Variant>::ConstIterator E = exported_members_defval_cache.find(p_property);
  2120. if (E) {
  2121. r_value = E->value;
  2122. return true;
  2123. }
  2124. if (base_script.is_valid()) {
  2125. return base_script->get_property_default_value(p_property, r_value);
  2126. }
  2127. #endif
  2128. return false;
  2129. }
  2130. void CSharpScript::update_exports() {
  2131. #ifdef TOOLS_ENABLED
  2132. _update_exports();
  2133. #endif
  2134. }
  2135. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2136. if (!valid) {
  2137. return false;
  2138. }
  2139. if (!GDMonoCache::godot_api_cache_updated) {
  2140. return false;
  2141. }
  2142. for (const EventSignalInfo &signal : event_signals) {
  2143. if (signal.name == p_signal) {
  2144. return true;
  2145. }
  2146. }
  2147. if (base_script.is_valid()) {
  2148. return base_script->has_script_signal(p_signal);
  2149. }
  2150. return false;
  2151. }
  2152. void CSharpScript::_get_script_signal_list(List<MethodInfo> *r_signals, bool p_include_base) const {
  2153. if (!valid) {
  2154. return;
  2155. }
  2156. for (const EventSignalInfo &signal : event_signals) {
  2157. r_signals->push_back(signal.method_info);
  2158. }
  2159. if (!p_include_base) {
  2160. return;
  2161. }
  2162. if (base_script.is_valid()) {
  2163. base_script->get_script_signal_list(r_signals);
  2164. }
  2165. }
  2166. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2167. _get_script_signal_list(r_signals, true);
  2168. }
  2169. bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
  2170. Ref<CSharpScript> cs = p_script;
  2171. if (cs.is_null()) {
  2172. return false;
  2173. }
  2174. if (!valid || !cs->valid) {
  2175. return false;
  2176. }
  2177. if (!GDMonoCache::godot_api_cache_updated) {
  2178. return false;
  2179. }
  2180. return GDMonoCache::managed_callbacks.ScriptManagerBridge_ScriptIsOrInherits(this, cs.ptr());
  2181. }
  2182. Ref<Script> CSharpScript::get_base_script() const {
  2183. return base_script;
  2184. }
  2185. StringName CSharpScript::get_global_name() const {
  2186. return type_info.is_global_class ? StringName(type_info.class_name) : StringName();
  2187. }
  2188. void CSharpScript::get_script_property_list(List<PropertyInfo> *r_list) const {
  2189. #ifdef TOOLS_ENABLED
  2190. const CSharpScript *top = this;
  2191. while (top != nullptr) {
  2192. for (const PropertyInfo &E : top->exported_members_cache) {
  2193. r_list->push_back(E);
  2194. }
  2195. top = top->base_script.ptr();
  2196. }
  2197. #else
  2198. const CSharpScript *top = this;
  2199. while (top != nullptr) {
  2200. List<PropertyInfo> props;
  2201. for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
  2202. props.push_front(E.value);
  2203. }
  2204. for (const PropertyInfo &prop : props) {
  2205. r_list->push_back(prop);
  2206. }
  2207. top = top->base_script.ptr();
  2208. }
  2209. #endif
  2210. }
  2211. int CSharpScript::get_member_line(const StringName &p_member) const {
  2212. // TODO omnisharp
  2213. return -1;
  2214. }
  2215. const Variant CSharpScript::get_rpc_config() const {
  2216. return rpc_config;
  2217. }
  2218. Error CSharpScript::load_source_code(const String &p_path) {
  2219. Error ferr = read_all_file_utf8(p_path, source);
  2220. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2221. ferr == ERR_INVALID_DATA
  2222. ? "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2223. " Please ensure that scripts are saved in valid UTF-8 unicode."
  2224. : "Failed to read file: '" + p_path + "'.");
  2225. #ifdef TOOLS_ENABLED
  2226. source_changed_cache = true;
  2227. #endif
  2228. return OK;
  2229. }
  2230. void CSharpScript::_clear() {
  2231. type_info = TypeInfo();
  2232. valid = false;
  2233. reload_invalidated = true;
  2234. }
  2235. CSharpScript::CSharpScript() {
  2236. _clear();
  2237. #ifdef DEBUG_ENABLED
  2238. {
  2239. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2240. CSharpLanguage::get_singleton()->script_list.add(&script_list);
  2241. }
  2242. #endif // DEBUG_ENABLED
  2243. }
  2244. CSharpScript::~CSharpScript() {
  2245. #ifdef DEBUG_ENABLED
  2246. {
  2247. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2248. CSharpLanguage::get_singleton()->script_list.remove(&script_list);
  2249. }
  2250. #endif // DEBUG_ENABLED
  2251. if (GDMonoCache::godot_api_cache_updated) {
  2252. GDMonoCache::managed_callbacks.ScriptManagerBridge_RemoveScriptBridge(this);
  2253. }
  2254. }
  2255. void CSharpScript::get_members(HashSet<StringName> *p_members) {
  2256. #ifdef DEBUG_ENABLED
  2257. if (p_members) {
  2258. for (const StringName &member_name : exported_members_names) {
  2259. p_members->insert(member_name);
  2260. }
  2261. }
  2262. #endif // DEBUG_ENABLED
  2263. }
  2264. /*************** RESOURCE ***************/
  2265. Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  2266. if (r_error) {
  2267. *r_error = ERR_FILE_CANT_OPEN;
  2268. }
  2269. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2270. String real_path = p_path;
  2271. if (p_path.begins_with("csharp://")) {
  2272. // This is a virtual path used by generic types, extract the real path.
  2273. real_path = "res://" + p_path.trim_prefix("csharp://");
  2274. real_path = real_path.substr(0, real_path.rfind_char(':'));
  2275. }
  2276. Ref<CSharpScript> scr;
  2277. if (GDMonoCache::godot_api_cache_updated) {
  2278. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetOrCreateScriptBridgeForPath(&p_path, &scr);
  2279. ERR_FAIL_COND_V_MSG(scr.is_null(), Ref<Resource>(), "Could not create C# script '" + real_path + "'.");
  2280. } else {
  2281. scr.instantiate();
  2282. }
  2283. #ifdef DEBUG_ENABLED
  2284. Error err = scr->load_source_code(real_path);
  2285. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot load C# script file '" + real_path + "'.");
  2286. #endif // DEBUG_ENABLED
  2287. // Only one instance of a C# script is allowed to exist.
  2288. ERR_FAIL_COND_V_MSG(!scr->get_path().is_empty() && scr->get_path() != p_original_path, Ref<Resource>(),
  2289. "The C# script path is different from the path it was registered in the C# dictionary.");
  2290. Ref<Resource> existing = ResourceCache::get_ref(p_path);
  2291. switch (p_cache_mode) {
  2292. case ResourceFormatLoader::CACHE_MODE_IGNORE:
  2293. case ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP:
  2294. break;
  2295. case ResourceFormatLoader::CACHE_MODE_REUSE:
  2296. if (existing.is_null()) {
  2297. scr->set_path(p_original_path);
  2298. } else {
  2299. scr = existing;
  2300. }
  2301. break;
  2302. case ResourceFormatLoader::CACHE_MODE_REPLACE:
  2303. case ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP:
  2304. scr->set_path(p_original_path, true);
  2305. break;
  2306. }
  2307. scr->reload();
  2308. if (r_error) {
  2309. *r_error = OK;
  2310. }
  2311. return scr;
  2312. }
  2313. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2314. p_extensions->push_back("cs");
  2315. }
  2316. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2317. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2318. }
  2319. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2320. return p_path.has_extension("cs") ? CSharpLanguage::get_singleton()->get_type() : "";
  2321. }
  2322. Error ResourceFormatSaverCSharpScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  2323. Ref<CSharpScript> sqscr = p_resource;
  2324. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2325. String source = sqscr->get_source_code();
  2326. #ifdef TOOLS_ENABLED
  2327. if (!FileAccess::exists(p_path)) {
  2328. // The file does not yet exist, let's assume the user just created this script. In such
  2329. // cases we need to check whether the solution and csproj were already created or not.
  2330. if (!_create_project_solution_if_needed()) {
  2331. ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
  2332. }
  2333. }
  2334. #endif
  2335. {
  2336. Error err;
  2337. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2338. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2339. file->store_string(source);
  2340. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2341. return ERR_CANT_CREATE;
  2342. }
  2343. }
  2344. #ifdef TOOLS_ENABLED
  2345. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2346. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2347. }
  2348. #endif
  2349. return OK;
  2350. }
  2351. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  2352. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2353. p_extensions->push_back("cs");
  2354. }
  2355. }
  2356. bool ResourceFormatSaverCSharpScript::recognize(const Ref<Resource> &p_resource) const {
  2357. return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
  2358. }