csharp_script.cpp 83 KB

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