csharp_script.cpp 87 KB

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