csharp_script.cpp 82 KB

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