csharp_script.cpp 83 KB

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