csharp_script.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "csharp_script.h"
  31. #include <mono/metadata/threads.h>
  32. #include "core/io/json.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "core/os/thread.h"
  36. #include "core/project_settings.h"
  37. #ifdef TOOLS_ENABLED
  38. #include "editor/bindings_generator.h"
  39. #include "editor/csharp_project.h"
  40. #include "editor/editor_node.h"
  41. #include "editor/node_dock.h"
  42. #endif
  43. #ifdef DEBUG_METHODS_ENABLED
  44. #include "class_db_api_json.h"
  45. #endif
  46. #include "editor/editor_internal_calls.h"
  47. #include "godotsharp_dirs.h"
  48. #include "mono_gd/gd_mono_cache.h"
  49. #include "mono_gd/gd_mono_class.h"
  50. #include "mono_gd/gd_mono_marshal.h"
  51. #include "mono_gd/gd_mono_utils.h"
  52. #include "signal_awaiter_utils.h"
  53. #include "utils/macros.h"
  54. #include "utils/mutex_utils.h"
  55. #include "utils/string_utils.h"
  56. #include "utils/thread_local.h"
  57. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  58. #ifdef TOOLS_ENABLED
  59. static bool _create_project_solution_if_needed() {
  60. String sln_path = GodotSharpDirs::get_project_sln_path();
  61. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  62. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  63. // A solution does not yet exist, create a new one
  64. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == NULL);
  65. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
  66. }
  67. return true;
  68. }
  69. #endif
  70. CSharpLanguage *CSharpLanguage::singleton = NULL;
  71. String CSharpLanguage::get_name() const {
  72. return "C#";
  73. }
  74. String CSharpLanguage::get_type() const {
  75. return "CSharpScript";
  76. }
  77. String CSharpLanguage::get_extension() const {
  78. return "cs";
  79. }
  80. Error CSharpLanguage::execute_file(const String &p_path) {
  81. // ??
  82. return OK;
  83. }
  84. void CSharpLanguage::init() {
  85. #ifdef DEBUG_METHODS_ENABLED
  86. if (OS::get_singleton()->get_cmdline_args().find("--class_db_to_json")) {
  87. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  88. #ifdef TOOLS_ENABLED
  89. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  90. #endif
  91. }
  92. #endif
  93. gdmono = memnew(GDMono);
  94. gdmono->initialize();
  95. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  96. // Generate bindings here, before loading assemblies. 'initialize_load_assemblies' aborts
  97. // the applications if the api assemblies or the main tools assembly is missing, but this
  98. // is not a problem for BindingsGenerator as it only needs the tools project editor assembly.
  99. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  100. BindingsGenerator::handle_cmdline_args(cmdline_args);
  101. #endif
  102. #ifndef MONO_GLUE_ENABLED
  103. print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'");
  104. #endif
  105. if (gdmono->is_runtime_initialized())
  106. gdmono->initialize_load_assemblies();
  107. #ifdef TOOLS_ENABLED
  108. EditorNode::add_init_callback(&_editor_init_callback);
  109. #endif
  110. }
  111. void CSharpLanguage::finish() {
  112. finalizing = true;
  113. // Make sure all script binding gchandles are released before finalizing GDMono
  114. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  115. CSharpScriptBinding &script_binding = E->value();
  116. if (script_binding.gchandle.is_valid()) {
  117. script_binding.gchandle->release();
  118. script_binding.inited = false;
  119. }
  120. }
  121. if (gdmono) {
  122. memdelete(gdmono);
  123. gdmono = NULL;
  124. }
  125. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  126. script_bindings.clear();
  127. #ifdef DEBUG_ENABLED
  128. for (List<ObjectID>::Element *E = unsafely_referenced_objects.front(); E; E = E->next()) {
  129. const ObjectID &id = E->get();
  130. Object *obj = ObjectDB::get_instance(id);
  131. if (obj) {
  132. ERR_PRINTS("Leaked unsafe reference to object: " + obj->get_class() + ":" + itos(id));
  133. } else {
  134. ERR_PRINTS("Leaked unsafe reference to deleted object: " + itos(id));
  135. }
  136. }
  137. #endif
  138. finalizing = false;
  139. }
  140. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  141. static const char *_reserved_words[] = {
  142. // Reserved keywords
  143. "abstract",
  144. "as",
  145. "base",
  146. "bool",
  147. "break",
  148. "byte",
  149. "case",
  150. "catch",
  151. "char",
  152. "checked",
  153. "class",
  154. "const",
  155. "continue",
  156. "decimal",
  157. "default",
  158. "delegate",
  159. "do",
  160. "double",
  161. "else",
  162. "enum",
  163. "event",
  164. "explicit",
  165. "extern",
  166. "false",
  167. "finally",
  168. "fixed",
  169. "float",
  170. "for",
  171. "foreach",
  172. "goto",
  173. "if",
  174. "implicit",
  175. "in",
  176. "int",
  177. "interface",
  178. "internal",
  179. "is",
  180. "lock",
  181. "long",
  182. "namespace",
  183. "new",
  184. "null",
  185. "object",
  186. "operator",
  187. "out",
  188. "override",
  189. "params",
  190. "private",
  191. "protected",
  192. "public",
  193. "readonly",
  194. "ref",
  195. "return",
  196. "sbyte",
  197. "sealed",
  198. "short",
  199. "sizeof",
  200. "stackalloc",
  201. "static",
  202. "string",
  203. "struct",
  204. "switch",
  205. "this",
  206. "throw",
  207. "true",
  208. "try",
  209. "typeof",
  210. "uint",
  211. "ulong",
  212. "unchecked",
  213. "unsafe",
  214. "ushort",
  215. "using",
  216. "virtual",
  217. "void",
  218. "volatile",
  219. "while",
  220. // Contextual keywords. Not reserved words, but I guess we should include
  221. // them because this seems to be used only for syntax highlighting.
  222. "add",
  223. "alias",
  224. "ascending",
  225. "async",
  226. "await",
  227. "by",
  228. "descending",
  229. "dynamic",
  230. "equals",
  231. "from",
  232. "get",
  233. "global",
  234. "group",
  235. "into",
  236. "join",
  237. "let",
  238. "nameof",
  239. "on",
  240. "orderby",
  241. "partial",
  242. "remove",
  243. "select",
  244. "set",
  245. "value",
  246. "var",
  247. "when",
  248. "where",
  249. "yield",
  250. 0
  251. };
  252. const char **w = _reserved_words;
  253. while (*w) {
  254. p_words->push_back(*w);
  255. w++;
  256. }
  257. }
  258. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  259. p_delimiters->push_back("//"); // single-line comment
  260. p_delimiters->push_back("/* */"); // delimited comment
  261. }
  262. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  263. p_delimiters->push_back("' '"); // character literal
  264. p_delimiters->push_back("\" \""); // regular string literal
  265. p_delimiters->push_back("@\" \""); // verbatim string literal
  266. }
  267. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  268. String base_class = p_base_class_name;
  269. if (p_class_name == base_class) {
  270. base_class = "Godot." + base_class;
  271. }
  272. return base_class;
  273. }
  274. Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  275. String script_template = "using " BINDINGS_NAMESPACE ";\n"
  276. "using System;\n"
  277. "\n"
  278. "public class %CLASS% : %BASE%\n"
  279. "{\n"
  280. " // Declare member variables here. Examples:\n"
  281. " // private int a = 2;\n"
  282. " // private string b = \"text\";\n"
  283. "\n"
  284. " // Called when the node enters the scene tree for the first time.\n"
  285. " public override void _Ready()\n"
  286. " {\n"
  287. " \n"
  288. " }\n"
  289. "\n"
  290. "// // Called every frame. 'delta' is the elapsed time since the previous frame.\n"
  291. "// public override void _Process(float delta)\n"
  292. "// {\n"
  293. "// \n"
  294. "// }\n"
  295. "}\n";
  296. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  297. script_template = script_template.replace("%BASE%", base_class_name)
  298. .replace("%CLASS%", p_class_name);
  299. Ref<CSharpScript> script;
  300. script.instance();
  301. script->set_source_code(script_template);
  302. script->set_name(p_class_name);
  303. return script;
  304. }
  305. bool CSharpLanguage::is_using_templates() {
  306. return true;
  307. }
  308. void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  309. String src = p_script->get_source_code();
  310. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  311. src = src.replace("%BASE%", base_class_name)
  312. .replace("%CLASS%", p_class_name)
  313. .replace("%TS%", _get_indentation());
  314. p_script->set_source_code(src);
  315. }
  316. String CSharpLanguage::validate_path(const String &p_path) const {
  317. String class_name = p_path.get_file().get_basename();
  318. List<String> keywords;
  319. get_reserved_words(&keywords);
  320. if (keywords.find(class_name)) {
  321. return TTR("Class name can't be a reserved keyword");
  322. }
  323. return "";
  324. }
  325. Script *CSharpLanguage::create_script() const {
  326. return memnew(CSharpScript);
  327. }
  328. bool CSharpLanguage::has_named_classes() const {
  329. return false;
  330. }
  331. bool CSharpLanguage::supports_builtin_mode() const {
  332. return false;
  333. }
  334. #ifdef TOOLS_ENABLED
  335. static String variant_type_to_managed_name(const String &p_var_type_name) {
  336. if (p_var_type_name.empty())
  337. return "object";
  338. if (!ClassDB::class_exists(p_var_type_name)) {
  339. return p_var_type_name;
  340. }
  341. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
  342. return "Godot.Object";
  343. if (p_var_type_name == Variant::get_type_name(Variant::REAL)) {
  344. #ifdef REAL_T_IS_DOUBLE
  345. return "double";
  346. #else
  347. return "float";
  348. #endif
  349. }
  350. if (p_var_type_name == Variant::get_type_name(Variant::STRING))
  351. return "string"; // I prefer this one >:[
  352. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
  353. return "Collections.Dictionary";
  354. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
  355. return "Collections.Array";
  356. if (p_var_type_name == Variant::get_type_name(Variant::POOL_BYTE_ARRAY))
  357. return "byte[]";
  358. if (p_var_type_name == Variant::get_type_name(Variant::POOL_INT_ARRAY))
  359. return "int[]";
  360. if (p_var_type_name == Variant::get_type_name(Variant::POOL_REAL_ARRAY)) {
  361. #ifdef REAL_T_IS_DOUBLE
  362. return "double[]";
  363. #else
  364. return "float[]";
  365. #endif
  366. }
  367. if (p_var_type_name == Variant::get_type_name(Variant::POOL_STRING_ARRAY))
  368. return "string[]";
  369. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR2_ARRAY))
  370. return "Vector2[]";
  371. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR3_ARRAY))
  372. return "Vector3[]";
  373. if (p_var_type_name == Variant::get_type_name(Variant::POOL_COLOR_ARRAY))
  374. return "Color[]";
  375. Variant::Type var_types[] = {
  376. Variant::BOOL,
  377. Variant::INT,
  378. Variant::VECTOR2,
  379. Variant::RECT2,
  380. Variant::VECTOR3,
  381. Variant::TRANSFORM2D,
  382. Variant::PLANE,
  383. Variant::QUAT,
  384. Variant::AABB,
  385. Variant::BASIS,
  386. Variant::TRANSFORM,
  387. Variant::COLOR,
  388. Variant::NODE_PATH,
  389. Variant::_RID
  390. };
  391. for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  392. if (p_var_type_name == Variant::get_type_name(var_types[i]))
  393. return p_var_type_name;
  394. }
  395. return "object";
  396. }
  397. String CSharpLanguage::make_function(const String &, const String &p_name, const PoolStringArray &p_args) const {
  398. // FIXME
  399. // - Due to Godot's API limitation this just appends the function to the end of the file
  400. // - Use fully qualified name if there is ambiguity
  401. String s = "private void " + p_name + "(";
  402. for (int i = 0; i < p_args.size(); i++) {
  403. const String &arg = p_args[i];
  404. if (i > 0)
  405. s += ", ";
  406. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  407. }
  408. s += ")\n{\n // Replace with function body.\n}\n";
  409. return s;
  410. }
  411. #else
  412. String CSharpLanguage::make_function(const String &, const String &, const PoolStringArray &) const {
  413. return String();
  414. }
  415. #endif
  416. String CSharpLanguage::_get_indentation() const {
  417. #ifdef TOOLS_ENABLED
  418. if (Engine::get_singleton()->is_editor_hint()) {
  419. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);
  420. if (use_space_indentation) {
  421. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  422. String space_indent = "";
  423. for (int i = 0; i < indent_size; i++) {
  424. space_indent += " ";
  425. }
  426. return space_indent;
  427. }
  428. }
  429. #endif
  430. return "\t";
  431. }
  432. String CSharpLanguage::debug_get_error() const {
  433. return _debug_error;
  434. }
  435. int CSharpLanguage::debug_get_stack_level_count() const {
  436. if (_debug_parse_err_line >= 0)
  437. return 1;
  438. // TODO: StackTrace
  439. return 1;
  440. }
  441. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  442. if (_debug_parse_err_line >= 0)
  443. return _debug_parse_err_line;
  444. // TODO: StackTrace
  445. return 1;
  446. }
  447. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  448. if (_debug_parse_err_line >= 0)
  449. return String();
  450. // TODO: StackTrace
  451. return String();
  452. }
  453. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  454. if (_debug_parse_err_line >= 0)
  455. return _debug_parse_err_file;
  456. // TODO: StackTrace
  457. return String();
  458. }
  459. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  460. #ifdef DEBUG_ENABLED
  461. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  462. GD_MONO_SCOPE_THREAD_ATTACH;
  463. if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated)
  464. return Vector<StackInfo>();
  465. MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
  466. MonoBoolean need_file_info = true;
  467. void *ctor_args[1] = { &need_file_info };
  468. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
  469. Vector<StackInfo> si;
  470. si = stack_trace_get_info(stack_trace);
  471. return si;
  472. #else
  473. return Vector<StackInfo>();
  474. #endif
  475. }
  476. #ifdef DEBUG_ENABLED
  477. Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
  478. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  479. GD_MONO_SCOPE_THREAD_ATTACH;
  480. MonoException *exc = NULL;
  481. MonoArray *frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames).invoke(p_stack_trace, &exc);
  482. if (exc) {
  483. GDMonoUtils::debug_print_unhandled_exception(exc);
  484. return Vector<StackInfo>();
  485. }
  486. int frame_count = mono_array_length(frames);
  487. if (frame_count <= 0)
  488. return Vector<StackInfo>();
  489. Vector<StackInfo> si;
  490. si.resize(frame_count);
  491. for (int i = 0; i < frame_count; i++) {
  492. StackInfo &sif = si.write[i];
  493. MonoObject *frame = mono_array_get(frames, MonoObject *, i);
  494. MonoString *file_name;
  495. int file_line_num;
  496. MonoString *method_decl;
  497. CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo).invoke(frame, &file_name, &file_line_num, &method_decl, &exc);
  498. if (exc) {
  499. GDMonoUtils::debug_print_unhandled_exception(exc);
  500. return Vector<StackInfo>();
  501. }
  502. // TODO
  503. // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
  504. // can reproduce with a MissingMethodException on internal calls
  505. sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
  506. sif.line = file_line_num;
  507. sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
  508. }
  509. return si;
  510. }
  511. #endif
  512. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  513. #ifdef DEBUG_ENABLED
  514. ObjectID id = p_obj->get_instance_id();
  515. ERR_FAIL_COND_MSG(unsafely_referenced_objects.find(id), "Multiple unsafe references for object: " + p_obj->get_class() + ":" + itos(id));
  516. unsafely_referenced_objects.push_back(id);
  517. #endif
  518. }
  519. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  520. #ifdef DEBUG_ENABLED
  521. ObjectID id = p_obj->get_instance_id();
  522. List<ObjectID>::Element *elem = unsafely_referenced_objects.find(id);
  523. ERR_FAIL_NULL(elem);
  524. unsafely_referenced_objects.erase(elem);
  525. #endif
  526. }
  527. void CSharpLanguage::frame() {
  528. if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) {
  529. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle;
  530. if (task_scheduler_handle.is_valid()) {
  531. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  532. if (task_scheduler) {
  533. MonoException *exc = NULL;
  534. CACHED_METHOD_THUNK(GodotTaskScheduler, Activate).invoke(task_scheduler, &exc);
  535. if (exc) {
  536. GDMonoUtils::debug_unhandled_exception(exc);
  537. }
  538. }
  539. }
  540. }
  541. }
  542. struct CSharpScriptDepSort {
  543. // must support sorting so inheritance works properly (parent must be reloaded first)
  544. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  545. if (A == B)
  546. return false; // shouldn't happen but..
  547. GDMonoClass *I = B->base;
  548. while (I) {
  549. if (I == A->script_class) {
  550. // A is a base of B
  551. return true;
  552. }
  553. I = I->get_parent_class();
  554. }
  555. return false; // not a base
  556. }
  557. };
  558. void CSharpLanguage::reload_all_scripts() {
  559. #ifdef GD_MONO_HOT_RELOAD
  560. if (is_assembly_reloading_needed()) {
  561. GD_MONO_SCOPE_THREAD_ATTACH;
  562. reload_assemblies(false);
  563. }
  564. #endif
  565. }
  566. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  567. (void)p_script; // UNUSED
  568. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  569. #ifdef TOOLS_ENABLED
  570. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  571. #endif
  572. #ifdef GD_MONO_HOT_RELOAD
  573. if (is_assembly_reloading_needed()) {
  574. GD_MONO_SCOPE_THREAD_ATTACH;
  575. reload_assemblies(p_soft_reload);
  576. }
  577. #endif
  578. }
  579. #ifdef GD_MONO_HOT_RELOAD
  580. bool CSharpLanguage::is_assembly_reloading_needed() {
  581. if (!gdmono->is_runtime_initialized())
  582. return false;
  583. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  584. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  585. String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
  586. if (appname_safe.empty()) {
  587. appname_safe = "UnnamedProject";
  588. }
  589. appname_safe += ".dll";
  590. if (proj_assembly) {
  591. String proj_asm_path = proj_assembly->get_path();
  592. if (!FileAccess::exists(proj_assembly->get_path())) {
  593. // Maybe it wasn't loaded from the default path, so check this as well
  594. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
  595. if (!FileAccess::exists(proj_asm_path))
  596. return false; // No assembly to load
  597. }
  598. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  599. return false; // Already up to date
  600. } else {
  601. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe)))
  602. return false; // No assembly to load
  603. }
  604. return true;
  605. }
  606. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  607. if (!gdmono->is_runtime_initialized())
  608. return;
  609. // There is no soft reloading with Mono. It's always hard reloading.
  610. List<Ref<CSharpScript> > scripts;
  611. {
  612. SCOPED_MUTEX_LOCK(script_instances_mutex);
  613. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  614. // Cast to CSharpScript to avoid being erased by accident
  615. scripts.push_back(Ref<CSharpScript>(elem->self()));
  616. }
  617. }
  618. List<Ref<CSharpScript> > to_reload;
  619. // We need to keep reference instances alive during reloading
  620. List<Ref<Reference> > ref_instances;
  621. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  622. CSharpScriptBinding &script_binding = E->value();
  623. Reference *ref = Object::cast_to<Reference>(script_binding.owner);
  624. if (ref) {
  625. ref_instances.push_back(Ref<Reference>(ref));
  626. }
  627. }
  628. // As scripts are going to be reloaded, must proceed without locking here
  629. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  630. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  631. Ref<CSharpScript> &script = E->get();
  632. to_reload.push_back(script);
  633. if (script->get_path().empty()) {
  634. script->tied_class_name_for_reload = script->script_class->get_name();
  635. script->tied_class_namespace_for_reload = script->script_class->get_namespace();
  636. }
  637. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  638. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  639. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  640. Object *obj = F->get();
  641. script->pending_reload_instances.insert(obj->get_instance_id());
  642. Reference *ref = Object::cast_to<Reference>(obj);
  643. if (ref) {
  644. ref_instances.push_back(Ref<Reference>(ref));
  645. }
  646. }
  647. #ifdef TOOLS_ENABLED
  648. for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) {
  649. Object *obj = F->get()->get_owner();
  650. script->pending_reload_instances.insert(obj->get_instance_id());
  651. Reference *ref = Object::cast_to<Reference>(obj);
  652. if (ref) {
  653. ref_instances.push_back(Ref<Reference>(ref));
  654. }
  655. }
  656. #endif
  657. // Save state and remove script from instances
  658. Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
  659. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  660. Object *obj = F->get();
  661. ERR_CONTINUE(!obj->get_script_instance());
  662. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  663. // Call OnBeforeSerialize
  664. if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  665. obj->get_script_instance()->call_multilevel(string_names.on_before_serialize);
  666. // Save instance info
  667. CSharpScript::StateBackup state;
  668. // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
  669. csi->get_properties_state_for_reloading(state.properties);
  670. owners_map[obj->get_instance_id()] = state;
  671. }
  672. }
  673. // After the state of all instances is saved, clear scripts and script instances
  674. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  675. Ref<CSharpScript> &script = E->get();
  676. while (script->instances.front()) {
  677. Object *obj = script->instances.front()->get();
  678. obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  679. }
  680. script->_clear();
  681. }
  682. // Do domain reload
  683. if (gdmono->reload_scripts_domain() != OK) {
  684. // Failed to reload the scripts domain
  685. // Make sure to add the scripts back to their owners before returning
  686. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  687. Ref<CSharpScript> scr = E->get();
  688. for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
  689. Object *obj = ObjectDB::get_instance(F->key());
  690. if (!obj)
  691. continue;
  692. ObjectID obj_id = obj->get_instance_id();
  693. // Use a placeholder for now to avoid losing the state when saving a scene
  694. obj->set_script(scr.get_ref_ptr());
  695. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  696. obj->set_script_instance(placeholder);
  697. #ifdef TOOLS_ENABLED
  698. // Even though build didn't fail, this tells the placeholder to keep properties and
  699. // it allows using property_set_fallback for restoring the state without a valid script.
  700. scr->placeholder_fallback_enabled = true;
  701. #endif
  702. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  703. for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
  704. placeholder->property_set_fallback(G->get().first, G->get().second, NULL);
  705. }
  706. scr->pending_reload_state.erase(obj_id);
  707. }
  708. }
  709. return;
  710. }
  711. List<Ref<CSharpScript> > to_reload_state;
  712. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  713. Ref<CSharpScript> script = E->get();
  714. if (!script->get_path().empty()) {
  715. #ifdef TOOLS_ENABLED
  716. script->exports_invalidated = true;
  717. #endif
  718. script->signals_invalidated = true;
  719. script->reload(p_soft_reload);
  720. script->update_exports();
  721. if (!script->valid) {
  722. script->pending_reload_instances.clear();
  723. continue;
  724. }
  725. } else {
  726. const StringName &class_namespace = script->tied_class_namespace_for_reload;
  727. const StringName &class_name = script->tied_class_name_for_reload;
  728. GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
  729. // Search in project and tools assemblies first as those are the most likely to have the class
  730. GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : NULL);
  731. #ifdef TOOLS_ENABLED
  732. if (!script_class) {
  733. GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
  734. script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : NULL);
  735. }
  736. #endif
  737. if (!script_class) {
  738. script_class = gdmono->get_class(class_namespace, class_name);
  739. }
  740. if (!script_class) {
  741. // The class was removed, can't reload
  742. script->pending_reload_instances.clear();
  743. continue;
  744. }
  745. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
  746. if (!obj_type) {
  747. // The class no longer inherits Godot.Object, can't reload
  748. script->pending_reload_instances.clear();
  749. continue;
  750. }
  751. GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
  752. CSharpScript::initialize_for_managed_type(script, script_class, native);
  753. }
  754. String native_name = NATIVE_GDMONOCLASS_NAME(script->native);
  755. {
  756. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  757. ObjectID obj_id = F->get();
  758. Object *obj = ObjectDB::get_instance(obj_id);
  759. if (!obj) {
  760. script->pending_reload_state.erase(obj_id);
  761. continue;
  762. }
  763. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  764. // No longer inherits the same compatible type, can't reload
  765. script->pending_reload_state.erase(obj_id);
  766. continue;
  767. }
  768. ScriptInstance *si = obj->get_script_instance();
  769. #ifdef TOOLS_ENABLED
  770. if (si) {
  771. // If the script instance is not null, then it must be a placeholder.
  772. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  773. CRASH_COND(!si->is_placeholder());
  774. if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
  775. // Replace placeholder with a script instance
  776. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  777. // Backup placeholder script instance state before replacing it with a script instance
  778. si->get_property_state(state_backup.properties);
  779. ScriptInstance *script_instance = script->instance_create(obj);
  780. if (script_instance) {
  781. script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  782. obj->set_script_instance(script_instance);
  783. }
  784. }
  785. continue;
  786. }
  787. #else
  788. CRASH_COND(si != NULL);
  789. #endif
  790. // Re-create script instance
  791. obj->set_script(script.get_ref_ptr()); // will create the script instance as well
  792. }
  793. }
  794. to_reload_state.push_back(script);
  795. }
  796. for (List<Ref<CSharpScript> >::Element *E = to_reload_state.front(); E; E = E->next()) {
  797. Ref<CSharpScript> script = E->get();
  798. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  799. ObjectID obj_id = F->get();
  800. Object *obj = ObjectDB::get_instance(obj_id);
  801. if (!obj) {
  802. script->pending_reload_state.erase(obj_id);
  803. continue;
  804. }
  805. ERR_CONTINUE(!obj->get_script_instance());
  806. // TODO: Restore serialized state
  807. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  808. for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
  809. obj->get_script_instance()->set(G->get().first, G->get().second);
  810. }
  811. // Call OnAfterDeserialization
  812. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  813. if (csi && csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  814. obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
  815. }
  816. script->pending_reload_instances.clear();
  817. }
  818. #ifdef TOOLS_ENABLED
  819. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  820. if (Engine::get_singleton()->is_editor_hint()) {
  821. EditorNode::get_singleton()->get_inspector()->update_tree();
  822. NodeDock::singleton->update_lists();
  823. }
  824. #endif
  825. }
  826. #endif
  827. void CSharpLanguage::_load_scripts_metadata() {
  828. scripts_metadata.clear();
  829. String scripts_metadata_filename = "scripts_metadata.";
  830. #ifdef TOOLS_ENABLED
  831. scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player";
  832. #else
  833. #ifdef DEBUG_ENABLED
  834. scripts_metadata_filename += "debug";
  835. #else
  836. scripts_metadata_filename += "release";
  837. #endif
  838. #endif
  839. String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename);
  840. if (FileAccess::exists(scripts_metadata_path)) {
  841. String old_json;
  842. Error ferr = read_all_file_utf8(scripts_metadata_path, old_json);
  843. ERR_FAIL_COND(ferr != OK);
  844. Variant old_dict_var;
  845. String err_str;
  846. int err_line;
  847. Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line);
  848. if (json_err != OK) {
  849. ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ").");
  850. return;
  851. }
  852. scripts_metadata = old_dict_var.operator Dictionary();
  853. scripts_metadata_invalidated = false;
  854. print_verbose("Successfully loaded scripts metadata");
  855. } else {
  856. if (!Engine::get_singleton()->is_editor_hint()) {
  857. ERR_PRINT("Missing scripts metadata file.");
  858. }
  859. }
  860. }
  861. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  862. p_extensions->push_back("cs");
  863. }
  864. #ifdef TOOLS_ENABLED
  865. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  866. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  867. }
  868. bool CSharpLanguage::overrides_external_editor() {
  869. return get_godotsharp_editor()->call("OverridesExternalEditor");
  870. }
  871. #endif
  872. void CSharpLanguage::thread_enter() {
  873. #if 0
  874. if (gdmono->is_runtime_initialized()) {
  875. GDMonoUtils::attach_current_thread();
  876. }
  877. #endif
  878. }
  879. void CSharpLanguage::thread_exit() {
  880. #if 0
  881. if (gdmono->is_runtime_initialized()) {
  882. GDMonoUtils::detach_current_thread();
  883. }
  884. #endif
  885. }
  886. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  887. // Not a parser error in our case, but it's still used for other type of errors
  888. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  889. _debug_parse_err_line = p_line;
  890. _debug_parse_err_file = p_file;
  891. _debug_error = p_error;
  892. ScriptDebugger::get_singleton()->debug(this, false, true);
  893. return true;
  894. } else {
  895. return false;
  896. }
  897. }
  898. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  899. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  900. _debug_parse_err_line = -1;
  901. _debug_parse_err_file = "";
  902. _debug_error = p_error;
  903. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  904. return true;
  905. } else {
  906. return false;
  907. }
  908. }
  909. void CSharpLanguage::_on_scripts_domain_unloaded() {
  910. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  911. CSharpScriptBinding &script_binding = E->value();
  912. script_binding.inited = false;
  913. }
  914. scripts_metadata_invalidated = true;
  915. }
  916. #ifdef TOOLS_ENABLED
  917. void CSharpLanguage::_editor_init_callback() {
  918. register_editor_internal_calls();
  919. // Initialize GodotSharpEditor
  920. GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
  921. CRASH_COND(editor_klass == NULL);
  922. MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
  923. CRASH_COND(mono_object == NULL);
  924. MonoException *exc = NULL;
  925. GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
  926. UNHANDLED_EXCEPTION(exc);
  927. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object));
  928. CRASH_COND(godotsharp_editor == NULL);
  929. // Enable it as a plugin
  930. EditorNode::add_editor_plugin(godotsharp_editor);
  931. godotsharp_editor->enable_plugin();
  932. get_singleton()->godotsharp_editor = godotsharp_editor;
  933. }
  934. #endif
  935. void CSharpLanguage::set_language_index(int p_idx) {
  936. ERR_FAIL_COND(lang_idx != -1);
  937. lang_idx = p_idx;
  938. }
  939. void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) {
  940. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  941. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  942. p_gchandle->release();
  943. }
  944. }
  945. void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle) {
  946. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_expected_obj); // We might lock after this, so pin it
  947. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  948. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  949. MonoObject *target = p_gchandle->get_target();
  950. // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
  951. // already released and could have been replaced) or if we can't get its target MonoObject*
  952. // (which doesn't necessarily mean it was released, and we want it released in order to
  953. // avoid locking other threads unnecessarily).
  954. if (target == p_expected_obj || target == NULL) {
  955. p_gchandle->release();
  956. }
  957. }
  958. MonoGCHandle::free_handle(pinned_gchandle);
  959. }
  960. CSharpLanguage::CSharpLanguage() {
  961. ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
  962. singleton = this;
  963. finalizing = false;
  964. gdmono = NULL;
  965. #ifdef NO_THREADS
  966. script_instances_mutex = NULL;
  967. script_gchandle_release_mutex = NULL;
  968. language_bind_mutex = NULL;
  969. #else
  970. script_instances_mutex = Mutex::create();
  971. script_gchandle_release_mutex = Mutex::create();
  972. language_bind_mutex = Mutex::create();
  973. #endif
  974. lang_idx = -1;
  975. scripts_metadata_invalidated = true;
  976. #ifdef TOOLS_ENABLED
  977. godotsharp_editor = NULL;
  978. #endif
  979. }
  980. CSharpLanguage::~CSharpLanguage() {
  981. finish();
  982. if (script_instances_mutex) {
  983. memdelete(script_instances_mutex);
  984. script_instances_mutex = NULL;
  985. }
  986. if (language_bind_mutex) {
  987. memdelete(language_bind_mutex);
  988. language_bind_mutex = NULL;
  989. }
  990. if (script_gchandle_release_mutex) {
  991. memdelete(script_gchandle_release_mutex);
  992. script_gchandle_release_mutex = NULL;
  993. }
  994. singleton = NULL;
  995. }
  996. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  997. #ifdef DEBUG_ENABLED
  998. // I don't trust you
  999. if (p_object->get_script_instance()) {
  1000. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  1001. CRASH_COND(csharp_instance != NULL && !csharp_instance->is_destructing_script_instance());
  1002. }
  1003. #endif
  1004. StringName type_name = p_object->get_class_name();
  1005. // ¯\_(ツ)_/¯
  1006. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  1007. while (classinfo && !classinfo->exposed)
  1008. classinfo = classinfo->inherits_ptr;
  1009. ERR_FAIL_NULL_V(classinfo, false);
  1010. type_name = classinfo->name;
  1011. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  1012. ERR_FAIL_NULL_V(type_class, false);
  1013. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  1014. ERR_FAIL_NULL_V(mono_object, false);
  1015. r_script_binding.inited = true;
  1016. r_script_binding.type_name = type_name;
  1017. r_script_binding.wrapper_class = type_class; // cache
  1018. r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
  1019. r_script_binding.owner = p_object;
  1020. // Tie managed to unmanaged
  1021. Reference *ref = Object::cast_to<Reference>(p_object);
  1022. if (ref) {
  1023. // Unsafe refcount increment. The managed instance also counts as a reference.
  1024. // This way if the unmanaged world has no references to our owner
  1025. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1026. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  1027. ref->reference();
  1028. CSharpLanguage::get_singleton()->post_unsafe_reference(ref);
  1029. }
  1030. return true;
  1031. }
  1032. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  1033. SCOPED_MUTEX_LOCK(language_bind_mutex);
  1034. Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
  1035. if (match)
  1036. return (void *)match;
  1037. CSharpScriptBinding script_binding;
  1038. if (!setup_csharp_script_binding(script_binding, p_object))
  1039. return NULL;
  1040. return (void *)insert_script_binding(p_object, script_binding);
  1041. }
  1042. Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  1043. return script_bindings.insert(p_object, p_script_binding);
  1044. }
  1045. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  1046. if (GDMono::get_singleton() == NULL) {
  1047. #ifdef DEBUG_ENABLED
  1048. CRASH_COND(!script_bindings.empty());
  1049. #endif
  1050. // Mono runtime finalized, all the gchandle bindings were already released
  1051. return;
  1052. }
  1053. if (finalizing)
  1054. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1055. GD_MONO_ASSERT_THREAD_ATTACHED;
  1056. {
  1057. SCOPED_MUTEX_LOCK(language_bind_mutex);
  1058. Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;
  1059. CSharpScriptBinding &script_binding = data->value();
  1060. if (script_binding.inited) {
  1061. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1062. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1063. MonoObject *mono_object = script_binding.gchandle->get_target();
  1064. if (mono_object) {
  1065. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  1066. }
  1067. }
  1068. script_bindings.erase(data);
  1069. }
  1070. }
  1071. void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
  1072. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1073. #ifdef DEBUG_ENABLED
  1074. CRASH_COND(!ref_owner);
  1075. CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
  1076. #endif
  1077. void *data = p_object->get_script_instance_binding(get_language_index());
  1078. CRASH_COND(!data);
  1079. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1080. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1081. if (!script_binding.inited)
  1082. return;
  1083. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1084. GD_MONO_SCOPE_THREAD_ATTACH;
  1085. // The reference count was increased after the managed side was the only one referencing our owner.
  1086. // This means the owner is being referenced again by the unmanaged side,
  1087. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1088. MonoObject *target = gchandle->get_target();
  1089. if (!target)
  1090. return; // Called after the managed side was collected, so nothing to do here
  1091. // Release the current weak handle and replace it with a strong handle.
  1092. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target);
  1093. gchandle->release();
  1094. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1095. }
  1096. }
  1097. bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
  1098. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1099. #ifdef DEBUG_ENABLED
  1100. CRASH_COND(!ref_owner);
  1101. CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
  1102. #endif
  1103. void *data = p_object->get_script_instance_binding(get_language_index());
  1104. CRASH_COND(!data);
  1105. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1106. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1107. int refcount = ref_owner->reference_get_count();
  1108. if (!script_binding.inited)
  1109. return refcount == 0;
  1110. if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1111. GD_MONO_SCOPE_THREAD_ATTACH;
  1112. // If owner owner is no longer referenced by the unmanaged side,
  1113. // the managed instance takes responsibility of deleting the owner when GCed.
  1114. MonoObject *target = gchandle->get_target();
  1115. if (!target)
  1116. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1117. // Release the current strong handle and replace it with a weak handle.
  1118. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target);
  1119. gchandle->release();
  1120. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1121. return false;
  1122. }
  1123. return refcount == 0;
  1124. }
  1125. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  1126. CSharpInstance *instance = memnew(CSharpInstance);
  1127. Reference *ref = Object::cast_to<Reference>(p_owner);
  1128. instance->base_ref = ref != NULL;
  1129. instance->script = Ref<CSharpScript>(p_script);
  1130. instance->owner = p_owner;
  1131. instance->gchandle = p_gchandle;
  1132. if (instance->base_ref)
  1133. instance->_reference_owner_unsafe();
  1134. p_script->instances.insert(p_owner);
  1135. return instance;
  1136. }
  1137. MonoObject *CSharpInstance::get_mono_object() const {
  1138. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  1139. return gchandle->get_target();
  1140. }
  1141. Object *CSharpInstance::get_owner() {
  1142. return owner;
  1143. }
  1144. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1145. ERR_FAIL_COND_V(!script.is_valid(), false);
  1146. GD_MONO_SCOPE_THREAD_ATTACH;
  1147. MonoObject *mono_object = get_mono_object();
  1148. ERR_FAIL_NULL_V(mono_object, false);
  1149. GDMonoClass *top = script->script_class;
  1150. while (top && top != script->native) {
  1151. GDMonoField *field = top->get_field(p_name);
  1152. if (field) {
  1153. field->set_value_from_variant(mono_object, p_value);
  1154. return true;
  1155. }
  1156. GDMonoProperty *property = top->get_property(p_name);
  1157. if (property) {
  1158. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
  1159. return true;
  1160. }
  1161. top = top->get_parent_class();
  1162. }
  1163. // Call _set
  1164. top = script->script_class;
  1165. while (top && top != script->native) {
  1166. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  1167. if (method) {
  1168. Variant name = p_name;
  1169. const Variant *args[2] = { &name, &p_value };
  1170. MonoObject *ret = method->invoke(mono_object, args);
  1171. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
  1172. return true;
  1173. break;
  1174. }
  1175. top = top->get_parent_class();
  1176. }
  1177. return false;
  1178. }
  1179. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1180. ERR_FAIL_COND_V(!script.is_valid(), false);
  1181. GD_MONO_SCOPE_THREAD_ATTACH;
  1182. MonoObject *mono_object = get_mono_object();
  1183. ERR_FAIL_NULL_V(mono_object, false);
  1184. GDMonoClass *top = script->script_class;
  1185. while (top && top != script->native) {
  1186. GDMonoField *field = top->get_field(p_name);
  1187. if (field) {
  1188. MonoObject *value = field->get_value(mono_object);
  1189. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1190. return true;
  1191. }
  1192. GDMonoProperty *property = top->get_property(p_name);
  1193. if (property) {
  1194. MonoException *exc = NULL;
  1195. MonoObject *value = property->get_value(mono_object, &exc);
  1196. if (exc) {
  1197. r_ret = Variant();
  1198. GDMonoUtils::set_pending_exception(exc);
  1199. } else {
  1200. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1201. }
  1202. return true;
  1203. }
  1204. top = top->get_parent_class();
  1205. }
  1206. // Call _get
  1207. top = script->script_class;
  1208. while (top && top != script->native) {
  1209. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  1210. if (method) {
  1211. Variant name = p_name;
  1212. const Variant *args[1] = { &name };
  1213. MonoObject *ret = method->invoke(mono_object, args);
  1214. if (ret) {
  1215. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  1216. return true;
  1217. }
  1218. break;
  1219. }
  1220. top = top->get_parent_class();
  1221. }
  1222. return false;
  1223. }
  1224. void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state) {
  1225. List<PropertyInfo> pinfo;
  1226. get_property_list(&pinfo);
  1227. for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
  1228. Pair<StringName, Variant> state_pair;
  1229. state_pair.first = E->get().name;
  1230. ManagedType managedType;
  1231. GDMonoField *field = script->script_class->get_field(state_pair.first);
  1232. if (!field)
  1233. continue; // Properties ignored. We get the property baking fields instead.
  1234. managedType = field->get_type();
  1235. if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
  1236. if (get(state_pair.first, state_pair.second)) {
  1237. r_state.push_back(state_pair);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1243. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  1244. p_properties->push_back(E->value());
  1245. }
  1246. // Call _get_property_list
  1247. ERR_FAIL_COND(!script.is_valid());
  1248. GD_MONO_SCOPE_THREAD_ATTACH;
  1249. MonoObject *mono_object = get_mono_object();
  1250. ERR_FAIL_NULL(mono_object);
  1251. GDMonoClass *top = script->script_class;
  1252. while (top && top != script->native) {
  1253. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);
  1254. if (method) {
  1255. MonoObject *ret = method->invoke(mono_object);
  1256. if (ret) {
  1257. Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
  1258. for (int i = 0, size = array.size(); i < size; i++)
  1259. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1260. return;
  1261. }
  1262. break;
  1263. }
  1264. top = top->get_parent_class();
  1265. }
  1266. }
  1267. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1268. if (script->member_info.has(p_name)) {
  1269. if (r_is_valid)
  1270. *r_is_valid = true;
  1271. return script->member_info[p_name].type;
  1272. }
  1273. if (r_is_valid)
  1274. *r_is_valid = false;
  1275. return Variant::NIL;
  1276. }
  1277. bool CSharpInstance::has_method(const StringName &p_method) const {
  1278. if (!script.is_valid())
  1279. return false;
  1280. GD_MONO_SCOPE_THREAD_ATTACH;
  1281. GDMonoClass *top = script->script_class;
  1282. while (top && top != script->native) {
  1283. if (top->has_fetched_method_unknown_params(p_method)) {
  1284. return true;
  1285. }
  1286. top = top->get_parent_class();
  1287. }
  1288. return false;
  1289. }
  1290. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1291. if (!script.is_valid())
  1292. ERR_FAIL_V(Variant());
  1293. GD_MONO_SCOPE_THREAD_ATTACH;
  1294. MonoObject *mono_object = get_mono_object();
  1295. if (!mono_object) {
  1296. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1297. ERR_FAIL_V(Variant());
  1298. }
  1299. GDMonoClass *top = script->script_class;
  1300. while (top && top != script->native) {
  1301. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1302. if (method) {
  1303. MonoObject *return_value = method->invoke(mono_object, p_args);
  1304. r_error.error = Variant::CallError::CALL_OK;
  1305. if (return_value) {
  1306. return GDMonoMarshal::mono_object_to_variant(return_value);
  1307. } else {
  1308. return Variant();
  1309. }
  1310. }
  1311. top = top->get_parent_class();
  1312. }
  1313. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1314. return Variant();
  1315. }
  1316. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1317. GD_MONO_SCOPE_THREAD_ATTACH;
  1318. if (script.is_valid()) {
  1319. MonoObject *mono_object = get_mono_object();
  1320. ERR_FAIL_NULL(mono_object);
  1321. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  1322. }
  1323. }
  1324. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  1325. GD_MONO_ASSERT_THREAD_ATTACHED;
  1326. GDMonoClass *top = script->script_class;
  1327. while (top && top != script->native) {
  1328. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1329. if (method) {
  1330. method->invoke(p_mono_object, p_args);
  1331. return;
  1332. }
  1333. top = top->get_parent_class();
  1334. }
  1335. }
  1336. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1337. // Sorry, the method is the one that controls the call order
  1338. call_multilevel(p_method, p_args, p_argcount);
  1339. }
  1340. bool CSharpInstance::_reference_owner_unsafe() {
  1341. #ifdef DEBUG_ENABLED
  1342. CRASH_COND(!base_ref);
  1343. CRASH_COND(owner == NULL);
  1344. CRASH_COND(unsafe_referenced); // already referenced
  1345. #endif
  1346. // Unsafe refcount increment. The managed instance also counts as a reference.
  1347. // This way if the unmanaged world has no references to our owner
  1348. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1349. // See: _unreference_owner_unsafe()
  1350. // May not me referenced yet, so we must use init_ref() instead of reference()
  1351. if (static_cast<Reference *>(owner)->init_ref()) {
  1352. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1353. unsafe_referenced = true;
  1354. }
  1355. return unsafe_referenced;
  1356. }
  1357. bool CSharpInstance::_unreference_owner_unsafe() {
  1358. #ifdef DEBUG_ENABLED
  1359. CRASH_COND(!base_ref);
  1360. CRASH_COND(owner == NULL);
  1361. #endif
  1362. if (!unsafe_referenced)
  1363. return false; // Already unreferenced
  1364. unsafe_referenced = false;
  1365. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1366. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1367. // See: _reference_owner_unsafe()
  1368. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1369. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1370. return static_cast<Reference *>(owner)->unreference();
  1371. }
  1372. MonoObject *CSharpInstance::_internal_new_managed() {
  1373. #ifdef DEBUG_ENABLED
  1374. CRASH_COND(!gchandle.is_valid());
  1375. #endif
  1376. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  1377. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1378. ERR_FAIL_NULL_V_MSG(ctor, NULL,
  1379. "Cannot create script instance because the class does not define a parameterless constructor: '" + script->get_path() + "'.");
  1380. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1381. ERR_FAIL_NULL_V(owner, NULL);
  1382. ERR_FAIL_COND_V(script.is_null(), NULL);
  1383. MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());
  1384. if (!mono_object) {
  1385. // Important to clear this before destroying the script instance here
  1386. script = Ref<CSharpScript>();
  1387. bool die = _unreference_owner_unsafe();
  1388. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  1389. CRASH_COND(die == true);
  1390. owner = NULL;
  1391. ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object.");
  1392. }
  1393. // Tie managed to unmanaged
  1394. gchandle = MonoGCHandle::create_strong(mono_object);
  1395. if (base_ref)
  1396. _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1397. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
  1398. // Construct
  1399. ctor->invoke_raw(mono_object, NULL);
  1400. return mono_object;
  1401. }
  1402. void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
  1403. #ifdef DEBUG_ENABLED
  1404. CRASH_COND(base_ref);
  1405. CRASH_COND(gchandle.is_null());
  1406. #endif
  1407. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1408. }
  1409. void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1410. #ifdef DEBUG_ENABLED
  1411. CRASH_COND(!base_ref);
  1412. CRASH_COND(gchandle.is_null());
  1413. #endif
  1414. r_remove_script_instance = false;
  1415. if (_unreference_owner_unsafe()) {
  1416. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1417. r_delete_owner = true;
  1418. } else {
  1419. r_delete_owner = false;
  1420. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1421. if (!p_is_finalizer) {
  1422. // If the native instance is still alive and Dispose() was called
  1423. // (instead of the finalizer), then we remove the script instance.
  1424. r_remove_script_instance = true;
  1425. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1426. // If the native instance is still alive and this is called from the finalizer,
  1427. // then it was referenced from another thread before the finalizer could
  1428. // unreference and delete it, so we want to keep it.
  1429. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1430. // could have already been collected. Instead we will create a new managed instance here.
  1431. MonoObject *new_managed = _internal_new_managed();
  1432. if (!new_managed) {
  1433. r_remove_script_instance = true;
  1434. }
  1435. }
  1436. }
  1437. }
  1438. void CSharpInstance::refcount_incremented() {
  1439. #ifdef DEBUG_ENABLED
  1440. CRASH_COND(!base_ref);
  1441. CRASH_COND(owner == NULL);
  1442. #endif
  1443. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1444. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1445. GD_MONO_SCOPE_THREAD_ATTACH;
  1446. // The reference count was increased after the managed side was the only one referencing our owner.
  1447. // This means the owner is being referenced again by the unmanaged side,
  1448. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1449. // Release the current weak handle and replace it with a strong handle.
  1450. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target());
  1451. gchandle->release();
  1452. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1453. }
  1454. }
  1455. bool CSharpInstance::refcount_decremented() {
  1456. #ifdef DEBUG_ENABLED
  1457. CRASH_COND(!base_ref);
  1458. CRASH_COND(owner == NULL);
  1459. #endif
  1460. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1461. int refcount = ref_owner->reference_get_count();
  1462. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1463. GD_MONO_SCOPE_THREAD_ATTACH;
  1464. // If owner owner is no longer referenced by the unmanaged side,
  1465. // the managed instance takes responsibility of deleting the owner when GCed.
  1466. // Release the current strong handle and replace it with a weak handle.
  1467. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target());
  1468. gchandle->release();
  1469. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1470. return false;
  1471. }
  1472. ref_dying = (refcount == 0);
  1473. return ref_dying;
  1474. }
  1475. MultiplayerAPI::RPCMode CSharpInstance::_member_get_rpc_mode(IMonoClassMember *p_member) const {
  1476. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  1477. return MultiplayerAPI::RPC_MODE_REMOTE;
  1478. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  1479. return MultiplayerAPI::RPC_MODE_MASTER;
  1480. if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
  1481. return MultiplayerAPI::RPC_MODE_PUPPET;
  1482. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  1483. return MultiplayerAPI::RPC_MODE_PUPPET;
  1484. if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
  1485. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1486. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  1487. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1488. if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
  1489. return MultiplayerAPI::RPC_MODE_MASTERSYNC;
  1490. if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
  1491. return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
  1492. return MultiplayerAPI::RPC_MODE_DISABLED;
  1493. }
  1494. MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  1495. GD_MONO_SCOPE_THREAD_ATTACH;
  1496. GDMonoClass *top = script->script_class;
  1497. while (top && top != script->native) {
  1498. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  1499. if (method && !method->is_static())
  1500. return _member_get_rpc_mode(method);
  1501. top = top->get_parent_class();
  1502. }
  1503. return MultiplayerAPI::RPC_MODE_DISABLED;
  1504. }
  1505. MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  1506. GD_MONO_SCOPE_THREAD_ATTACH;
  1507. GDMonoClass *top = script->script_class;
  1508. while (top && top != script->native) {
  1509. GDMonoField *field = top->get_field(p_variable);
  1510. if (field && !field->is_static())
  1511. return _member_get_rpc_mode(field);
  1512. GDMonoProperty *property = top->get_property(p_variable);
  1513. if (property && !property->is_static())
  1514. return _member_get_rpc_mode(property);
  1515. top = top->get_parent_class();
  1516. }
  1517. return MultiplayerAPI::RPC_MODE_DISABLED;
  1518. }
  1519. void CSharpInstance::notification(int p_notification) {
  1520. GD_MONO_SCOPE_THREAD_ATTACH;
  1521. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1522. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1523. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1524. // to be sent at least once, which happens right before the call to the destructor.
  1525. predelete_notified = true;
  1526. if (base_ref) {
  1527. // It's not safe to proceed if the owner derives Reference and the refcount reached 0.
  1528. // At this point, Dispose() was already called (manually or from the finalizer) so
  1529. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1530. // managed side references it and Dispose() needs to be called to release it.
  1531. // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
  1532. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1533. return;
  1534. }
  1535. _call_notification(p_notification);
  1536. MonoObject *mono_object = get_mono_object();
  1537. ERR_FAIL_NULL(mono_object);
  1538. MonoException *exc = NULL;
  1539. GDMonoUtils::dispose(mono_object, &exc);
  1540. if (exc) {
  1541. GDMonoUtils::set_pending_exception(exc);
  1542. }
  1543. return;
  1544. }
  1545. _call_notification(p_notification);
  1546. }
  1547. void CSharpInstance::_call_notification(int p_notification) {
  1548. GD_MONO_ASSERT_THREAD_ATTACHED;
  1549. MonoObject *mono_object = get_mono_object();
  1550. ERR_FAIL_NULL(mono_object);
  1551. // Custom version of _call_multilevel, optimized for _notification
  1552. uint32_t arg = p_notification;
  1553. void *args[1] = { &arg };
  1554. StringName method_name = CACHED_STRING_NAME(_notification);
  1555. GDMonoClass *top = script->script_class;
  1556. while (top && top != script->native) {
  1557. GDMonoMethod *method = top->get_method(method_name, 1);
  1558. if (method) {
  1559. method->invoke_raw(mono_object, args);
  1560. return;
  1561. }
  1562. top = top->get_parent_class();
  1563. }
  1564. }
  1565. String CSharpInstance::to_string(bool *r_valid) {
  1566. GD_MONO_SCOPE_THREAD_ATTACH;
  1567. MonoObject *mono_object = get_mono_object();
  1568. if (mono_object == NULL) {
  1569. if (r_valid)
  1570. *r_valid = false;
  1571. return String();
  1572. }
  1573. MonoException *exc = NULL;
  1574. MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc);
  1575. if (exc) {
  1576. GDMonoUtils::set_pending_exception(exc);
  1577. if (r_valid)
  1578. *r_valid = false;
  1579. return String();
  1580. }
  1581. if (result == NULL) {
  1582. if (r_valid)
  1583. *r_valid = false;
  1584. return String();
  1585. }
  1586. return GDMonoMarshal::mono_string_to_godot(result);
  1587. }
  1588. Ref<Script> CSharpInstance::get_script() const {
  1589. return script;
  1590. }
  1591. ScriptLanguage *CSharpInstance::get_language() {
  1592. return CSharpLanguage::get_singleton();
  1593. }
  1594. CSharpInstance::CSharpInstance() :
  1595. owner(NULL),
  1596. base_ref(false),
  1597. ref_dying(false),
  1598. unsafe_referenced(false),
  1599. predelete_notified(false),
  1600. destructing_script_instance(false) {
  1601. }
  1602. CSharpInstance::~CSharpInstance() {
  1603. GD_MONO_SCOPE_THREAD_ATTACH;
  1604. destructing_script_instance = true;
  1605. if (gchandle.is_valid()) {
  1606. if (!predelete_notified && !ref_dying) {
  1607. // This destructor is not called from the owners destructor.
  1608. // This could be being called from the owner's set_script_instance method,
  1609. // meaning this script is being replaced with another one. If this is the case,
  1610. // we must call Dispose here, because Dispose calls owner->set_script_instance(NULL)
  1611. // and that would mess up with the new script instance if called later.
  1612. MonoObject *mono_object = gchandle->get_target();
  1613. if (mono_object) {
  1614. MonoException *exc = NULL;
  1615. GDMonoUtils::dispose(mono_object, &exc);
  1616. if (exc) {
  1617. GDMonoUtils::set_pending_exception(exc);
  1618. }
  1619. }
  1620. }
  1621. gchandle->release(); // Make sure the gchandle is released
  1622. }
  1623. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1624. if (base_ref && !ref_dying && owner && unsafe_referenced) {
  1625. // The owner's script or script instance is being replaced (or removed)
  1626. // Transfer ownership to an "instance binding"
  1627. void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  1628. CRASH_COND(data == NULL);
  1629. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1630. if (!script_binding.inited) {
  1631. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1632. if (!script_binding.inited) { // Other thread may have set it up
  1633. // Already had a binding that needs to be setup
  1634. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner);
  1635. CRASH_COND(!script_binding.inited);
  1636. }
  1637. }
  1638. bool die = _unreference_owner_unsafe();
  1639. CRASH_COND(die == true); // The "instance binding" should be holding a reference
  1640. }
  1641. if (script.is_valid() && owner) {
  1642. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1643. #ifdef DEBUG_ENABLED
  1644. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1645. Set<Object *>::Element *match = script->instances.find(owner);
  1646. CRASH_COND(!match);
  1647. script->instances.erase(match);
  1648. #else
  1649. script->instances.erase(owner);
  1650. #endif
  1651. }
  1652. }
  1653. #ifdef TOOLS_ENABLED
  1654. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1655. placeholders.erase(p_placeholder);
  1656. }
  1657. #endif
  1658. #ifdef TOOLS_ENABLED
  1659. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1660. if (base_cache.is_valid()) {
  1661. base_cache->_update_exports_values(values, propnames);
  1662. }
  1663. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1664. values[E->key()] = E->get();
  1665. }
  1666. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1667. propnames.push_back(E->get());
  1668. }
  1669. }
  1670. void CSharpScript::_update_member_info_no_exports() {
  1671. if (exports_invalidated) {
  1672. GD_MONO_ASSERT_THREAD_ATTACHED;
  1673. exports_invalidated = false;
  1674. member_info.clear();
  1675. GDMonoClass *top = script_class;
  1676. while (top && top != native) {
  1677. PropertyInfo prop_info;
  1678. bool exported;
  1679. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1680. for (int i = fields.size() - 1; i >= 0; i--) {
  1681. GDMonoField *field = fields[i];
  1682. if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
  1683. StringName member_name = field->get_name();
  1684. member_info[member_name] = prop_info;
  1685. exported_members_cache.push_front(prop_info);
  1686. exported_members_defval_cache[member_name] = Variant();
  1687. }
  1688. }
  1689. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1690. for (int i = properties.size() - 1; i >= 0; i--) {
  1691. GDMonoProperty *property = properties[i];
  1692. if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
  1693. StringName member_name = property->get_name();
  1694. member_info[member_name] = prop_info;
  1695. exported_members_cache.push_front(prop_info);
  1696. exported_members_defval_cache[member_name] = Variant();
  1697. }
  1698. }
  1699. top = top->get_parent_class();
  1700. }
  1701. }
  1702. }
  1703. #endif
  1704. bool CSharpScript::_update_exports() {
  1705. #ifdef TOOLS_ENABLED
  1706. if (!Engine::get_singleton()->is_editor_hint())
  1707. return false;
  1708. placeholder_fallback_enabled = true; // until proven otherwise
  1709. if (!valid)
  1710. return false;
  1711. bool changed = false;
  1712. if (exports_invalidated) {
  1713. GD_MONO_SCOPE_THREAD_ATTACH;
  1714. exports_invalidated = false;
  1715. changed = true;
  1716. member_info.clear();
  1717. exported_members_cache.clear();
  1718. exported_members_defval_cache.clear();
  1719. // Here we create a temporary managed instance of the class to get the initial values
  1720. MonoObject *tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  1721. if (!tmp_object) {
  1722. ERR_PRINT("Failed to allocate temporary MonoObject.");
  1723. return false;
  1724. }
  1725. uint32_t tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed)
  1726. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1727. ERR_FAIL_NULL_V_MSG(ctor, NULL,
  1728. "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");
  1729. MonoException *ctor_exc = NULL;
  1730. ctor->invoke(tmp_object, NULL, &ctor_exc);
  1731. Object *tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));
  1732. if (ctor_exc) {
  1733. // TODO: Should we free 'tmp_native' if the exception was thrown after its creation?
  1734. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1735. tmp_object = NULL;
  1736. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1737. GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
  1738. return false;
  1739. }
  1740. GDMonoClass *top = script_class;
  1741. while (top && top != native) {
  1742. PropertyInfo prop_info;
  1743. bool exported;
  1744. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1745. for (int i = fields.size() - 1; i >= 0; i--) {
  1746. GDMonoField *field = fields[i];
  1747. if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
  1748. StringName member_name = field->get_name();
  1749. if (exported) {
  1750. member_info[member_name] = prop_info;
  1751. exported_members_cache.push_front(prop_info);
  1752. if (tmp_object) {
  1753. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1754. }
  1755. } else {
  1756. member_info[member_name] = prop_info;
  1757. }
  1758. }
  1759. }
  1760. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1761. for (int i = properties.size() - 1; i >= 0; i--) {
  1762. GDMonoProperty *property = properties[i];
  1763. if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
  1764. StringName member_name = property->get_name();
  1765. if (exported) {
  1766. member_info[member_name] = prop_info;
  1767. exported_members_cache.push_front(prop_info);
  1768. if (tmp_object) {
  1769. MonoException *exc = NULL;
  1770. MonoObject *ret = property->get_value(tmp_object, &exc);
  1771. if (exc) {
  1772. exported_members_defval_cache[member_name] = Variant();
  1773. GDMonoUtils::debug_print_unhandled_exception(exc);
  1774. } else {
  1775. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
  1776. }
  1777. }
  1778. } else {
  1779. member_info[member_name] = prop_info;
  1780. }
  1781. }
  1782. }
  1783. top = top->get_parent_class();
  1784. }
  1785. // Dispose the temporary managed instance
  1786. MonoException *exc = NULL;
  1787. GDMonoUtils::dispose(tmp_object, &exc);
  1788. if (exc) {
  1789. ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
  1790. GDMonoUtils::debug_print_unhandled_exception(exc);
  1791. }
  1792. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1793. tmp_object = NULL;
  1794. if (tmp_native && !Object::cast_to<Reference>(tmp_native)) {
  1795. Node *node = Object::cast_to<Node>(tmp_native);
  1796. if (node && node->is_inside_tree()) {
  1797. ERR_PRINTS("Temporary instance was added to the scene tree.");
  1798. } else {
  1799. memdelete(tmp_native);
  1800. }
  1801. }
  1802. }
  1803. placeholder_fallback_enabled = false;
  1804. if (placeholders.size()) {
  1805. // Update placeholders if any
  1806. Map<StringName, Variant> values;
  1807. List<PropertyInfo> propnames;
  1808. _update_exports_values(values, propnames);
  1809. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1810. E->get()->update(propnames, values);
  1811. }
  1812. }
  1813. return changed;
  1814. #endif
  1815. return false;
  1816. }
  1817. void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
  1818. // no need to load the script's signals more than once
  1819. if (!signals_invalidated) {
  1820. return;
  1821. }
  1822. // make sure this classes signals are empty when loading for the first time
  1823. _signals.clear();
  1824. GD_MONO_SCOPE_THREAD_ATTACH;
  1825. GDMonoClass *top = p_class;
  1826. while (top && top != p_native_class) {
  1827. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1828. for (int i = delegates.size() - 1; i >= 0; --i) {
  1829. Vector<Argument> parameters;
  1830. GDMonoClass *delegate = delegates[i];
  1831. if (_get_signal(top, delegate, parameters)) {
  1832. _signals[delegate->get_name()] = parameters;
  1833. }
  1834. }
  1835. top = top->get_parent_class();
  1836. }
  1837. signals_invalidated = false;
  1838. }
  1839. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1840. GD_MONO_ASSERT_THREAD_ATTACHED;
  1841. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1842. MonoType *raw_type = p_delegate->get_mono_type();
  1843. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1844. // Arguments are accessibles as arguments of .Invoke method
  1845. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1846. Vector<StringName> names;
  1847. Vector<ManagedType> types;
  1848. invoke->get_parameter_names(names);
  1849. invoke->get_parameter_types(types);
  1850. if (names.size() == types.size()) {
  1851. for (int i = 0; i < names.size(); ++i) {
  1852. Argument arg;
  1853. arg.name = names[i];
  1854. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1855. if (arg.type == Variant::NIL) {
  1856. ERR_PRINTS("Unknown type of signal parameter: '" + arg.name + "' in '" + p_class->get_full_name() + "'.");
  1857. return false;
  1858. }
  1859. params.push_back(arg);
  1860. }
  1861. return true;
  1862. }
  1863. }
  1864. }
  1865. return false;
  1866. }
  1867. #ifdef TOOLS_ENABLED
  1868. /**
  1869. * Returns false if there was an error, otherwise true.
  1870. * If there was an error, r_prop_info and r_exported are not assigned any value.
  1871. */
  1872. bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
  1873. GD_MONO_ASSERT_THREAD_ATTACHED;
  1874. // Goddammit, C++. All I wanted was some nested functions.
  1875. #define MEMBER_FULL_QUALIFIED_NAME(m_member) \
  1876. (m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())
  1877. if (p_member->is_static()) {
  1878. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1879. ERR_PRINTS("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1880. return false;
  1881. }
  1882. if (member_info.has(p_member->get_name()))
  1883. return false;
  1884. ManagedType type;
  1885. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
  1886. type = static_cast<GDMonoField *>(p_member)->get_type();
  1887. } else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1888. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1889. } else {
  1890. CRASH_NOW();
  1891. }
  1892. bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));
  1893. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1894. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1895. if (!property->has_getter()) {
  1896. if (exported)
  1897. ERR_PRINTS("Read-only property cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1898. return false;
  1899. }
  1900. if (!property->has_setter()) {
  1901. if (exported)
  1902. ERR_PRINTS("Write-only property (without getter) cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1903. return false;
  1904. }
  1905. }
  1906. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1907. if (!p_inspect_export || !exported) {
  1908. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1909. r_exported = false;
  1910. return true;
  1911. }
  1912. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1913. PropertyHint hint = PROPERTY_HINT_NONE;
  1914. String hint_string;
  1915. if (variant_type == Variant::NIL) {
  1916. ERR_PRINTS("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1917. return false;
  1918. }
  1919. int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);
  1920. ERR_FAIL_COND_V_MSG(hint_res == -1, false,
  1921. "Error while trying to determine information about the exported member: '" +
  1922. MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1923. if (hint_res == 0) {
  1924. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1925. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1926. }
  1927. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1928. r_exported = true;
  1929. return true;
  1930. #undef MEMBER_FULL_QUALIFIED_NAME
  1931. }
  1932. int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) {
  1933. GD_MONO_ASSERT_THREAD_ATTACHED;
  1934. if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) {
  1935. r_hint = PROPERTY_HINT_ENUM;
  1936. Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields();
  1937. MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr());
  1938. String name_only_hint_string;
  1939. // True: enum Foo { Bar, Baz, Quux }
  1940. // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
  1941. // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
  1942. bool uses_default_values = true;
  1943. for (int i = 0; i < fields.size(); i++) {
  1944. MonoClassField *field = fields[i];
  1945. if (i > 0) {
  1946. r_hint_string += ",";
  1947. name_only_hint_string += ",";
  1948. }
  1949. String enum_field_name = mono_field_get_name(field);
  1950. r_hint_string += enum_field_name;
  1951. name_only_hint_string += enum_field_name;
  1952. // TODO:
  1953. // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
  1954. // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
  1955. MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL);
  1956. ERR_FAIL_NULL_V_MSG(val_obj, -1, "Failed to get '" + enum_field_name + "' constant enum value.");
  1957. bool r_error;
  1958. uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
  1959. ERR_FAIL_COND_V_MSG(r_error, -1, "Failed to unbox '" + enum_field_name + "' constant enum value.");
  1960. if (val != (unsigned int)i) {
  1961. uses_default_values = false;
  1962. }
  1963. r_hint_string += ":";
  1964. r_hint_string += String::num_uint64(val);
  1965. }
  1966. if (uses_default_values) {
  1967. // If we use the format NAME:VAL, that's what the editor displays.
  1968. // That's annoying if the user is not using custom values for the enum constants.
  1969. // This may not be needed in the future if the editor is changed to not display values.
  1970. r_hint_string = name_only_hint_string;
  1971. }
  1972. } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) {
  1973. GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
  1974. CRASH_COND(field_native_class == NULL);
  1975. r_hint = PROPERTY_HINT_RESOURCE_TYPE;
  1976. r_hint_string = NATIVE_GDMONOCLASS_NAME(field_native_class);
  1977. } else if (p_allow_generics && p_variant_type == Variant::ARRAY) {
  1978. // Nested arrays are not supported in the inspector
  1979. ManagedType elem_type;
  1980. if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type))
  1981. return 0;
  1982. Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);
  1983. PropertyHint elem_hint = PROPERTY_HINT_NONE;
  1984. String elem_hint_string;
  1985. ERR_FAIL_COND_V_MSG(elem_variant_type == Variant::NIL, -1, "Unknown array element type.");
  1986. int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string);
  1987. ERR_FAIL_COND_V_MSG(hint_res == -1, -1, "Error while trying to determine information about the array element type.");
  1988. // Format: type/hint:hint_string
  1989. r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string;
  1990. r_hint = PROPERTY_HINT_TYPE_STRING;
  1991. } else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) {
  1992. // TODO: Dictionaries are not supported in the inspector
  1993. } else {
  1994. return 0;
  1995. }
  1996. return 1;
  1997. }
  1998. #endif
  1999. void CSharpScript::_clear() {
  2000. tool = false;
  2001. valid = false;
  2002. base = NULL;
  2003. native = NULL;
  2004. script_class = NULL;
  2005. }
  2006. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  2007. if (unlikely(GDMono::get_singleton() == NULL)) {
  2008. // Probably not the best error but eh.
  2009. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  2010. return Variant();
  2011. }
  2012. GD_MONO_SCOPE_THREAD_ATTACH;
  2013. GDMonoClass *top = script_class;
  2014. while (top && top != native) {
  2015. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  2016. if (method && method->is_static()) {
  2017. MonoObject *result = method->invoke(NULL, p_args);
  2018. if (result) {
  2019. return GDMonoMarshal::mono_object_to_variant(result);
  2020. } else {
  2021. return Variant();
  2022. }
  2023. }
  2024. top = top->get_parent_class();
  2025. }
  2026. // No static method found. Try regular instance calls
  2027. return Script::call(p_method, p_args, p_argcount, r_error);
  2028. }
  2029. void CSharpScript::_resource_path_changed() {
  2030. String path = get_path();
  2031. if (!path.empty()) {
  2032. name = get_path().get_file().get_basename();
  2033. }
  2034. }
  2035. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  2036. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  2037. r_ret = get_source_code();
  2038. return true;
  2039. }
  2040. return false;
  2041. }
  2042. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  2043. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  2044. set_source_code(p_value);
  2045. reload();
  2046. return true;
  2047. }
  2048. return false;
  2049. }
  2050. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  2051. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  2052. }
  2053. void CSharpScript::_bind_methods() {
  2054. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  2055. }
  2056. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
  2057. // This method should not fail, only assertions allowed
  2058. CRASH_COND(p_class == NULL);
  2059. // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
  2060. Ref<CSharpScript> script = memnew(CSharpScript);
  2061. initialize_for_managed_type(script, p_class, p_native);
  2062. return script;
  2063. }
  2064. void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) {
  2065. // This method should not fail, only assertions allowed
  2066. CRASH_COND(p_class == NULL);
  2067. p_script->name = p_class->get_name();
  2068. p_script->script_class = p_class;
  2069. p_script->native = p_native;
  2070. CRASH_COND(p_script->native == NULL);
  2071. GDMonoClass *base = p_script->script_class->get_parent_class();
  2072. if (base != p_script->native)
  2073. p_script->base = base;
  2074. p_script->valid = true;
  2075. p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2076. if (!p_script->tool) {
  2077. GDMonoClass *nesting_class = p_script->script_class->get_nesting_class();
  2078. p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2079. }
  2080. #if TOOLS_ENABLED
  2081. if (!p_script->tool) {
  2082. p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2083. }
  2084. #endif
  2085. #ifdef DEBUG_ENABLED
  2086. // For debug builds, we must fetch from all native base methods as well.
  2087. // Native base methods must be fetched before the current class.
  2088. // Not needed if the script class itself is a native class.
  2089. if (p_script->script_class != p_script->native) {
  2090. GDMonoClass *native_top = p_script->native;
  2091. while (native_top) {
  2092. native_top->fetch_methods_with_godot_api_checks(p_script->native);
  2093. if (native_top == CACHED_CLASS(GodotObject))
  2094. break;
  2095. native_top = native_top->get_parent_class();
  2096. }
  2097. }
  2098. #endif
  2099. p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);
  2100. // Need to fetch method from base classes as well
  2101. GDMonoClass *top = p_script->script_class;
  2102. while (top && top != p_script->native) {
  2103. top->fetch_methods_with_godot_api_checks(p_script->native);
  2104. top = top->get_parent_class();
  2105. }
  2106. p_script->load_script_signals(p_script->script_class, p_script->native);
  2107. #ifdef TOOLS_ENABLED
  2108. p_script->_update_member_info_no_exports();
  2109. #endif
  2110. }
  2111. bool CSharpScript::can_instance() const {
  2112. #ifdef TOOLS_ENABLED
  2113. if (Engine::get_singleton()->is_editor_hint()) {
  2114. // Hack to lower the risk of attached scripts not being added to the C# project
  2115. if (!get_path().empty() && get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  2116. if (_create_project_solution_if_needed()) {
  2117. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2118. "Compile",
  2119. ProjectSettings::get_singleton()->globalize_path(get_path()));
  2120. } else {
  2121. ERR_PRINTS("C# project could not be created; cannot add file: '" + get_path() + "'.");
  2122. }
  2123. }
  2124. }
  2125. #endif
  2126. #ifdef TOOLS_ENABLED
  2127. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  2128. #else
  2129. bool extra_cond = true;
  2130. #endif
  2131. // FIXME Need to think this through better.
  2132. // For tool scripts, this will never fire if the class is not found. That's because we
  2133. // don't know if it's a tool script if we can't find the class to access the attributes.
  2134. if (extra_cond && !script_class) {
  2135. if (GDMono::get_singleton()->get_project_assembly() == NULL) {
  2136. // The project assembly is not loaded
  2137. ERR_FAIL_V_MSG(NULL, "Cannot instance script because the project assembly is not loaded. Script: '" + get_path() + "'.");
  2138. } else {
  2139. // The project assembly is loaded, but the class could not found
  2140. ERR_FAIL_V_MSG(NULL, "Cannot instance script because the class '" + name + "' could not be found. Script: '" + get_path() + "'.");
  2141. }
  2142. }
  2143. return valid && extra_cond;
  2144. }
  2145. StringName CSharpScript::get_instance_base_type() const {
  2146. if (native)
  2147. return native->get_name();
  2148. else
  2149. return StringName();
  2150. }
  2151. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  2152. GD_MONO_ASSERT_THREAD_ATTACHED;
  2153. /* STEP 1, CREATE */
  2154. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  2155. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  2156. if (ctor == NULL) {
  2157. ERR_FAIL_COND_V_MSG(p_argcount == 0, NULL,
  2158. "Cannot create script instance. The class '" + script_class->get_full_name() +
  2159. "' does not define a parameterless constructor." +
  2160. (get_path().empty() ? String() : " Path: '" + get_path() + "'."));
  2161. ERR_FAIL_V_MSG(NULL, "Constructor not found.");
  2162. }
  2163. Ref<Reference> ref;
  2164. if (p_isref) {
  2165. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  2166. ref = Ref<Reference>(static_cast<Reference *>(p_owner));
  2167. }
  2168. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  2169. if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) {
  2170. void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  2171. CRASH_COND(data == NULL);
  2172. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  2173. if (script_binding.inited && script_binding.gchandle.is_valid()) {
  2174. MonoObject *mono_object = script_binding.gchandle->get_target();
  2175. if (mono_object) {
  2176. MonoException *exc = NULL;
  2177. GDMonoUtils::dispose(mono_object, &exc);
  2178. if (exc) {
  2179. GDMonoUtils::set_pending_exception(exc);
  2180. }
  2181. }
  2182. script_binding.inited = false;
  2183. }
  2184. }
  2185. CSharpInstance *instance = memnew(CSharpInstance);
  2186. instance->base_ref = p_isref;
  2187. instance->script = Ref<CSharpScript>(this);
  2188. instance->owner = p_owner;
  2189. instance->owner->set_script_instance(instance);
  2190. /* STEP 2, INITIALIZE AND CONSTRUCT */
  2191. MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  2192. if (!mono_object) {
  2193. // Important to clear this before destroying the script instance here
  2194. instance->script = Ref<CSharpScript>();
  2195. instance->owner = NULL;
  2196. bool die = instance->_unreference_owner_unsafe();
  2197. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  2198. CRASH_COND(die == true);
  2199. p_owner->set_script_instance(NULL);
  2200. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  2201. ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object.");
  2202. }
  2203. // Tie managed to unmanaged
  2204. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  2205. if (instance->base_ref)
  2206. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  2207. {
  2208. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2209. instances.insert(instance->owner);
  2210. }
  2211. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  2212. // Construct
  2213. ctor->invoke(mono_object, p_args);
  2214. /* STEP 3, PARTY */
  2215. //@TODO make thread safe
  2216. return instance;
  2217. }
  2218. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  2219. if (!valid) {
  2220. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  2221. return Variant();
  2222. }
  2223. r_error.error = Variant::CallError::CALL_OK;
  2224. ERR_FAIL_NULL_V(native, Variant());
  2225. GD_MONO_SCOPE_THREAD_ATTACH;
  2226. Object *owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  2227. REF ref;
  2228. Reference *r = Object::cast_to<Reference>(owner);
  2229. if (r) {
  2230. ref = REF(r);
  2231. }
  2232. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  2233. if (!instance) {
  2234. if (ref.is_null()) {
  2235. memdelete(owner); //no owner, sorry
  2236. }
  2237. return Variant();
  2238. }
  2239. if (ref.is_valid()) {
  2240. return ref;
  2241. } else {
  2242. return owner;
  2243. }
  2244. }
  2245. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  2246. #ifdef DEBUG_ENABLED
  2247. CRASH_COND(!valid);
  2248. #endif
  2249. if (native) {
  2250. String native_name = NATIVE_GDMONOCLASS_NAME(native);
  2251. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  2252. if (ScriptDebugger::get_singleton()) {
  2253. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  2254. }
  2255. ERR_FAIL_V_MSG(NULL, "Script inherits from native type '" + native_name +
  2256. "', so it can't be instanced in object of type: '" + p_this->get_class() + "'.");
  2257. }
  2258. }
  2259. GD_MONO_SCOPE_THREAD_ATTACH;
  2260. Variant::CallError unchecked_error;
  2261. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error);
  2262. }
  2263. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  2264. #ifdef TOOLS_ENABLED
  2265. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  2266. placeholders.insert(si);
  2267. _update_exports();
  2268. return si;
  2269. #else
  2270. return NULL;
  2271. #endif
  2272. }
  2273. bool CSharpScript::instance_has(const Object *p_this) const {
  2274. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2275. return instances.has((Object *)p_this);
  2276. }
  2277. bool CSharpScript::has_source_code() const {
  2278. return !source.empty();
  2279. }
  2280. String CSharpScript::get_source_code() const {
  2281. return source;
  2282. }
  2283. void CSharpScript::set_source_code(const String &p_code) {
  2284. if (source == p_code)
  2285. return;
  2286. source = p_code;
  2287. #ifdef TOOLS_ENABLED
  2288. source_changed_cache = true;
  2289. #endif
  2290. }
  2291. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  2292. if (!script_class)
  2293. return;
  2294. GD_MONO_SCOPE_THREAD_ATTACH;
  2295. // TODO: Filter out things unsuitable for explicit calls, like constructors.
  2296. const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
  2297. for (int i = 0; i < methods.size(); ++i) {
  2298. p_list->push_back(methods[i]->get_method_info());
  2299. }
  2300. }
  2301. bool CSharpScript::has_method(const StringName &p_method) const {
  2302. if (!script_class)
  2303. return false;
  2304. GD_MONO_SCOPE_THREAD_ATTACH;
  2305. return script_class->has_fetched_method_unknown_params(p_method);
  2306. }
  2307. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2308. if (!script_class)
  2309. return MethodInfo();
  2310. GD_MONO_SCOPE_THREAD_ATTACH;
  2311. GDMonoClass *top = script_class;
  2312. while (top && top != native) {
  2313. GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
  2314. if (params) {
  2315. return params->get_method_info();
  2316. }
  2317. top = top->get_parent_class();
  2318. }
  2319. return MethodInfo();
  2320. }
  2321. Error CSharpScript::reload(bool p_keep_state) {
  2322. bool has_instances;
  2323. {
  2324. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2325. has_instances = instances.size();
  2326. }
  2327. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  2328. GD_MONO_SCOPE_THREAD_ATTACH;
  2329. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  2330. if (project_assembly) {
  2331. const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path());
  2332. if (script_metadata_var) {
  2333. Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"];
  2334. const Variant *namespace_ = script_metadata.getptr("namespace");
  2335. const Variant *class_name = script_metadata.getptr("class_name");
  2336. ERR_FAIL_NULL_V(namespace_, ERR_BUG);
  2337. ERR_FAIL_NULL_V(class_name, ERR_BUG);
  2338. GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
  2339. if (klass) {
  2340. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass);
  2341. ERR_FAIL_COND_V(!obj_type, ERR_BUG);
  2342. script_class = klass;
  2343. }
  2344. } else {
  2345. // Missing script metadata. Fallback to legacy method
  2346. script_class = project_assembly->get_object_derived_class(name);
  2347. }
  2348. valid = script_class != NULL;
  2349. if (script_class) {
  2350. #ifdef DEBUG_ENABLED
  2351. print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
  2352. #endif
  2353. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2354. if (!tool) {
  2355. GDMonoClass *nesting_class = script_class->get_nesting_class();
  2356. tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2357. }
  2358. #if TOOLS_ENABLED
  2359. if (!tool) {
  2360. tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2361. }
  2362. #endif
  2363. native = GDMonoUtils::get_class_native_base(script_class);
  2364. CRASH_COND(native == NULL);
  2365. GDMonoClass *base_class = script_class->get_parent_class();
  2366. if (base_class != native)
  2367. base = base_class;
  2368. #ifdef DEBUG_ENABLED
  2369. // For debug builds, we must fetch from all native base methods as well.
  2370. // Native base methods must be fetched before the current class.
  2371. // Not needed if the script class itself is a native class.
  2372. if (script_class != native) {
  2373. GDMonoClass *native_top = native;
  2374. while (native_top) {
  2375. native_top->fetch_methods_with_godot_api_checks(native);
  2376. if (native_top == CACHED_CLASS(GodotObject))
  2377. break;
  2378. native_top = native_top->get_parent_class();
  2379. }
  2380. }
  2381. #endif
  2382. script_class->fetch_methods_with_godot_api_checks(native);
  2383. // Need to fetch method from base classes as well
  2384. GDMonoClass *top = script_class;
  2385. while (top && top != native) {
  2386. top->fetch_methods_with_godot_api_checks(native);
  2387. top = top->get_parent_class();
  2388. }
  2389. load_script_signals(script_class, native);
  2390. _update_exports();
  2391. }
  2392. return OK;
  2393. }
  2394. return ERR_FILE_MISSING_DEPENDENCIES;
  2395. }
  2396. ScriptLanguage *CSharpScript::get_language() const {
  2397. return CSharpLanguage::get_singleton();
  2398. }
  2399. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2400. #ifdef TOOLS_ENABLED
  2401. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  2402. if (E) {
  2403. r_value = E->get();
  2404. return true;
  2405. }
  2406. if (base_cache.is_valid()) {
  2407. return base_cache->get_property_default_value(p_property, r_value);
  2408. }
  2409. #endif
  2410. return false;
  2411. }
  2412. void CSharpScript::update_exports() {
  2413. #ifdef TOOLS_ENABLED
  2414. _update_exports();
  2415. #endif
  2416. }
  2417. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2418. return _signals.has(p_signal);
  2419. }
  2420. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2421. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  2422. MethodInfo mi;
  2423. mi.name = E->key();
  2424. for (int i = 0; i < E->get().size(); i++) {
  2425. PropertyInfo arg;
  2426. arg.name = E->get()[i].name;
  2427. mi.arguments.push_back(arg);
  2428. }
  2429. r_signals->push_back(mi);
  2430. }
  2431. }
  2432. Ref<Script> CSharpScript::get_base_script() const {
  2433. // TODO search in metadata file once we have it, not important any way?
  2434. return Ref<Script>();
  2435. }
  2436. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  2437. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  2438. p_list->push_back(E->value());
  2439. }
  2440. }
  2441. int CSharpScript::get_member_line(const StringName &p_member) const {
  2442. // TODO omnisharp
  2443. return -1;
  2444. }
  2445. Error CSharpScript::load_source_code(const String &p_path) {
  2446. Error ferr = read_all_file_utf8(p_path, source);
  2447. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2448. ferr == ERR_INVALID_DATA ?
  2449. "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2450. " Please ensure that scripts are saved in valid UTF-8 unicode." :
  2451. "Failed to read file: '" + p_path + "'.");
  2452. #ifdef TOOLS_ENABLED
  2453. source_changed_cache = true;
  2454. #endif
  2455. return OK;
  2456. }
  2457. StringName CSharpScript::get_script_name() const {
  2458. return name;
  2459. }
  2460. CSharpScript::CSharpScript() :
  2461. script_list(this) {
  2462. _clear();
  2463. #ifdef TOOLS_ENABLED
  2464. source_changed_cache = false;
  2465. placeholder_fallback_enabled = false;
  2466. exports_invalidated = true;
  2467. #endif
  2468. signals_invalidated = true;
  2469. _resource_path_changed();
  2470. #ifdef DEBUG_ENABLED
  2471. {
  2472. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2473. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2474. }
  2475. #endif
  2476. }
  2477. CSharpScript::~CSharpScript() {
  2478. #ifdef DEBUG_ENABLED
  2479. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2480. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2481. #endif
  2482. }
  2483. /*************** RESOURCE ***************/
  2484. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  2485. if (r_error)
  2486. *r_error = ERR_FILE_CANT_OPEN;
  2487. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2488. CSharpScript *script = memnew(CSharpScript);
  2489. Ref<CSharpScript> scriptres(script);
  2490. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2491. Error err = script->load_source_code(p_path);
  2492. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load C# script file '" + p_path + "'.");
  2493. #endif
  2494. script->set_path(p_original_path);
  2495. script->reload();
  2496. if (r_error)
  2497. *r_error = OK;
  2498. return scriptres;
  2499. }
  2500. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2501. p_extensions->push_back("cs");
  2502. }
  2503. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2504. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2505. }
  2506. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2507. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2508. }
  2509. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  2510. Ref<CSharpScript> sqscr = p_resource;
  2511. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2512. String source = sqscr->get_source_code();
  2513. #ifdef TOOLS_ENABLED
  2514. if (!FileAccess::exists(p_path)) {
  2515. // The file does not yet exists, let's assume the user just created this script
  2516. if (_create_project_solution_if_needed()) {
  2517. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2518. "Compile",
  2519. ProjectSettings::get_singleton()->globalize_path(p_path));
  2520. } else {
  2521. ERR_PRINTS("C# project could not be created; cannot add file: '" + p_path + "'.");
  2522. }
  2523. }
  2524. #endif
  2525. Error err;
  2526. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2527. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2528. file->store_string(source);
  2529. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2530. memdelete(file);
  2531. return ERR_CANT_CREATE;
  2532. }
  2533. file->close();
  2534. memdelete(file);
  2535. #ifdef TOOLS_ENABLED
  2536. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2537. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2538. }
  2539. #endif
  2540. return OK;
  2541. }
  2542. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  2543. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2544. p_extensions->push_back("cs");
  2545. }
  2546. }
  2547. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  2548. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  2549. }
  2550. CSharpLanguage::StringNameCache::StringNameCache() {
  2551. _signal_callback = StaticCString::create("_signal_callback");
  2552. _set = StaticCString::create("_set");
  2553. _get = StaticCString::create("_get");
  2554. _get_property_list = StaticCString::create("_get_property_list");
  2555. _notification = StaticCString::create("_notification");
  2556. _script_source = StaticCString::create("script/source");
  2557. on_before_serialize = StaticCString::create("OnBeforeSerialize");
  2558. on_after_deserialize = StaticCString::create("OnAfterDeserialize");
  2559. dotctor = StaticCString::create(".ctor");
  2560. }