csharp_script.cpp 81 KB

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