csharp_script.cpp 81 KB

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