csharp_script.cpp 86 KB

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