csharp_script.cpp 87 KB

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