gdscript.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080
  1. /**************************************************************************/
  2. /* gdscript.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdscript.h"
  31. #include "gdscript_analyzer.h"
  32. #include "gdscript_cache.h"
  33. #include "gdscript_compiler.h"
  34. #include "gdscript_parser.h"
  35. #include "gdscript_rpc_callable.h"
  36. #include "gdscript_tokenizer_buffer.h"
  37. #include "gdscript_warning.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "editor/gdscript_docgen.h"
  40. #endif
  41. #ifdef TESTS_ENABLED
  42. #include "tests/gdscript_test_runner.h"
  43. #endif
  44. #include "core/config/engine.h"
  45. #include "core/config/project_settings.h"
  46. #include "core/core_constants.h"
  47. #include "core/io/file_access.h"
  48. #include "core/io/file_access_encrypted.h"
  49. #include "core/os/os.h"
  50. #include "scene/resources/packed_scene.h"
  51. #include "scene/scene_string_names.h"
  52. #ifdef TOOLS_ENABLED
  53. #include "core/extension/gdextension_manager.h"
  54. #include "editor/editor_paths.h"
  55. #endif
  56. #include <stdint.h>
  57. ///////////////////////////
  58. GDScriptNativeClass::GDScriptNativeClass(const StringName &p_name) {
  59. name = p_name;
  60. }
  61. bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
  62. bool ok;
  63. int64_t v = ClassDB::get_integer_constant(name, p_name, &ok);
  64. if (ok) {
  65. r_ret = v;
  66. return true;
  67. } else {
  68. return false;
  69. }
  70. }
  71. void GDScriptNativeClass::_bind_methods() {
  72. ClassDB::bind_method(D_METHOD("new"), &GDScriptNativeClass::_new);
  73. }
  74. Variant GDScriptNativeClass::_new() {
  75. Object *o = instantiate();
  76. ERR_FAIL_NULL_V_MSG(o, Variant(), "Class type: '" + String(name) + "' is not instantiable.");
  77. RefCounted *rc = Object::cast_to<RefCounted>(o);
  78. if (rc) {
  79. return Ref<RefCounted>(rc);
  80. } else {
  81. return o;
  82. }
  83. }
  84. Object *GDScriptNativeClass::instantiate() {
  85. return ClassDB::instantiate_no_placeholders(name);
  86. }
  87. Variant GDScriptNativeClass::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  88. if (p_method == SNAME("new")) {
  89. // Constructor.
  90. return Object::callp(p_method, p_args, p_argcount, r_error);
  91. }
  92. MethodBind *method = ClassDB::get_method(name, p_method);
  93. if (method && method->is_static()) {
  94. // Native static method.
  95. return method->call(nullptr, p_args, p_argcount, r_error);
  96. }
  97. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  98. return Variant();
  99. }
  100. GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) {
  101. if (likely(p_script->valid) && p_script->initializer) {
  102. return p_script->initializer;
  103. } else {
  104. GDScript *base_src = p_script->_base;
  105. if (base_src != nullptr) {
  106. return _super_constructor(base_src);
  107. } else {
  108. return nullptr;
  109. }
  110. }
  111. }
  112. void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) {
  113. GDScript *base_src = p_script->_base;
  114. if (base_src != nullptr) {
  115. _super_implicit_constructor(base_src, p_instance, r_error);
  116. if (r_error.error != Callable::CallError::CALL_OK) {
  117. return;
  118. }
  119. }
  120. ERR_FAIL_NULL(p_script->implicit_initializer);
  121. if (likely(p_script->valid)) {
  122. p_script->implicit_initializer->call(p_instance, nullptr, 0, r_error);
  123. } else {
  124. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  125. }
  126. }
  127. GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
  128. /* STEP 1, CREATE */
  129. GDScriptInstance *instance = memnew(GDScriptInstance);
  130. instance->base_ref_counted = p_is_ref_counted;
  131. instance->members.resize(member_indices.size());
  132. instance->script = Ref<GDScript>(this);
  133. instance->owner = p_owner;
  134. instance->owner_id = p_owner->get_instance_id();
  135. #ifdef DEBUG_ENABLED
  136. //needed for hot reloading
  137. for (const KeyValue<StringName, MemberInfo> &E : member_indices) {
  138. instance->member_indices_cache[E.key] = E.value.index;
  139. }
  140. #endif
  141. instance->owner->set_script_instance(instance);
  142. /* STEP 2, INITIALIZE AND CONSTRUCT */
  143. {
  144. MutexLock lock(GDScriptLanguage::singleton->mutex);
  145. instances.insert(instance->owner);
  146. }
  147. _super_implicit_constructor(this, instance, r_error);
  148. if (r_error.error != Callable::CallError::CALL_OK) {
  149. String error_text = Variant::get_call_error_text(instance->owner, "@implicit_new", nullptr, 0, r_error);
  150. instance->script = Ref<GDScript>();
  151. instance->owner->set_script_instance(nullptr);
  152. {
  153. MutexLock lock(GDScriptLanguage::singleton->mutex);
  154. instances.erase(p_owner);
  155. }
  156. ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance: " + error_text);
  157. }
  158. if (p_argcount < 0) {
  159. return instance;
  160. }
  161. initializer = _super_constructor(this);
  162. if (initializer != nullptr) {
  163. initializer->call(instance, p_args, p_argcount, r_error);
  164. if (r_error.error != Callable::CallError::CALL_OK) {
  165. String error_text = Variant::get_call_error_text(instance->owner, "_init", p_args, p_argcount, r_error);
  166. instance->script = Ref<GDScript>();
  167. instance->owner->set_script_instance(nullptr);
  168. {
  169. MutexLock lock(GDScriptLanguage::singleton->mutex);
  170. instances.erase(p_owner);
  171. }
  172. ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance: " + error_text);
  173. }
  174. }
  175. //@TODO make thread safe
  176. return instance;
  177. }
  178. Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  179. /* STEP 1, CREATE */
  180. if (!valid) {
  181. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  182. return Variant();
  183. }
  184. r_error.error = Callable::CallError::CALL_OK;
  185. Ref<RefCounted> ref;
  186. Object *owner = nullptr;
  187. GDScript *_baseptr = this;
  188. while (_baseptr->_base) {
  189. _baseptr = _baseptr->_base;
  190. }
  191. ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant());
  192. if (_baseptr->native.ptr()) {
  193. owner = _baseptr->native->instantiate();
  194. } else {
  195. owner = memnew(RefCounted); //by default, no base means use reference
  196. }
  197. ERR_FAIL_NULL_V_MSG(owner, Variant(), "Can't inherit from a virtual class.");
  198. RefCounted *r = Object::cast_to<RefCounted>(owner);
  199. if (r) {
  200. ref = Ref<RefCounted>(r);
  201. }
  202. GDScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
  203. if (!instance) {
  204. if (ref.is_null()) {
  205. memdelete(owner); //no owner, sorry
  206. }
  207. return Variant();
  208. }
  209. if (ref.is_valid()) {
  210. return ref;
  211. } else {
  212. return owner;
  213. }
  214. }
  215. bool GDScript::can_instantiate() const {
  216. #ifdef TOOLS_ENABLED
  217. return valid && (tool || ScriptServer::is_scripting_enabled());
  218. #else
  219. return valid;
  220. #endif
  221. }
  222. Ref<Script> GDScript::get_base_script() const {
  223. if (_base) {
  224. return Ref<GDScript>(_base);
  225. } else {
  226. return Ref<Script>();
  227. }
  228. }
  229. StringName GDScript::get_global_name() const {
  230. return global_name;
  231. }
  232. StringName GDScript::get_instance_base_type() const {
  233. if (native.is_valid()) {
  234. return native->get_name();
  235. }
  236. if (base.is_valid() && base->is_valid()) {
  237. return base->get_instance_base_type();
  238. }
  239. return StringName();
  240. }
  241. struct _GDScriptMemberSort {
  242. int index = 0;
  243. StringName name;
  244. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
  245. };
  246. #ifdef TOOLS_ENABLED
  247. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  248. placeholders.erase(p_placeholder);
  249. }
  250. #endif
  251. void GDScript::_get_script_method_list(List<MethodInfo> *r_list, bool p_include_base) const {
  252. const GDScript *current = this;
  253. while (current) {
  254. for (const KeyValue<StringName, GDScriptFunction *> &E : current->member_functions) {
  255. r_list->push_back(E.value->get_method_info());
  256. }
  257. if (!p_include_base) {
  258. return;
  259. }
  260. current = current->_base;
  261. }
  262. }
  263. void GDScript::get_script_method_list(List<MethodInfo> *r_list) const {
  264. _get_script_method_list(r_list, true);
  265. }
  266. void GDScript::_get_script_property_list(List<PropertyInfo> *r_list, bool p_include_base) const {
  267. const GDScript *sptr = this;
  268. List<PropertyInfo> props;
  269. while (sptr) {
  270. Vector<_GDScriptMemberSort> msort;
  271. for (const KeyValue<StringName, MemberInfo> &E : sptr->member_indices) {
  272. if (!sptr->members.has(E.key)) {
  273. continue; // Skip base class members.
  274. }
  275. _GDScriptMemberSort ms;
  276. ms.index = E.value.index;
  277. ms.name = E.key;
  278. msort.push_back(ms);
  279. }
  280. msort.sort();
  281. msort.reverse();
  282. for (int i = 0; i < msort.size(); i++) {
  283. props.push_front(sptr->member_indices[msort[i].name].property_info);
  284. }
  285. #ifdef TOOLS_ENABLED
  286. r_list->push_back(sptr->get_class_category());
  287. #endif // TOOLS_ENABLED
  288. for (const PropertyInfo &E : props) {
  289. r_list->push_back(E);
  290. }
  291. if (!p_include_base) {
  292. break;
  293. }
  294. props.clear();
  295. sptr = sptr->_base;
  296. }
  297. }
  298. void GDScript::get_script_property_list(List<PropertyInfo> *r_list) const {
  299. _get_script_property_list(r_list, true);
  300. }
  301. bool GDScript::has_method(const StringName &p_method) const {
  302. return member_functions.has(p_method);
  303. }
  304. bool GDScript::has_static_method(const StringName &p_method) const {
  305. return member_functions.has(p_method) && member_functions[p_method]->is_static();
  306. }
  307. int GDScript::get_script_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  308. HashMap<StringName, GDScriptFunction *>::ConstIterator E = member_functions.find(p_method);
  309. if (!E) {
  310. if (r_is_valid) {
  311. *r_is_valid = false;
  312. }
  313. return 0;
  314. }
  315. if (r_is_valid) {
  316. *r_is_valid = true;
  317. }
  318. return E->value->get_argument_count();
  319. }
  320. MethodInfo GDScript::get_method_info(const StringName &p_method) const {
  321. HashMap<StringName, GDScriptFunction *>::ConstIterator E = member_functions.find(p_method);
  322. if (!E) {
  323. return MethodInfo();
  324. }
  325. return E->value->get_method_info();
  326. }
  327. bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  328. #ifdef TOOLS_ENABLED
  329. HashMap<StringName, Variant>::ConstIterator E = member_default_values_cache.find(p_property);
  330. if (E) {
  331. r_value = E->value;
  332. return true;
  333. }
  334. if (base_cache.is_valid()) {
  335. return base_cache->get_property_default_value(p_property, r_value);
  336. }
  337. #endif
  338. return false;
  339. }
  340. ScriptInstance *GDScript::instance_create(Object *p_this) {
  341. ERR_FAIL_COND_V_MSG(!valid, nullptr, "Script is invalid!");
  342. GDScript *top = this;
  343. while (top->_base) {
  344. top = top->_base;
  345. }
  346. if (top->native.is_valid()) {
  347. if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
  348. if (EngineDebugger::is_active()) {
  349. GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'");
  350. }
  351. ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type '" + p_this->get_class() + "'" + ".");
  352. }
  353. }
  354. Callable::CallError unchecked_error;
  355. return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error);
  356. }
  357. PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) {
  358. #ifdef TOOLS_ENABLED
  359. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
  360. placeholders.insert(si);
  361. _update_exports(nullptr, false, si);
  362. return si;
  363. #else
  364. return nullptr;
  365. #endif
  366. }
  367. bool GDScript::instance_has(const Object *p_this) const {
  368. MutexLock lock(GDScriptLanguage::singleton->mutex);
  369. return instances.has((Object *)p_this);
  370. }
  371. bool GDScript::has_source_code() const {
  372. return !source.is_empty();
  373. }
  374. String GDScript::get_source_code() const {
  375. return source;
  376. }
  377. void GDScript::set_source_code(const String &p_code) {
  378. if (source == p_code) {
  379. return;
  380. }
  381. source = p_code;
  382. #ifdef TOOLS_ENABLED
  383. source_changed_cache = true;
  384. #endif
  385. }
  386. #ifdef TOOLS_ENABLED
  387. void GDScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  388. for (const KeyValue<StringName, Variant> &E : member_default_values_cache) {
  389. values[E.key] = E.value;
  390. }
  391. for (const PropertyInfo &E : members_cache) {
  392. propnames.push_back(E);
  393. }
  394. if (base_cache.is_valid()) {
  395. base_cache->_update_exports_values(values, propnames);
  396. }
  397. }
  398. void GDScript::_add_doc(const DocData::ClassDoc &p_inner_class) {
  399. if (_owner) { // Only the top-level class stores doc info
  400. _owner->_add_doc(p_inner_class);
  401. } else { // Remove old docs, add new
  402. for (int i = 0; i < docs.size(); i++) {
  403. if (docs[i].name == p_inner_class.name) {
  404. docs.remove_at(i);
  405. break;
  406. }
  407. }
  408. docs.append(p_inner_class);
  409. }
  410. }
  411. void GDScript::_clear_doc() {
  412. docs.clear();
  413. doc = DocData::ClassDoc();
  414. }
  415. String GDScript::get_class_icon_path() const {
  416. return simplified_icon_path;
  417. }
  418. #endif
  419. bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderScriptInstance *p_instance_to_update, bool p_base_exports_changed) {
  420. #ifdef TOOLS_ENABLED
  421. static Vector<GDScript *> base_caches;
  422. if (!p_recursive_call) {
  423. base_caches.clear();
  424. }
  425. base_caches.append(this);
  426. bool changed = p_base_exports_changed;
  427. if (source_changed_cache) {
  428. source_changed_cache = false;
  429. changed = true;
  430. String basedir = path;
  431. if (basedir.is_empty()) {
  432. basedir = get_path();
  433. }
  434. if (!basedir.is_empty()) {
  435. basedir = basedir.get_base_dir();
  436. }
  437. GDScriptParser parser;
  438. GDScriptAnalyzer analyzer(&parser);
  439. Error err = parser.parse(source, path, false);
  440. if (err == OK && analyzer.analyze() == OK) {
  441. const GDScriptParser::ClassNode *c = parser.get_tree();
  442. if (base_cache.is_valid()) {
  443. base_cache->inheriters_cache.erase(get_instance_id());
  444. base_cache = Ref<GDScript>();
  445. }
  446. GDScriptParser::DataType base_type = parser.get_tree()->base_type;
  447. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  448. Ref<GDScript> bf = GDScriptCache::get_full_script(base_type.script_path, err, path);
  449. if (err == OK) {
  450. bf = Ref<GDScript>(bf->find_class(base_type.class_type->fqcn));
  451. if (bf.is_valid()) {
  452. base_cache = bf;
  453. bf->inheriters_cache.insert(get_instance_id());
  454. }
  455. }
  456. }
  457. members_cache.clear();
  458. member_default_values_cache.clear();
  459. _signals.clear();
  460. members_cache.push_back(get_class_category());
  461. for (int i = 0; i < c->members.size(); i++) {
  462. const GDScriptParser::ClassNode::Member &member = c->members[i];
  463. switch (member.type) {
  464. case GDScriptParser::ClassNode::Member::VARIABLE: {
  465. if (!member.variable->exported) {
  466. continue;
  467. }
  468. members_cache.push_back(member.variable->export_info);
  469. Variant default_value = analyzer.make_variable_default_value(member.variable);
  470. member_default_values_cache[member.variable->identifier->name] = default_value;
  471. } break;
  472. case GDScriptParser::ClassNode::Member::SIGNAL: {
  473. _signals[member.signal->identifier->name] = member.signal->method_info;
  474. } break;
  475. case GDScriptParser::ClassNode::Member::GROUP: {
  476. members_cache.push_back(member.annotation->export_info);
  477. } break;
  478. default:
  479. break; // Nothing.
  480. }
  481. }
  482. } else {
  483. placeholder_fallback_enabled = true;
  484. return false;
  485. }
  486. } else if (placeholder_fallback_enabled) {
  487. return false;
  488. }
  489. placeholder_fallback_enabled = false;
  490. if (base_cache.is_valid() && base_cache->is_valid()) {
  491. for (int i = 0; i < base_caches.size(); i++) {
  492. if (base_caches[i] == base_cache.ptr()) {
  493. if (r_err) {
  494. *r_err = true;
  495. }
  496. valid = false; // to show error in the editor
  497. base_cache->valid = false;
  498. base_cache->inheriters_cache.clear(); // to prevent future stackoverflows
  499. base_cache.unref();
  500. base.unref();
  501. _base = nullptr;
  502. ERR_FAIL_V_MSG(false, "Cyclic inheritance in script class.");
  503. }
  504. }
  505. if (base_cache->_update_exports(r_err, true)) {
  506. if (r_err && *r_err) {
  507. return false;
  508. }
  509. changed = true;
  510. }
  511. }
  512. if ((changed || p_instance_to_update) && placeholders.size()) { //hm :(
  513. // update placeholders if any
  514. HashMap<StringName, Variant> values;
  515. List<PropertyInfo> propnames;
  516. _update_exports_values(values, propnames);
  517. if (changed) {
  518. for (PlaceHolderScriptInstance *E : placeholders) {
  519. E->update(propnames, values);
  520. }
  521. } else {
  522. p_instance_to_update->update(propnames, values);
  523. }
  524. }
  525. return changed;
  526. #else
  527. return false;
  528. #endif
  529. }
  530. void GDScript::update_exports() {
  531. #ifdef TOOLS_ENABLED
  532. _update_exports_down(false);
  533. #endif
  534. }
  535. #ifdef TOOLS_ENABLED
  536. void GDScript::_update_exports_down(bool p_base_exports_changed) {
  537. bool cyclic_error = false;
  538. bool changed = _update_exports(&cyclic_error, false, nullptr, p_base_exports_changed);
  539. if (cyclic_error) {
  540. return;
  541. }
  542. HashSet<ObjectID> copy = inheriters_cache; //might get modified
  543. for (const ObjectID &E : copy) {
  544. Object *id = ObjectDB::get_instance(E);
  545. GDScript *s = Object::cast_to<GDScript>(id);
  546. if (!s) {
  547. continue;
  548. }
  549. s->_update_exports_down(p_base_exports_changed || changed);
  550. }
  551. }
  552. #endif
  553. String GDScript::_get_debug_path() const {
  554. if (is_built_in() && !get_name().is_empty()) {
  555. return vformat("%s(%s)", get_name(), get_script_path());
  556. } else {
  557. return get_script_path();
  558. }
  559. }
  560. Error GDScript::_static_init() {
  561. if (likely(valid) && static_initializer) {
  562. Callable::CallError call_err;
  563. static_initializer->call(nullptr, nullptr, 0, call_err);
  564. if (call_err.error != Callable::CallError::CALL_OK) {
  565. return ERR_CANT_CREATE;
  566. }
  567. }
  568. Error err = OK;
  569. for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
  570. err = inner.value->_static_init();
  571. if (err) {
  572. break;
  573. }
  574. }
  575. return err;
  576. }
  577. void GDScript::_static_default_init() {
  578. for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
  579. const GDScriptDataType &type = E.value.data_type;
  580. // Only initialize builtin types, which are not expected to be `null`.
  581. if (!type.has_type || type.kind != GDScriptDataType::BUILTIN) {
  582. continue;
  583. }
  584. if (type.builtin_type == Variant::ARRAY && type.has_container_element_type(0)) {
  585. Array default_value;
  586. const GDScriptDataType &element_type = type.get_container_element_type(0);
  587. default_value.set_typed(element_type.builtin_type, element_type.native_type, element_type.script_type);
  588. static_variables.write[E.value.index] = default_value;
  589. } else {
  590. Variant default_value;
  591. Callable::CallError err;
  592. Variant::construct(type.builtin_type, default_value, nullptr, 0, err);
  593. static_variables.write[E.value.index] = default_value;
  594. }
  595. }
  596. }
  597. #ifdef TOOLS_ENABLED
  598. void GDScript::_save_old_static_data() {
  599. old_static_variables_indices = static_variables_indices;
  600. old_static_variables = static_variables;
  601. for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
  602. inner.value->_save_old_static_data();
  603. }
  604. }
  605. void GDScript::_restore_old_static_data() {
  606. for (KeyValue<StringName, MemberInfo> &E : old_static_variables_indices) {
  607. if (static_variables_indices.has(E.key)) {
  608. static_variables.write[static_variables_indices[E.key].index] = old_static_variables[E.value.index];
  609. }
  610. }
  611. old_static_variables_indices.clear();
  612. old_static_variables.clear();
  613. for (KeyValue<StringName, Ref<GDScript>> &inner : subclasses) {
  614. inner.value->_restore_old_static_data();
  615. }
  616. }
  617. #endif
  618. Error GDScript::reload(bool p_keep_state) {
  619. if (reloading) {
  620. return OK;
  621. }
  622. reloading = true;
  623. bool has_instances;
  624. {
  625. MutexLock lock(GDScriptLanguage::singleton->mutex);
  626. has_instances = instances.size();
  627. }
  628. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  629. String basedir = path;
  630. if (basedir.is_empty()) {
  631. basedir = get_path();
  632. }
  633. if (!basedir.is_empty()) {
  634. basedir = basedir.get_base_dir();
  635. }
  636. // Loading a template, don't parse.
  637. #ifdef TOOLS_ENABLED
  638. if (EditorPaths::get_singleton() && basedir.begins_with(EditorPaths::get_singleton()->get_project_script_templates_dir())) {
  639. reloading = false;
  640. return OK;
  641. }
  642. #endif
  643. {
  644. String source_path = path;
  645. if (source_path.is_empty()) {
  646. source_path = get_path();
  647. }
  648. if (!source_path.is_empty()) {
  649. if (GDScriptCache::get_cached_script(source_path).is_null()) {
  650. MutexLock lock(GDScriptCache::singleton->mutex);
  651. GDScriptCache::singleton->shallow_gdscript_cache[source_path] = Ref<GDScript>(this);
  652. }
  653. if (GDScriptCache::has_parser(source_path)) {
  654. Error err = OK;
  655. Ref<GDScriptParserRef> parser_ref = GDScriptCache::get_parser(source_path, GDScriptParserRef::EMPTY, err);
  656. if (parser_ref.is_valid()) {
  657. uint32_t source_hash;
  658. if (!binary_tokens.is_empty()) {
  659. source_hash = hash_djb2_buffer(binary_tokens.ptr(), binary_tokens.size());
  660. } else {
  661. source_hash = source.hash();
  662. }
  663. if (parser_ref->get_source_hash() != source_hash) {
  664. GDScriptCache::remove_parser(source_path);
  665. }
  666. }
  667. }
  668. }
  669. }
  670. bool can_run = ScriptServer::is_scripting_enabled() || is_tool();
  671. #ifdef TOOLS_ENABLED
  672. if (p_keep_state && can_run && is_valid()) {
  673. _save_old_static_data();
  674. }
  675. #endif
  676. valid = false;
  677. GDScriptParser parser;
  678. Error err;
  679. if (!binary_tokens.is_empty()) {
  680. err = parser.parse_binary(binary_tokens, path);
  681. } else {
  682. err = parser.parse(source, path, false);
  683. }
  684. if (err) {
  685. if (EngineDebugger::is_active()) {
  686. GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
  687. }
  688. // TODO: Show all error messages.
  689. _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_errors().front()->get().line, ("Parse Error: " + parser.get_errors().front()->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  690. reloading = false;
  691. return ERR_PARSE_ERROR;
  692. }
  693. GDScriptAnalyzer analyzer(&parser);
  694. err = analyzer.analyze();
  695. if (err) {
  696. if (EngineDebugger::is_active()) {
  697. GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
  698. }
  699. const List<GDScriptParser::ParserError>::Element *e = parser.get_errors().front();
  700. while (e != nullptr) {
  701. _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), e->get().line, ("Parse Error: " + e->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  702. e = e->next();
  703. }
  704. reloading = false;
  705. return ERR_PARSE_ERROR;
  706. }
  707. can_run = ScriptServer::is_scripting_enabled() || parser.is_tool();
  708. GDScriptCompiler compiler;
  709. err = compiler.compile(&parser, this, p_keep_state);
  710. if (err) {
  711. _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  712. if (can_run) {
  713. if (EngineDebugger::is_active()) {
  714. GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
  715. }
  716. reloading = false;
  717. return ERR_COMPILATION_FAILED;
  718. } else {
  719. reloading = false;
  720. return err;
  721. }
  722. }
  723. #ifdef TOOLS_ENABLED
  724. // Done after compilation because it needs the GDScript object's inner class GDScript objects,
  725. // which are made by calling make_scripts() within compiler.compile() above.
  726. GDScriptDocGen::generate_docs(this, parser.get_tree());
  727. #endif
  728. #ifdef DEBUG_ENABLED
  729. for (const GDScriptWarning &warning : parser.get_warnings()) {
  730. if (EngineDebugger::is_active()) {
  731. Vector<ScriptLanguage::StackInfo> si;
  732. EngineDebugger::get_script_debugger()->send_error("", get_script_path(), warning.start_line, warning.get_name(), warning.get_message(), false, ERR_HANDLER_WARNING, si);
  733. }
  734. }
  735. #endif
  736. if (can_run) {
  737. err = _static_init();
  738. if (err) {
  739. return err;
  740. }
  741. }
  742. #ifdef TOOLS_ENABLED
  743. if (can_run && p_keep_state) {
  744. _restore_old_static_data();
  745. }
  746. #endif
  747. reloading = false;
  748. return OK;
  749. }
  750. ScriptLanguage *GDScript::get_language() const {
  751. return GDScriptLanguage::get_singleton();
  752. }
  753. void GDScript::get_constants(HashMap<StringName, Variant> *p_constants) {
  754. if (p_constants) {
  755. for (const KeyValue<StringName, Variant> &E : constants) {
  756. (*p_constants)[E.key] = E.value;
  757. }
  758. }
  759. }
  760. void GDScript::get_members(HashSet<StringName> *p_members) {
  761. if (p_members) {
  762. for (const StringName &E : members) {
  763. p_members->insert(E);
  764. }
  765. }
  766. }
  767. const Variant GDScript::get_rpc_config() const {
  768. return rpc_config;
  769. }
  770. void GDScript::unload_static() const {
  771. GDScriptCache::remove_script(fully_qualified_name);
  772. }
  773. Variant GDScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  774. GDScript *top = this;
  775. while (top) {
  776. if (likely(top->valid)) {
  777. HashMap<StringName, GDScriptFunction *>::Iterator E = top->member_functions.find(p_method);
  778. if (E) {
  779. ERR_FAIL_COND_V_MSG(!E->value->is_static(), Variant(), "Can't call non-static function '" + String(p_method) + "' in script.");
  780. return E->value->call(nullptr, p_args, p_argcount, r_error);
  781. }
  782. }
  783. top = top->_base;
  784. }
  785. //none found, regular
  786. return Script::callp(p_method, p_args, p_argcount, r_error);
  787. }
  788. bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
  789. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  790. r_ret = get_source_code();
  791. return true;
  792. }
  793. const GDScript *top = this;
  794. while (top) {
  795. {
  796. HashMap<StringName, Variant>::ConstIterator E = top->constants.find(p_name);
  797. if (E) {
  798. r_ret = E->value;
  799. return true;
  800. }
  801. }
  802. {
  803. HashMap<StringName, MemberInfo>::ConstIterator E = top->static_variables_indices.find(p_name);
  804. if (E) {
  805. if (likely(top->valid) && E->value.getter) {
  806. Callable::CallError ce;
  807. const Variant ret = const_cast<GDScript *>(this)->callp(E->value.getter, nullptr, 0, ce);
  808. r_ret = (ce.error == Callable::CallError::CALL_OK) ? ret : Variant();
  809. return true;
  810. }
  811. r_ret = top->static_variables[E->value.index];
  812. return true;
  813. }
  814. }
  815. if (likely(top->valid)) {
  816. HashMap<StringName, GDScriptFunction *>::ConstIterator E = top->member_functions.find(p_name);
  817. if (E && E->value->is_static()) {
  818. if (top->rpc_config.has(p_name)) {
  819. r_ret = Callable(memnew(GDScriptRPCCallable(const_cast<GDScript *>(top), E->key)));
  820. } else {
  821. r_ret = Callable(const_cast<GDScript *>(top), E->key);
  822. }
  823. return true;
  824. }
  825. }
  826. {
  827. HashMap<StringName, Ref<GDScript>>::ConstIterator E = top->subclasses.find(p_name);
  828. if (E) {
  829. r_ret = E->value;
  830. return true;
  831. }
  832. }
  833. top = top->_base;
  834. }
  835. return false;
  836. }
  837. bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
  838. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  839. set_source_code(p_value);
  840. reload(true);
  841. return true;
  842. }
  843. GDScript *top = this;
  844. while (top) {
  845. HashMap<StringName, MemberInfo>::ConstIterator E = top->static_variables_indices.find(p_name);
  846. if (E) {
  847. const MemberInfo *member = &E->value;
  848. Variant value = p_value;
  849. if (member->data_type.has_type && !member->data_type.is_type(value)) {
  850. const Variant *args = &p_value;
  851. Callable::CallError err;
  852. Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
  853. if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
  854. return false;
  855. }
  856. }
  857. if (likely(top->valid) && member->setter) {
  858. const Variant *args = &value;
  859. Callable::CallError err;
  860. callp(member->setter, &args, 1, err);
  861. return err.error == Callable::CallError::CALL_OK;
  862. } else {
  863. top->static_variables.write[member->index] = value;
  864. return true;
  865. }
  866. }
  867. top = top->_base;
  868. }
  869. return false;
  870. }
  871. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  872. p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
  873. List<const GDScript *> classes;
  874. const GDScript *top = this;
  875. while (top) {
  876. classes.push_back(top);
  877. top = top->_base;
  878. }
  879. for (const List<const GDScript *>::Element *E = classes.back(); E; E = E->prev()) {
  880. Vector<_GDScriptMemberSort> msort;
  881. for (const KeyValue<StringName, MemberInfo> &F : E->get()->static_variables_indices) {
  882. _GDScriptMemberSort ms;
  883. ms.index = F.value.index;
  884. ms.name = F.key;
  885. msort.push_back(ms);
  886. }
  887. msort.sort();
  888. for (int i = 0; i < msort.size(); i++) {
  889. p_properties->push_back(E->get()->static_variables_indices[msort[i].name].property_info);
  890. }
  891. }
  892. }
  893. void GDScript::_bind_methods() {
  894. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new"));
  895. }
  896. void GDScript::set_path(const String &p_path, bool p_take_over) {
  897. if (is_root_script()) {
  898. Script::set_path(p_path, p_take_over);
  899. }
  900. String old_path = path;
  901. path = p_path;
  902. path_valid = true;
  903. GDScriptCache::move_script(old_path, p_path);
  904. for (KeyValue<StringName, Ref<GDScript>> &kv : subclasses) {
  905. kv.value->set_path(p_path, p_take_over);
  906. }
  907. }
  908. String GDScript::get_script_path() const {
  909. if (!path_valid && !get_path().is_empty()) {
  910. return get_path();
  911. }
  912. return path;
  913. }
  914. Error GDScript::load_source_code(const String &p_path) {
  915. if (p_path.is_empty() || p_path.begins_with("gdscript://") || ResourceLoader::get_resource_type(p_path.get_slice("::", 0)) == "PackedScene") {
  916. return OK;
  917. }
  918. Vector<uint8_t> sourcef;
  919. Error err;
  920. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  921. if (err) {
  922. const char *err_name;
  923. if (err < 0 || err >= ERR_MAX) {
  924. err_name = "(invalid error code)";
  925. } else {
  926. err_name = error_names[err];
  927. }
  928. ERR_FAIL_COND_V_MSG(err, err, "Attempt to open script '" + p_path + "' resulted in error '" + err_name + "'.");
  929. }
  930. uint64_t len = f->get_length();
  931. sourcef.resize(len + 1);
  932. uint8_t *w = sourcef.ptrw();
  933. uint64_t r = f->get_buffer(w, len);
  934. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  935. w[len] = 0;
  936. String s;
  937. if (s.parse_utf8((const char *)w) != OK) {
  938. ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
  939. }
  940. source = s;
  941. path = p_path;
  942. path_valid = true;
  943. #ifdef TOOLS_ENABLED
  944. source_changed_cache = true;
  945. set_edited(false);
  946. set_last_modified_time(FileAccess::get_modified_time(path));
  947. #endif // TOOLS_ENABLED
  948. return OK;
  949. }
  950. void GDScript::set_binary_tokens_source(const Vector<uint8_t> &p_binary_tokens) {
  951. binary_tokens = p_binary_tokens;
  952. }
  953. const Vector<uint8_t> &GDScript::get_binary_tokens_source() const {
  954. return binary_tokens;
  955. }
  956. Vector<uint8_t> GDScript::get_as_binary_tokens() const {
  957. GDScriptTokenizerBuffer tokenizer;
  958. return tokenizer.parse_code_string(source, GDScriptTokenizerBuffer::COMPRESS_NONE);
  959. }
  960. const HashMap<StringName, GDScriptFunction *> &GDScript::debug_get_member_functions() const {
  961. return member_functions;
  962. }
  963. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  964. for (const KeyValue<StringName, MemberInfo> &E : member_indices) {
  965. if (E.value.index == p_idx) {
  966. return E.key;
  967. }
  968. }
  969. return "<error>";
  970. }
  971. StringName GDScript::debug_get_static_var_by_index(int p_idx) const {
  972. for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
  973. if (E.value.index == p_idx) {
  974. return E.key;
  975. }
  976. }
  977. return "<error>";
  978. }
  979. Ref<GDScript> GDScript::get_base() const {
  980. return base;
  981. }
  982. bool GDScript::inherits_script(const Ref<Script> &p_script) const {
  983. Ref<GDScript> gd = p_script;
  984. if (gd.is_null()) {
  985. return false;
  986. }
  987. const GDScript *s = this;
  988. while (s) {
  989. if (s == p_script.ptr()) {
  990. return true;
  991. }
  992. s = s->_base;
  993. }
  994. return false;
  995. }
  996. GDScript *GDScript::find_class(const String &p_qualified_name) {
  997. String first = p_qualified_name.get_slice("::", 0);
  998. Vector<String> class_names;
  999. GDScript *result = nullptr;
  1000. // Empty initial name means start here.
  1001. if (first.is_empty() || first == global_name) {
  1002. class_names = p_qualified_name.split("::");
  1003. result = this;
  1004. } else if (p_qualified_name.begins_with(get_root_script()->path)) {
  1005. // Script path could have a class path separator("::") in it.
  1006. class_names = p_qualified_name.trim_prefix(get_root_script()->path).split("::");
  1007. result = get_root_script();
  1008. } else if (HashMap<StringName, Ref<GDScript>>::Iterator E = subclasses.find(first)) {
  1009. class_names = p_qualified_name.split("::");
  1010. result = E->value.ptr();
  1011. } else if (_owner != nullptr) {
  1012. // Check parent scope.
  1013. return _owner->find_class(p_qualified_name);
  1014. }
  1015. // Starts at index 1 because index 0 was handled above.
  1016. for (int i = 1; result != nullptr && i < class_names.size(); i++) {
  1017. if (HashMap<StringName, Ref<GDScript>>::Iterator E = result->subclasses.find(class_names[i])) {
  1018. result = E->value.ptr();
  1019. } else {
  1020. // Couldn't find inner class.
  1021. return nullptr;
  1022. }
  1023. }
  1024. return result;
  1025. }
  1026. bool GDScript::has_class(const GDScript *p_script) {
  1027. String fqn = p_script->fully_qualified_name;
  1028. if (fully_qualified_name.is_empty() && fqn.get_slice("::", 0).is_empty()) {
  1029. return p_script == this;
  1030. } else if (fqn.begins_with(fully_qualified_name)) {
  1031. return p_script == find_class(fqn.trim_prefix(fully_qualified_name));
  1032. }
  1033. return false;
  1034. }
  1035. GDScript *GDScript::get_root_script() {
  1036. GDScript *result = this;
  1037. while (result->_owner) {
  1038. result = result->_owner;
  1039. }
  1040. return result;
  1041. }
  1042. RBSet<GDScript *> GDScript::get_dependencies() {
  1043. RBSet<GDScript *> dependencies;
  1044. _collect_dependencies(dependencies, this);
  1045. dependencies.erase(this);
  1046. return dependencies;
  1047. }
  1048. HashMap<GDScript *, RBSet<GDScript *>> GDScript::get_all_dependencies() {
  1049. HashMap<GDScript *, RBSet<GDScript *>> all_dependencies;
  1050. List<GDScript *> scripts;
  1051. {
  1052. MutexLock lock(GDScriptLanguage::singleton->mutex);
  1053. SelfList<GDScript> *elem = GDScriptLanguage::singleton->script_list.first();
  1054. while (elem) {
  1055. scripts.push_back(elem->self());
  1056. elem = elem->next();
  1057. }
  1058. }
  1059. for (GDScript *scr : scripts) {
  1060. if (scr == nullptr || scr->destructing) {
  1061. continue;
  1062. }
  1063. all_dependencies.insert(scr, scr->get_dependencies());
  1064. }
  1065. return all_dependencies;
  1066. }
  1067. RBSet<GDScript *> GDScript::get_must_clear_dependencies() {
  1068. RBSet<GDScript *> dependencies = get_dependencies();
  1069. RBSet<GDScript *> must_clear_dependencies;
  1070. HashMap<GDScript *, RBSet<GDScript *>> all_dependencies = get_all_dependencies();
  1071. RBSet<GDScript *> cant_clear;
  1072. for (KeyValue<GDScript *, RBSet<GDScript *>> &E : all_dependencies) {
  1073. if (dependencies.has(E.key)) {
  1074. continue;
  1075. }
  1076. for (GDScript *F : E.value) {
  1077. if (dependencies.has(F)) {
  1078. cant_clear.insert(F);
  1079. }
  1080. }
  1081. }
  1082. for (GDScript *E : dependencies) {
  1083. if (cant_clear.has(E) || ScriptServer::is_global_class(E->get_fully_qualified_name())) {
  1084. continue;
  1085. }
  1086. must_clear_dependencies.insert(E);
  1087. }
  1088. cant_clear.clear();
  1089. dependencies.clear();
  1090. all_dependencies.clear();
  1091. return must_clear_dependencies;
  1092. }
  1093. bool GDScript::has_script_signal(const StringName &p_signal) const {
  1094. if (_signals.has(p_signal)) {
  1095. return true;
  1096. }
  1097. if (base.is_valid()) {
  1098. return base->has_script_signal(p_signal);
  1099. }
  1100. #ifdef TOOLS_ENABLED
  1101. else if (base_cache.is_valid()) {
  1102. return base_cache->has_script_signal(p_signal);
  1103. }
  1104. #endif
  1105. return false;
  1106. }
  1107. void GDScript::_get_script_signal_list(List<MethodInfo> *r_list, bool p_include_base) const {
  1108. for (const KeyValue<StringName, MethodInfo> &E : _signals) {
  1109. r_list->push_back(E.value);
  1110. }
  1111. if (!p_include_base) {
  1112. return;
  1113. }
  1114. if (base.is_valid()) {
  1115. base->get_script_signal_list(r_list);
  1116. }
  1117. #ifdef TOOLS_ENABLED
  1118. else if (base_cache.is_valid()) {
  1119. base_cache->get_script_signal_list(r_list);
  1120. }
  1121. #endif
  1122. }
  1123. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  1124. _get_script_signal_list(r_signals, true);
  1125. }
  1126. GDScript *GDScript::_get_gdscript_from_variant(const Variant &p_variant) {
  1127. Object *obj = p_variant;
  1128. if (obj == nullptr || obj->get_instance_id().is_null()) {
  1129. return nullptr;
  1130. }
  1131. return Object::cast_to<GDScript>(obj);
  1132. }
  1133. void GDScript::_collect_function_dependencies(GDScriptFunction *p_func, RBSet<GDScript *> &p_dependencies, const GDScript *p_except) {
  1134. if (p_func == nullptr) {
  1135. return;
  1136. }
  1137. for (GDScriptFunction *lambda : p_func->lambdas) {
  1138. _collect_function_dependencies(lambda, p_dependencies, p_except);
  1139. }
  1140. for (const Variant &V : p_func->constants) {
  1141. GDScript *scr = _get_gdscript_from_variant(V);
  1142. if (scr != nullptr && scr != p_except) {
  1143. scr->_collect_dependencies(p_dependencies, p_except);
  1144. }
  1145. }
  1146. }
  1147. void GDScript::_collect_dependencies(RBSet<GDScript *> &p_dependencies, const GDScript *p_except) {
  1148. if (p_dependencies.has(this)) {
  1149. return;
  1150. }
  1151. if (this != p_except) {
  1152. p_dependencies.insert(this);
  1153. }
  1154. for (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {
  1155. _collect_function_dependencies(E.value, p_dependencies, p_except);
  1156. }
  1157. if (implicit_initializer) {
  1158. _collect_function_dependencies(implicit_initializer, p_dependencies, p_except);
  1159. }
  1160. if (implicit_ready) {
  1161. _collect_function_dependencies(implicit_ready, p_dependencies, p_except);
  1162. }
  1163. if (static_initializer) {
  1164. _collect_function_dependencies(static_initializer, p_dependencies, p_except);
  1165. }
  1166. for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  1167. if (E.value != p_except) {
  1168. E.value->_collect_dependencies(p_dependencies, p_except);
  1169. }
  1170. }
  1171. for (const KeyValue<StringName, Variant> &E : constants) {
  1172. GDScript *scr = _get_gdscript_from_variant(E.value);
  1173. if (scr != nullptr && scr != p_except) {
  1174. scr->_collect_dependencies(p_dependencies, p_except);
  1175. }
  1176. }
  1177. }
  1178. GDScript::GDScript() :
  1179. script_list(this) {
  1180. {
  1181. MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
  1182. GDScriptLanguage::get_singleton()->script_list.add(&script_list);
  1183. }
  1184. path = vformat("gdscript://%d.gd", get_instance_id());
  1185. }
  1186. void GDScript::_save_orphaned_subclasses(ClearData *p_clear_data) {
  1187. struct ClassRefWithName {
  1188. ObjectID id;
  1189. String fully_qualified_name;
  1190. };
  1191. Vector<ClassRefWithName> weak_subclasses;
  1192. // collect subclasses ObjectID and name
  1193. for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  1194. E.value->_owner = nullptr; //bye, you are no longer owned cause I died
  1195. ClassRefWithName subclass;
  1196. subclass.id = E.value->get_instance_id();
  1197. subclass.fully_qualified_name = E.value->fully_qualified_name;
  1198. weak_subclasses.push_back(subclass);
  1199. }
  1200. // clear subclasses to allow unused subclasses to be deleted
  1201. for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  1202. p_clear_data->scripts.insert(E.value);
  1203. }
  1204. subclasses.clear();
  1205. // subclasses are also held by constants, clear those as well
  1206. for (KeyValue<StringName, Variant> &E : constants) {
  1207. GDScript *gdscr = _get_gdscript_from_variant(E.value);
  1208. if (gdscr != nullptr) {
  1209. p_clear_data->scripts.insert(gdscr);
  1210. }
  1211. }
  1212. constants.clear();
  1213. // keep orphan subclass only for subclasses that are still in use
  1214. for (int i = 0; i < weak_subclasses.size(); i++) {
  1215. ClassRefWithName subclass = weak_subclasses[i];
  1216. Object *obj = ObjectDB::get_instance(subclass.id);
  1217. if (!obj) {
  1218. continue;
  1219. }
  1220. // subclass is not released
  1221. GDScriptLanguage::get_singleton()->add_orphan_subclass(subclass.fully_qualified_name, subclass.id);
  1222. }
  1223. }
  1224. #ifdef DEBUG_ENABLED
  1225. String GDScript::debug_get_script_name(const Ref<Script> &p_script) {
  1226. if (p_script.is_valid()) {
  1227. Ref<GDScript> gdscript = p_script;
  1228. if (gdscript.is_valid()) {
  1229. if (gdscript->get_local_name() != StringName()) {
  1230. return gdscript->get_local_name();
  1231. }
  1232. return gdscript->get_fully_qualified_name().get_file();
  1233. }
  1234. if (p_script->get_global_name() != StringName()) {
  1235. return p_script->get_global_name();
  1236. } else if (!p_script->get_path().is_empty()) {
  1237. return p_script->get_path().get_file();
  1238. } else if (!p_script->get_name().is_empty()) {
  1239. return p_script->get_name(); // Resource name.
  1240. }
  1241. }
  1242. return "<unknown script>";
  1243. }
  1244. #endif
  1245. String GDScript::canonicalize_path(const String &p_path) {
  1246. if (p_path.get_extension() == "gdc") {
  1247. return p_path.get_basename() + ".gd";
  1248. }
  1249. return p_path;
  1250. }
  1251. GDScript::UpdatableFuncPtr::UpdatableFuncPtr(GDScriptFunction *p_function) {
  1252. if (p_function == nullptr) {
  1253. return;
  1254. }
  1255. ptr = p_function;
  1256. script = ptr->get_script();
  1257. ERR_FAIL_NULL(script);
  1258. MutexLock script_lock(script->func_ptrs_to_update_mutex);
  1259. list_element = script->func_ptrs_to_update.push_back(this);
  1260. }
  1261. GDScript::UpdatableFuncPtr::~UpdatableFuncPtr() {
  1262. ERR_FAIL_NULL(script);
  1263. if (list_element) {
  1264. MutexLock script_lock(script->func_ptrs_to_update_mutex);
  1265. list_element->erase();
  1266. list_element = nullptr;
  1267. }
  1268. }
  1269. void GDScript::_recurse_replace_function_ptrs(const HashMap<GDScriptFunction *, GDScriptFunction *> &p_replacements) const {
  1270. MutexLock lock(func_ptrs_to_update_mutex);
  1271. for (UpdatableFuncPtr *updatable : func_ptrs_to_update) {
  1272. HashMap<GDScriptFunction *, GDScriptFunction *>::ConstIterator replacement = p_replacements.find(updatable->ptr);
  1273. if (replacement) {
  1274. updatable->ptr = replacement->value;
  1275. } else {
  1276. // Probably a lambda from another reload, ignore.
  1277. updatable->ptr = nullptr;
  1278. }
  1279. }
  1280. for (HashMap<StringName, Ref<GDScript>>::ConstIterator subscript = subclasses.begin(); subscript; ++subscript) {
  1281. subscript->value->_recurse_replace_function_ptrs(p_replacements);
  1282. }
  1283. }
  1284. void GDScript::clear(ClearData *p_clear_data) {
  1285. if (clearing) {
  1286. return;
  1287. }
  1288. clearing = true;
  1289. ClearData data;
  1290. ClearData *clear_data = p_clear_data;
  1291. bool is_root = false;
  1292. // If `clear_data` is `nullptr`, it means that it's the root.
  1293. // The root is in charge to clear functions and scripts of itself and its dependencies
  1294. if (clear_data == nullptr) {
  1295. clear_data = &data;
  1296. is_root = true;
  1297. }
  1298. {
  1299. MutexLock lock(func_ptrs_to_update_mutex);
  1300. for (UpdatableFuncPtr *updatable : func_ptrs_to_update) {
  1301. updatable->ptr = nullptr;
  1302. }
  1303. }
  1304. // If we're in the process of shutting things down then every single script will be cleared
  1305. // anyway, so we can safely skip this very costly operation.
  1306. if (!GDScriptLanguage::singleton->finishing) {
  1307. RBSet<GDScript *> must_clear_dependencies = get_must_clear_dependencies();
  1308. for (GDScript *E : must_clear_dependencies) {
  1309. clear_data->scripts.insert(E);
  1310. E->clear(clear_data);
  1311. }
  1312. }
  1313. for (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {
  1314. clear_data->functions.insert(E.value);
  1315. }
  1316. member_functions.clear();
  1317. for (KeyValue<StringName, MemberInfo> &E : member_indices) {
  1318. clear_data->scripts.insert(E.value.data_type.script_type_ref);
  1319. E.value.data_type.script_type_ref = Ref<Script>();
  1320. }
  1321. for (KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
  1322. clear_data->scripts.insert(E.value.data_type.script_type_ref);
  1323. E.value.data_type.script_type_ref = Ref<Script>();
  1324. }
  1325. static_variables.clear();
  1326. static_variables_indices.clear();
  1327. if (implicit_initializer) {
  1328. clear_data->functions.insert(implicit_initializer);
  1329. implicit_initializer = nullptr;
  1330. }
  1331. if (implicit_ready) {
  1332. clear_data->functions.insert(implicit_ready);
  1333. implicit_ready = nullptr;
  1334. }
  1335. if (static_initializer) {
  1336. clear_data->functions.insert(static_initializer);
  1337. static_initializer = nullptr;
  1338. }
  1339. _save_orphaned_subclasses(clear_data);
  1340. #ifdef TOOLS_ENABLED
  1341. // Clearing inner class doc, script doc only cleared when the script source deleted.
  1342. if (_owner) {
  1343. _clear_doc();
  1344. }
  1345. #endif
  1346. // If it's not the root, skip clearing the data
  1347. if (is_root) {
  1348. // All dependencies have been accounted for
  1349. for (GDScriptFunction *E : clear_data->functions) {
  1350. memdelete(E);
  1351. }
  1352. for (Ref<Script> &E : clear_data->scripts) {
  1353. Ref<GDScript> gdscr = E;
  1354. if (gdscr.is_valid()) {
  1355. GDScriptCache::remove_script(gdscr->get_path());
  1356. }
  1357. }
  1358. clear_data->clear();
  1359. }
  1360. }
  1361. GDScript::~GDScript() {
  1362. if (destructing) {
  1363. return;
  1364. }
  1365. destructing = true;
  1366. if (is_print_verbose_enabled()) {
  1367. MutexLock lock(func_ptrs_to_update_mutex);
  1368. if (!func_ptrs_to_update.is_empty()) {
  1369. print_line(vformat("GDScript: %d orphaned lambdas becoming invalid at destruction of script '%s'.", func_ptrs_to_update.size(), fully_qualified_name));
  1370. }
  1371. }
  1372. clear();
  1373. {
  1374. MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
  1375. while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
  1376. // Order matters since clearing the stack may already cause
  1377. // the GDScriptFunctionState to be destroyed and thus removed from the list.
  1378. pending_func_states.remove(E);
  1379. GDScriptFunctionState *state = E->self();
  1380. ObjectID state_id = state->get_instance_id();
  1381. state->_clear_connections();
  1382. if (ObjectDB::get_instance(state_id)) {
  1383. state->_clear_stack();
  1384. }
  1385. }
  1386. }
  1387. {
  1388. MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
  1389. script_list.remove_from_list();
  1390. }
  1391. }
  1392. //////////////////////////////
  1393. // INSTANCE //
  1394. //////////////////////////////
  1395. bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
  1396. {
  1397. HashMap<StringName, GDScript::MemberInfo>::Iterator E = script->member_indices.find(p_name);
  1398. if (E) {
  1399. const GDScript::MemberInfo *member = &E->value;
  1400. Variant value = p_value;
  1401. if (member->data_type.has_type && !member->data_type.is_type(value)) {
  1402. const Variant *args = &p_value;
  1403. Callable::CallError err;
  1404. Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
  1405. if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
  1406. return false;
  1407. }
  1408. }
  1409. if (likely(script->valid) && member->setter) {
  1410. const Variant *args = &value;
  1411. Callable::CallError err;
  1412. callp(member->setter, &args, 1, err);
  1413. return err.error == Callable::CallError::CALL_OK;
  1414. } else {
  1415. members.write[member->index] = value;
  1416. return true;
  1417. }
  1418. }
  1419. }
  1420. GDScript *sptr = script.ptr();
  1421. while (sptr) {
  1422. {
  1423. HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = sptr->static_variables_indices.find(p_name);
  1424. if (E) {
  1425. const GDScript::MemberInfo *member = &E->value;
  1426. Variant value = p_value;
  1427. if (member->data_type.has_type && !member->data_type.is_type(value)) {
  1428. const Variant *args = &p_value;
  1429. Callable::CallError err;
  1430. Variant::construct(member->data_type.builtin_type, value, &args, 1, err);
  1431. if (err.error != Callable::CallError::CALL_OK || !member->data_type.is_type(value)) {
  1432. return false;
  1433. }
  1434. }
  1435. if (likely(sptr->valid) && member->setter) {
  1436. const Variant *args = &value;
  1437. Callable::CallError err;
  1438. callp(member->setter, &args, 1, err);
  1439. return err.error == Callable::CallError::CALL_OK;
  1440. } else {
  1441. sptr->static_variables.write[member->index] = value;
  1442. return true;
  1443. }
  1444. }
  1445. }
  1446. if (likely(sptr->valid)) {
  1447. HashMap<StringName, GDScriptFunction *>::Iterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  1448. if (E) {
  1449. Variant name = p_name;
  1450. const Variant *args[2] = { &name, &p_value };
  1451. Callable::CallError err;
  1452. Variant ret = E->value->call(this, (const Variant **)args, 2, err);
  1453. if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
  1454. return true;
  1455. }
  1456. }
  1457. }
  1458. sptr = sptr->_base;
  1459. }
  1460. return false;
  1461. }
  1462. bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
  1463. {
  1464. HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = script->member_indices.find(p_name);
  1465. if (E) {
  1466. if (likely(script->valid) && E->value.getter) {
  1467. Callable::CallError err;
  1468. const Variant ret = const_cast<GDScriptInstance *>(this)->callp(E->value.getter, nullptr, 0, err);
  1469. r_ret = (err.error == Callable::CallError::CALL_OK) ? ret : Variant();
  1470. return true;
  1471. }
  1472. r_ret = members[E->value.index];
  1473. return true;
  1474. }
  1475. }
  1476. const GDScript *sptr = script.ptr();
  1477. while (sptr) {
  1478. {
  1479. HashMap<StringName, Variant>::ConstIterator E = sptr->constants.find(p_name);
  1480. if (E) {
  1481. r_ret = E->value;
  1482. return true;
  1483. }
  1484. }
  1485. {
  1486. HashMap<StringName, GDScript::MemberInfo>::ConstIterator E = sptr->static_variables_indices.find(p_name);
  1487. if (E) {
  1488. if (likely(sptr->valid) && E->value.getter) {
  1489. Callable::CallError ce;
  1490. const Variant ret = const_cast<GDScript *>(sptr)->callp(E->value.getter, nullptr, 0, ce);
  1491. r_ret = (ce.error == Callable::CallError::CALL_OK) ? ret : Variant();
  1492. return true;
  1493. }
  1494. r_ret = sptr->static_variables[E->value.index];
  1495. return true;
  1496. }
  1497. }
  1498. {
  1499. HashMap<StringName, MethodInfo>::ConstIterator E = sptr->_signals.find(p_name);
  1500. if (E) {
  1501. r_ret = Signal(owner, E->key);
  1502. return true;
  1503. }
  1504. }
  1505. if (likely(sptr->valid)) {
  1506. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_name);
  1507. if (E) {
  1508. if (sptr->rpc_config.has(p_name)) {
  1509. r_ret = Callable(memnew(GDScriptRPCCallable(owner, E->key)));
  1510. } else {
  1511. r_ret = Callable(owner, E->key);
  1512. }
  1513. return true;
  1514. }
  1515. }
  1516. {
  1517. HashMap<StringName, Ref<GDScript>>::ConstIterator E = sptr->subclasses.find(p_name);
  1518. if (E) {
  1519. r_ret = E->value;
  1520. return true;
  1521. }
  1522. }
  1523. if (likely(sptr->valid)) {
  1524. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  1525. if (E) {
  1526. Variant name = p_name;
  1527. const Variant *args[1] = { &name };
  1528. Callable::CallError err;
  1529. Variant ret = const_cast<GDScriptFunction *>(E->value)->call(const_cast<GDScriptInstance *>(this), (const Variant **)args, 1, err);
  1530. if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  1531. r_ret = ret;
  1532. return true;
  1533. }
  1534. }
  1535. }
  1536. sptr = sptr->_base;
  1537. }
  1538. return false;
  1539. }
  1540. Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1541. if (script->member_indices.has(p_name)) {
  1542. if (r_is_valid) {
  1543. *r_is_valid = true;
  1544. }
  1545. return script->member_indices[p_name].property_info.type;
  1546. }
  1547. if (r_is_valid) {
  1548. *r_is_valid = false;
  1549. }
  1550. return Variant::NIL;
  1551. }
  1552. void GDScriptInstance::validate_property(PropertyInfo &p_property) const {
  1553. Variant property = (Dictionary)p_property;
  1554. const Variant *args[1] = { &property };
  1555. const GDScript *sptr = script.ptr();
  1556. while (sptr) {
  1557. if (likely(sptr->valid)) {
  1558. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._validate_property);
  1559. if (E) {
  1560. Callable::CallError err;
  1561. Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
  1562. if (err.error == Callable::CallError::CALL_OK) {
  1563. p_property = PropertyInfo::from_dict(property);
  1564. return;
  1565. }
  1566. }
  1567. }
  1568. sptr = sptr->_base;
  1569. }
  1570. }
  1571. void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1572. // exported members, not done yet!
  1573. const GDScript *sptr = script.ptr();
  1574. List<PropertyInfo> props;
  1575. while (sptr) {
  1576. if (likely(sptr->valid)) {
  1577. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  1578. if (E) {
  1579. Callable::CallError err;
  1580. Variant ret = const_cast<GDScriptFunction *>(E->value)->call(const_cast<GDScriptInstance *>(this), nullptr, 0, err);
  1581. if (err.error == Callable::CallError::CALL_OK) {
  1582. ERR_FAIL_COND_MSG(ret.get_type() != Variant::ARRAY, "Wrong type for _get_property_list, must be an array of dictionaries.");
  1583. Array arr = ret;
  1584. for (int i = 0; i < arr.size(); i++) {
  1585. Dictionary d = arr[i];
  1586. ERR_CONTINUE(!d.has("name"));
  1587. ERR_CONTINUE(!d.has("type"));
  1588. PropertyInfo pinfo;
  1589. pinfo.name = d["name"];
  1590. pinfo.type = Variant::Type(d["type"].operator int());
  1591. if (d.has("hint")) {
  1592. pinfo.hint = PropertyHint(d["hint"].operator int());
  1593. }
  1594. if (d.has("hint_string")) {
  1595. pinfo.hint_string = d["hint_string"];
  1596. }
  1597. if (d.has("usage")) {
  1598. pinfo.usage = d["usage"];
  1599. }
  1600. if (d.has("class_name")) {
  1601. pinfo.class_name = d["class_name"];
  1602. }
  1603. ERR_CONTINUE(pinfo.name.is_empty() && (pinfo.usage & PROPERTY_USAGE_STORAGE));
  1604. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  1605. props.push_back(pinfo);
  1606. }
  1607. }
  1608. }
  1609. }
  1610. //instance a fake script for editing the values
  1611. Vector<_GDScriptMemberSort> msort;
  1612. for (const KeyValue<StringName, GDScript::MemberInfo> &F : sptr->member_indices) {
  1613. if (!sptr->members.has(F.key)) {
  1614. continue; // Skip base class members.
  1615. }
  1616. _GDScriptMemberSort ms;
  1617. ms.index = F.value.index;
  1618. ms.name = F.key;
  1619. msort.push_back(ms);
  1620. }
  1621. msort.sort();
  1622. msort.reverse();
  1623. for (int i = 0; i < msort.size(); i++) {
  1624. props.push_front(sptr->member_indices[msort[i].name].property_info);
  1625. }
  1626. #ifdef TOOLS_ENABLED
  1627. p_properties->push_back(sptr->get_class_category());
  1628. #endif // TOOLS_ENABLED
  1629. for (PropertyInfo &prop : props) {
  1630. validate_property(prop);
  1631. p_properties->push_back(prop);
  1632. }
  1633. props.clear();
  1634. sptr = sptr->_base;
  1635. }
  1636. }
  1637. bool GDScriptInstance::property_can_revert(const StringName &p_name) const {
  1638. Variant name = p_name;
  1639. const Variant *args[1] = { &name };
  1640. const GDScript *sptr = script.ptr();
  1641. while (sptr) {
  1642. if (likely(sptr->valid)) {
  1643. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_can_revert);
  1644. if (E) {
  1645. Callable::CallError err;
  1646. Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
  1647. if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
  1648. return true;
  1649. }
  1650. }
  1651. }
  1652. sptr = sptr->_base;
  1653. }
  1654. return false;
  1655. }
  1656. bool GDScriptInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
  1657. Variant name = p_name;
  1658. const Variant *args[1] = { &name };
  1659. const GDScript *sptr = script.ptr();
  1660. while (sptr) {
  1661. if (likely(sptr->valid)) {
  1662. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_get_revert);
  1663. if (E) {
  1664. Callable::CallError err;
  1665. Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
  1666. if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  1667. r_ret = ret;
  1668. return true;
  1669. }
  1670. }
  1671. }
  1672. sptr = sptr->_base;
  1673. }
  1674. return false;
  1675. }
  1676. void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
  1677. const GDScript *sptr = script.ptr();
  1678. while (sptr) {
  1679. for (const KeyValue<StringName, GDScriptFunction *> &E : sptr->member_functions) {
  1680. p_list->push_back(E.value->get_method_info());
  1681. }
  1682. sptr = sptr->_base;
  1683. }
  1684. }
  1685. bool GDScriptInstance::has_method(const StringName &p_method) const {
  1686. const GDScript *sptr = script.ptr();
  1687. while (sptr) {
  1688. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_method);
  1689. if (E) {
  1690. return true;
  1691. }
  1692. sptr = sptr->_base;
  1693. }
  1694. return false;
  1695. }
  1696. int GDScriptInstance::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  1697. const GDScript *sptr = script.ptr();
  1698. while (sptr) {
  1699. HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(p_method);
  1700. if (E) {
  1701. if (r_is_valid) {
  1702. *r_is_valid = true;
  1703. }
  1704. return E->value->get_argument_count();
  1705. }
  1706. sptr = sptr->_base;
  1707. }
  1708. if (r_is_valid) {
  1709. *r_is_valid = false;
  1710. }
  1711. return 0;
  1712. }
  1713. void GDScriptInstance::_call_implicit_ready_recursively(GDScript *p_script) {
  1714. // Call base class first.
  1715. if (p_script->_base) {
  1716. _call_implicit_ready_recursively(p_script->_base);
  1717. }
  1718. if (likely(p_script->valid) && p_script->implicit_ready) {
  1719. Callable::CallError err;
  1720. p_script->implicit_ready->call(this, nullptr, 0, err);
  1721. }
  1722. }
  1723. Variant GDScriptInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1724. GDScript *sptr = script.ptr();
  1725. if (unlikely(p_method == SceneStringName(_ready))) {
  1726. // Call implicit ready first, including for the super classes recursively.
  1727. _call_implicit_ready_recursively(sptr);
  1728. }
  1729. while (sptr) {
  1730. if (likely(sptr->valid)) {
  1731. HashMap<StringName, GDScriptFunction *>::Iterator E = sptr->member_functions.find(p_method);
  1732. if (E) {
  1733. return E->value->call(this, p_args, p_argcount, r_error);
  1734. }
  1735. }
  1736. sptr = sptr->_base;
  1737. }
  1738. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1739. return Variant();
  1740. }
  1741. void GDScriptInstance::notification(int p_notification, bool p_reversed) {
  1742. if (unlikely(!script->valid)) {
  1743. return;
  1744. }
  1745. //notification is not virtual, it gets called at ALL levels just like in C.
  1746. Variant value = p_notification;
  1747. const Variant *args[1] = { &value };
  1748. List<GDScript *> pl;
  1749. GDScript *sptr = script.ptr();
  1750. while (sptr) {
  1751. if (p_reversed) {
  1752. pl.push_back(sptr);
  1753. } else {
  1754. pl.push_front(sptr);
  1755. }
  1756. sptr = sptr->_base;
  1757. }
  1758. for (GDScript *sc : pl) {
  1759. if (likely(sc->valid)) {
  1760. HashMap<StringName, GDScriptFunction *>::Iterator E = sc->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  1761. if (E) {
  1762. Callable::CallError err;
  1763. E->value->call(this, args, 1, err);
  1764. if (err.error != Callable::CallError::CALL_OK) {
  1765. //print error about notification call
  1766. }
  1767. }
  1768. }
  1769. }
  1770. }
  1771. String GDScriptInstance::to_string(bool *r_valid) {
  1772. if (has_method(CoreStringName(_to_string))) {
  1773. Callable::CallError ce;
  1774. Variant ret = callp(CoreStringName(_to_string), nullptr, 0, ce);
  1775. if (ce.error == Callable::CallError::CALL_OK) {
  1776. if (ret.get_type() != Variant::STRING) {
  1777. if (r_valid) {
  1778. *r_valid = false;
  1779. }
  1780. ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringName(_to_string) + ", must be a String.");
  1781. }
  1782. if (r_valid) {
  1783. *r_valid = true;
  1784. }
  1785. return ret.operator String();
  1786. }
  1787. }
  1788. if (r_valid) {
  1789. *r_valid = false;
  1790. }
  1791. return String();
  1792. }
  1793. Ref<Script> GDScriptInstance::get_script() const {
  1794. return script;
  1795. }
  1796. ScriptLanguage *GDScriptInstance::get_language() {
  1797. return GDScriptLanguage::get_singleton();
  1798. }
  1799. const Variant GDScriptInstance::get_rpc_config() const {
  1800. return script->get_rpc_config();
  1801. }
  1802. void GDScriptInstance::reload_members() {
  1803. #ifdef DEBUG_ENABLED
  1804. Vector<Variant> new_members;
  1805. new_members.resize(script->member_indices.size());
  1806. //pass the values to the new indices
  1807. for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
  1808. if (member_indices_cache.has(E.key)) {
  1809. Variant value = members[member_indices_cache[E.key]];
  1810. new_members.write[E.value.index] = value;
  1811. }
  1812. }
  1813. members.resize(new_members.size()); //resize
  1814. //apply
  1815. members = new_members;
  1816. //pass the values to the new indices
  1817. member_indices_cache.clear();
  1818. for (const KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
  1819. member_indices_cache[E.key] = E.value.index;
  1820. }
  1821. #endif
  1822. }
  1823. GDScriptInstance::GDScriptInstance() {
  1824. owner = nullptr;
  1825. base_ref_counted = false;
  1826. }
  1827. GDScriptInstance::~GDScriptInstance() {
  1828. MutexLock lock(GDScriptLanguage::get_singleton()->mutex);
  1829. while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
  1830. // Order matters since clearing the stack may already cause
  1831. // the GDSCriptFunctionState to be destroyed and thus removed from the list.
  1832. pending_func_states.remove(E);
  1833. GDScriptFunctionState *state = E->self();
  1834. ObjectID state_id = state->get_instance_id();
  1835. state->_clear_connections();
  1836. if (ObjectDB::get_instance(state_id)) {
  1837. state->_clear_stack();
  1838. }
  1839. }
  1840. if (script.is_valid() && owner) {
  1841. script->instances.erase(owner);
  1842. }
  1843. }
  1844. /************* SCRIPT LANGUAGE **************/
  1845. GDScriptLanguage *GDScriptLanguage::singleton = nullptr;
  1846. String GDScriptLanguage::get_name() const {
  1847. return "GDScript";
  1848. }
  1849. /* LANGUAGE FUNCTIONS */
  1850. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  1851. if (globals.has(p_name)) {
  1852. //overwrite existing
  1853. global_array.write[globals[p_name]] = p_value;
  1854. return;
  1855. }
  1856. if (global_array_empty_indexes.size()) {
  1857. int index = global_array_empty_indexes[global_array_empty_indexes.size() - 1];
  1858. globals[p_name] = index;
  1859. global_array.write[index] = p_value;
  1860. global_array_empty_indexes.resize(global_array_empty_indexes.size() - 1);
  1861. } else {
  1862. globals[p_name] = global_array.size();
  1863. global_array.push_back(p_value);
  1864. _global_array = global_array.ptrw();
  1865. }
  1866. }
  1867. void GDScriptLanguage::_remove_global(const StringName &p_name) {
  1868. if (!globals.has(p_name)) {
  1869. return;
  1870. }
  1871. global_array_empty_indexes.push_back(globals[p_name]);
  1872. global_array.write[globals[p_name]] = Variant::NIL;
  1873. globals.erase(p_name);
  1874. }
  1875. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  1876. _add_global(p_variable, p_value);
  1877. }
  1878. void GDScriptLanguage::add_named_global_constant(const StringName &p_name, const Variant &p_value) {
  1879. named_globals[p_name] = p_value;
  1880. }
  1881. Variant GDScriptLanguage::get_any_global_constant(const StringName &p_name) {
  1882. if (named_globals.has(p_name)) {
  1883. return named_globals[p_name];
  1884. }
  1885. if (globals.has(p_name)) {
  1886. return _global_array[globals[p_name]];
  1887. }
  1888. ERR_FAIL_V_MSG(Variant(), vformat("Could not find any global constant with name: %s.", p_name));
  1889. }
  1890. void GDScriptLanguage::remove_named_global_constant(const StringName &p_name) {
  1891. ERR_FAIL_COND(!named_globals.has(p_name));
  1892. named_globals.erase(p_name);
  1893. }
  1894. void GDScriptLanguage::init() {
  1895. //populate global constants
  1896. int gcc = CoreConstants::get_global_constant_count();
  1897. for (int i = 0; i < gcc; i++) {
  1898. _add_global(StaticCString::create(CoreConstants::get_global_constant_name(i)), CoreConstants::get_global_constant_value(i));
  1899. }
  1900. _add_global(StaticCString::create("PI"), Math_PI);
  1901. _add_global(StaticCString::create("TAU"), Math_TAU);
  1902. _add_global(StaticCString::create("INF"), INFINITY);
  1903. _add_global(StaticCString::create("NAN"), NAN);
  1904. //populate native classes
  1905. List<StringName> class_list;
  1906. ClassDB::get_class_list(&class_list);
  1907. for (const StringName &n : class_list) {
  1908. if (globals.has(n)) {
  1909. continue;
  1910. }
  1911. Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(n));
  1912. _add_global(n, nc);
  1913. }
  1914. //populate singletons
  1915. List<Engine::Singleton> singletons;
  1916. Engine::get_singleton()->get_singletons(&singletons);
  1917. for (const Engine::Singleton &E : singletons) {
  1918. _add_global(E.name, E.ptr);
  1919. }
  1920. #ifdef TOOLS_ENABLED
  1921. if (Engine::get_singleton()->is_editor_hint()) {
  1922. GDExtensionManager::get_singleton()->connect("extension_loaded", callable_mp(this, &GDScriptLanguage::_extension_loaded));
  1923. GDExtensionManager::get_singleton()->connect("extension_unloading", callable_mp(this, &GDScriptLanguage::_extension_unloading));
  1924. }
  1925. #endif
  1926. #ifdef TESTS_ENABLED
  1927. GDScriptTests::GDScriptTestRunner::handle_cmdline();
  1928. #endif
  1929. }
  1930. #ifdef TOOLS_ENABLED
  1931. void GDScriptLanguage::_extension_loaded(const Ref<GDExtension> &p_extension) {
  1932. List<StringName> class_list;
  1933. ClassDB::get_extension_class_list(p_extension, &class_list);
  1934. for (const StringName &n : class_list) {
  1935. if (globals.has(n)) {
  1936. continue;
  1937. }
  1938. Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(n));
  1939. _add_global(n, nc);
  1940. }
  1941. }
  1942. void GDScriptLanguage::_extension_unloading(const Ref<GDExtension> &p_extension) {
  1943. List<StringName> class_list;
  1944. ClassDB::get_extension_class_list(p_extension, &class_list);
  1945. for (const StringName &n : class_list) {
  1946. _remove_global(n);
  1947. }
  1948. }
  1949. #endif
  1950. String GDScriptLanguage::get_type() const {
  1951. return "GDScript";
  1952. }
  1953. String GDScriptLanguage::get_extension() const {
  1954. return "gd";
  1955. }
  1956. void GDScriptLanguage::finish() {
  1957. if (finishing) {
  1958. return;
  1959. }
  1960. finishing = true;
  1961. _call_stack.free();
  1962. // Clear the cache before parsing the script_list
  1963. GDScriptCache::clear();
  1964. // Clear dependencies between scripts, to ensure cyclic references are broken
  1965. // (to avoid leaks at exit).
  1966. SelfList<GDScript> *s = script_list.first();
  1967. while (s) {
  1968. // This ensures the current script is not released before we can check
  1969. // what's the next one in the list (we can't get the next upfront because we
  1970. // don't know if the reference breaking will cause it -or any other after
  1971. // it, for that matter- to be released so the next one is not the same as
  1972. // before).
  1973. Ref<GDScript> scr = s->self();
  1974. if (scr.is_valid()) {
  1975. for (KeyValue<StringName, GDScriptFunction *> &E : scr->member_functions) {
  1976. GDScriptFunction *func = E.value;
  1977. for (int i = 0; i < func->argument_types.size(); i++) {
  1978. func->argument_types.write[i].script_type_ref = Ref<Script>();
  1979. }
  1980. func->return_type.script_type_ref = Ref<Script>();
  1981. }
  1982. for (KeyValue<StringName, GDScript::MemberInfo> &E : scr->member_indices) {
  1983. E.value.data_type.script_type_ref = Ref<Script>();
  1984. }
  1985. // Clear backup for scripts that could slip out of the cyclic reference
  1986. // check
  1987. scr->clear();
  1988. }
  1989. s = s->next();
  1990. }
  1991. script_list.clear();
  1992. function_list.clear();
  1993. finishing = false;
  1994. }
  1995. void GDScriptLanguage::profiling_start() {
  1996. #ifdef DEBUG_ENABLED
  1997. MutexLock lock(mutex);
  1998. SelfList<GDScriptFunction> *elem = function_list.first();
  1999. while (elem) {
  2000. elem->self()->profile.call_count.set(0);
  2001. elem->self()->profile.self_time.set(0);
  2002. elem->self()->profile.total_time.set(0);
  2003. elem->self()->profile.frame_call_count.set(0);
  2004. elem->self()->profile.frame_self_time.set(0);
  2005. elem->self()->profile.frame_total_time.set(0);
  2006. elem->self()->profile.last_frame_call_count = 0;
  2007. elem->self()->profile.last_frame_self_time = 0;
  2008. elem->self()->profile.last_frame_total_time = 0;
  2009. elem->self()->profile.native_calls.clear();
  2010. elem->self()->profile.last_native_calls.clear();
  2011. elem = elem->next();
  2012. }
  2013. profiling = true;
  2014. #endif
  2015. }
  2016. void GDScriptLanguage::profiling_set_save_native_calls(bool p_enable) {
  2017. #ifdef DEBUG_ENABLED
  2018. MutexLock lock(mutex);
  2019. profile_native_calls = p_enable;
  2020. #endif
  2021. }
  2022. void GDScriptLanguage::profiling_stop() {
  2023. #ifdef DEBUG_ENABLED
  2024. MutexLock lock(mutex);
  2025. profiling = false;
  2026. #endif
  2027. }
  2028. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  2029. int current = 0;
  2030. #ifdef DEBUG_ENABLED
  2031. MutexLock lock(mutex);
  2032. profiling_collate_native_call_data(true);
  2033. SelfList<GDScriptFunction> *elem = function_list.first();
  2034. while (elem) {
  2035. if (current >= p_info_max) {
  2036. break;
  2037. }
  2038. int last_non_internal = current;
  2039. p_info_arr[current].call_count = elem->self()->profile.call_count.get();
  2040. p_info_arr[current].self_time = elem->self()->profile.self_time.get();
  2041. p_info_arr[current].total_time = elem->self()->profile.total_time.get();
  2042. p_info_arr[current].signature = elem->self()->profile.signature;
  2043. current++;
  2044. int nat_time = 0;
  2045. HashMap<String, GDScriptFunction::Profile::NativeProfile>::ConstIterator nat_calls = elem->self()->profile.native_calls.begin();
  2046. while (nat_calls) {
  2047. p_info_arr[current].call_count = nat_calls->value.call_count;
  2048. p_info_arr[current].total_time = nat_calls->value.total_time;
  2049. p_info_arr[current].self_time = nat_calls->value.total_time;
  2050. p_info_arr[current].signature = nat_calls->value.signature;
  2051. nat_time += nat_calls->value.total_time;
  2052. current++;
  2053. ++nat_calls;
  2054. }
  2055. p_info_arr[last_non_internal].internal_time = nat_time;
  2056. elem = elem->next();
  2057. }
  2058. #endif
  2059. return current;
  2060. }
  2061. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  2062. int current = 0;
  2063. #ifdef DEBUG_ENABLED
  2064. MutexLock lock(mutex);
  2065. profiling_collate_native_call_data(false);
  2066. SelfList<GDScriptFunction> *elem = function_list.first();
  2067. while (elem) {
  2068. if (current >= p_info_max) {
  2069. break;
  2070. }
  2071. if (elem->self()->profile.last_frame_call_count > 0) {
  2072. int last_non_internal = current;
  2073. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  2074. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  2075. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  2076. p_info_arr[current].signature = elem->self()->profile.signature;
  2077. current++;
  2078. int nat_time = 0;
  2079. HashMap<String, GDScriptFunction::Profile::NativeProfile>::ConstIterator nat_calls = elem->self()->profile.last_native_calls.begin();
  2080. while (nat_calls) {
  2081. p_info_arr[current].call_count = nat_calls->value.call_count;
  2082. p_info_arr[current].total_time = nat_calls->value.total_time;
  2083. p_info_arr[current].self_time = nat_calls->value.total_time;
  2084. p_info_arr[current].internal_time = nat_calls->value.total_time;
  2085. p_info_arr[current].signature = nat_calls->value.signature;
  2086. nat_time += nat_calls->value.total_time;
  2087. current++;
  2088. ++nat_calls;
  2089. }
  2090. p_info_arr[last_non_internal].internal_time = nat_time;
  2091. }
  2092. elem = elem->next();
  2093. }
  2094. #endif
  2095. return current;
  2096. }
  2097. void GDScriptLanguage::profiling_collate_native_call_data(bool p_accumulated) {
  2098. #ifdef DEBUG_ENABLED
  2099. // The same native call can be called from multiple functions, so join them together here.
  2100. // Only use the name of the function (ie signature.split[2]).
  2101. HashMap<String, GDScriptFunction::Profile::NativeProfile *> seen_nat_calls;
  2102. SelfList<GDScriptFunction> *elem = function_list.first();
  2103. while (elem) {
  2104. HashMap<String, GDScriptFunction::Profile::NativeProfile> *nat_calls = p_accumulated ? &elem->self()->profile.native_calls : &elem->self()->profile.last_native_calls;
  2105. HashMap<String, GDScriptFunction::Profile::NativeProfile>::Iterator it = nat_calls->begin();
  2106. while (it != nat_calls->end()) {
  2107. Vector<String> sig = it->value.signature.split("::");
  2108. HashMap<String, GDScriptFunction::Profile::NativeProfile *>::ConstIterator already_found = seen_nat_calls.find(sig[2]);
  2109. if (already_found) {
  2110. already_found->value->total_time += it->value.total_time;
  2111. already_found->value->call_count += it->value.call_count;
  2112. elem->self()->profile.last_native_calls.remove(it);
  2113. } else {
  2114. seen_nat_calls.insert(sig[2], &it->value);
  2115. }
  2116. ++it;
  2117. }
  2118. elem = elem->next();
  2119. }
  2120. #endif
  2121. }
  2122. struct GDScriptDepSort {
  2123. //must support sorting so inheritance works properly (parent must be reloaded first)
  2124. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  2125. if (A == B) {
  2126. return false; //shouldn't happen but..
  2127. }
  2128. const GDScript *I = B->get_base().ptr();
  2129. while (I) {
  2130. if (I == A.ptr()) {
  2131. // A is a base of B
  2132. return true;
  2133. }
  2134. I = I->get_base().ptr();
  2135. }
  2136. return false; //not a base
  2137. }
  2138. };
  2139. void GDScriptLanguage::reload_all_scripts() {
  2140. #ifdef DEBUG_ENABLED
  2141. print_verbose("GDScript: Reloading all scripts");
  2142. Array scripts;
  2143. {
  2144. MutexLock lock(mutex);
  2145. SelfList<GDScript> *elem = script_list.first();
  2146. while (elem) {
  2147. if (elem->self()->get_path().is_resource_file()) {
  2148. print_verbose("GDScript: Found: " + elem->self()->get_path());
  2149. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  2150. }
  2151. elem = elem->next();
  2152. }
  2153. #ifdef TOOLS_ENABLED
  2154. if (Engine::get_singleton()->is_editor_hint()) {
  2155. // Reload all pointers to existing singletons so that tool scripts can work with the reloaded extensions.
  2156. List<Engine::Singleton> singletons;
  2157. Engine::get_singleton()->get_singletons(&singletons);
  2158. for (const Engine::Singleton &E : singletons) {
  2159. if (globals.has(E.name)) {
  2160. _add_global(E.name, E.ptr);
  2161. }
  2162. }
  2163. }
  2164. #endif
  2165. }
  2166. reload_scripts(scripts, true);
  2167. #endif
  2168. }
  2169. void GDScriptLanguage::reload_scripts(const Array &p_scripts, bool p_soft_reload) {
  2170. #ifdef DEBUG_ENABLED
  2171. List<Ref<GDScript>> scripts;
  2172. {
  2173. MutexLock lock(mutex);
  2174. SelfList<GDScript> *elem = script_list.first();
  2175. while (elem) {
  2176. // Scripts will reload all subclasses, so only reload root scripts.
  2177. if (elem->self()->is_root_script() && !elem->self()->get_path().is_empty()) {
  2178. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  2179. }
  2180. elem = elem->next();
  2181. }
  2182. }
  2183. //when someone asks you why dynamically typed languages are easier to write....
  2184. HashMap<Ref<GDScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> to_reload;
  2185. //as scripts are going to be reloaded, must proceed without locking here
  2186. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  2187. for (Ref<GDScript> &scr : scripts) {
  2188. bool reload = p_scripts.has(scr) || to_reload.has(scr->get_base());
  2189. if (!reload) {
  2190. continue;
  2191. }
  2192. to_reload.insert(scr, HashMap<ObjectID, List<Pair<StringName, Variant>>>());
  2193. if (!p_soft_reload) {
  2194. //save state and remove script from instances
  2195. HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[scr];
  2196. while (scr->instances.front()) {
  2197. Object *obj = scr->instances.front()->get();
  2198. //save instance info
  2199. List<Pair<StringName, Variant>> state;
  2200. if (obj->get_script_instance()) {
  2201. obj->get_script_instance()->get_property_state(state);
  2202. map[obj->get_instance_id()] = state;
  2203. obj->set_script(Variant());
  2204. }
  2205. }
  2206. //same thing for placeholders
  2207. #ifdef TOOLS_ENABLED
  2208. while (scr->placeholders.size()) {
  2209. Object *obj = (*scr->placeholders.begin())->get_owner();
  2210. //save instance info
  2211. if (obj->get_script_instance()) {
  2212. map.insert(obj->get_instance_id(), List<Pair<StringName, Variant>>());
  2213. List<Pair<StringName, Variant>> &state = map[obj->get_instance_id()];
  2214. obj->get_script_instance()->get_property_state(state);
  2215. obj->set_script(Variant());
  2216. } else {
  2217. // no instance found. Let's remove it so we don't loop forever
  2218. scr->placeholders.erase(*scr->placeholders.begin());
  2219. }
  2220. }
  2221. #endif
  2222. for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : scr->pending_reload_state) {
  2223. map[F.key] = F.value; //pending to reload, use this one instead
  2224. }
  2225. }
  2226. }
  2227. for (KeyValue<Ref<GDScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> &E : to_reload) {
  2228. Ref<GDScript> scr = E.key;
  2229. print_verbose("GDScript: Reloading: " + scr->get_path());
  2230. if (scr->is_built_in()) {
  2231. // TODO: It would be nice to do it more efficiently than loading the whole scene again.
  2232. Ref<PackedScene> scene = ResourceLoader::load(scr->get_path().get_slice("::", 0), "", ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP);
  2233. ERR_CONTINUE(scene.is_null());
  2234. Ref<SceneState> state = scene->get_state();
  2235. Ref<GDScript> fresh = state->get_sub_resource(scr->get_path());
  2236. ERR_CONTINUE(fresh.is_null());
  2237. scr->set_source_code(fresh->get_source_code());
  2238. } else {
  2239. scr->load_source_code(scr->get_path());
  2240. }
  2241. scr->reload(p_soft_reload);
  2242. //restore state if saved
  2243. for (KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : E.value) {
  2244. List<Pair<StringName, Variant>> &saved_state = F.value;
  2245. Object *obj = ObjectDB::get_instance(F.key);
  2246. if (!obj) {
  2247. continue;
  2248. }
  2249. if (!p_soft_reload) {
  2250. //clear it just in case (may be a pending reload state)
  2251. obj->set_script(Variant());
  2252. }
  2253. obj->set_script(scr);
  2254. ScriptInstance *script_inst = obj->get_script_instance();
  2255. if (!script_inst) {
  2256. //failed, save reload state for next time if not saved
  2257. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  2258. scr->pending_reload_state[obj->get_instance_id()] = saved_state;
  2259. }
  2260. continue;
  2261. }
  2262. if (script_inst->is_placeholder() && scr->is_placeholder_fallback_enabled()) {
  2263. PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_inst);
  2264. for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
  2265. placeholder->property_set_fallback(G->get().first, G->get().second);
  2266. }
  2267. } else {
  2268. for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
  2269. script_inst->set(G->get().first, G->get().second);
  2270. }
  2271. }
  2272. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  2273. }
  2274. //if instance states were saved, set them!
  2275. }
  2276. #endif
  2277. }
  2278. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  2279. Array scripts;
  2280. scripts.push_back(p_script);
  2281. reload_scripts(scripts, p_soft_reload);
  2282. }
  2283. void GDScriptLanguage::frame() {
  2284. calls = 0;
  2285. #ifdef DEBUG_ENABLED
  2286. if (profiling) {
  2287. MutexLock lock(mutex);
  2288. SelfList<GDScriptFunction> *elem = function_list.first();
  2289. while (elem) {
  2290. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count.get();
  2291. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time.get();
  2292. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time.get();
  2293. elem->self()->profile.last_native_calls = elem->self()->profile.native_calls;
  2294. elem->self()->profile.frame_call_count.set(0);
  2295. elem->self()->profile.frame_self_time.set(0);
  2296. elem->self()->profile.frame_total_time.set(0);
  2297. elem->self()->profile.native_calls.clear();
  2298. elem = elem->next();
  2299. }
  2300. }
  2301. #endif
  2302. }
  2303. /* EDITOR FUNCTIONS */
  2304. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  2305. // Please keep alphabetical order within categories.
  2306. static const char *_reserved_words[] = {
  2307. // Control flow.
  2308. "break",
  2309. "continue",
  2310. "elif",
  2311. "else",
  2312. "for",
  2313. "if",
  2314. "match",
  2315. "pass",
  2316. "return",
  2317. "when",
  2318. "while",
  2319. // Declarations.
  2320. "class",
  2321. "class_name",
  2322. "const",
  2323. "enum",
  2324. "extends",
  2325. "func",
  2326. "namespace", // Reserved for potential future use.
  2327. "signal",
  2328. "static",
  2329. "trait", // Reserved for potential future use.
  2330. "var",
  2331. // Other keywords.
  2332. "await",
  2333. "breakpoint",
  2334. "self",
  2335. "super",
  2336. "yield", // Reserved for potential future use.
  2337. // Operators.
  2338. "and",
  2339. "as",
  2340. "in",
  2341. "is",
  2342. "not",
  2343. "or",
  2344. // Special values (tokenizer treats them as literals, not as tokens).
  2345. "false",
  2346. "null",
  2347. "true",
  2348. // Constants.
  2349. "INF",
  2350. "NAN",
  2351. "PI",
  2352. "TAU",
  2353. // Functions (highlighter uses global function color instead).
  2354. "assert",
  2355. "preload",
  2356. // Types (highlighter uses type color instead).
  2357. "void",
  2358. nullptr,
  2359. };
  2360. const char **w = _reserved_words;
  2361. while (*w) {
  2362. p_words->push_back(*w);
  2363. w++;
  2364. }
  2365. }
  2366. bool GDScriptLanguage::is_control_flow_keyword(const String &p_keyword) const {
  2367. // Please keep alphabetical order.
  2368. return p_keyword == "break" ||
  2369. p_keyword == "continue" ||
  2370. p_keyword == "elif" ||
  2371. p_keyword == "else" ||
  2372. p_keyword == "for" ||
  2373. p_keyword == "if" ||
  2374. p_keyword == "match" ||
  2375. p_keyword == "pass" ||
  2376. p_keyword == "return" ||
  2377. p_keyword == "when" ||
  2378. p_keyword == "while";
  2379. }
  2380. bool GDScriptLanguage::handles_global_class_type(const String &p_type) const {
  2381. return p_type == "GDScript";
  2382. }
  2383. String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
  2384. Error err;
  2385. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  2386. if (err) {
  2387. return String();
  2388. }
  2389. String source = f->get_as_utf8_string();
  2390. GDScriptParser parser;
  2391. err = parser.parse(source, p_path, false, false);
  2392. const GDScriptParser::ClassNode *c = parser.get_tree();
  2393. if (!c) {
  2394. return String(); // No class parsed.
  2395. }
  2396. /* **WARNING**
  2397. *
  2398. * This function is written with the goal to be *extremely* error tolerant, as such
  2399. * it should meet the following requirements:
  2400. *
  2401. * - It must not rely on the analyzer (in fact, the analyzer must not be used here),
  2402. * because at the time global classes are parsed, the dependencies may not be present
  2403. * yet, hence the function will fail (which is unintended).
  2404. * - It must not fail even if the parsing fails, because even if the file is broken,
  2405. * it should attempt its best to retrieve the inheritance metadata.
  2406. *
  2407. * Before changing this function, please ask the current maintainer of EditorFileSystem.
  2408. */
  2409. if (r_base_type) {
  2410. const GDScriptParser::ClassNode *subclass = c;
  2411. String path = p_path;
  2412. GDScriptParser subparser;
  2413. while (subclass) {
  2414. if (subclass->extends_used) {
  2415. if (!subclass->extends_path.is_empty()) {
  2416. if (subclass->extends.size() == 0) {
  2417. get_global_class_name(subclass->extends_path, r_base_type);
  2418. subclass = nullptr;
  2419. break;
  2420. } else {
  2421. Vector<GDScriptParser::IdentifierNode *> extend_classes = subclass->extends;
  2422. Ref<FileAccess> subfile = FileAccess::open(subclass->extends_path, FileAccess::READ);
  2423. if (subfile.is_null()) {
  2424. break;
  2425. }
  2426. String subsource = subfile->get_as_utf8_string();
  2427. if (subsource.is_empty()) {
  2428. break;
  2429. }
  2430. String subpath = subclass->extends_path;
  2431. if (subpath.is_relative_path()) {
  2432. subpath = path.get_base_dir().path_join(subpath).simplify_path();
  2433. }
  2434. if (OK != subparser.parse(subsource, subpath, false)) {
  2435. break;
  2436. }
  2437. path = subpath;
  2438. subclass = subparser.get_tree();
  2439. while (extend_classes.size() > 0) {
  2440. bool found = false;
  2441. for (int i = 0; i < subclass->members.size(); i++) {
  2442. if (subclass->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
  2443. continue;
  2444. }
  2445. const GDScriptParser::ClassNode *inner_class = subclass->members[i].m_class;
  2446. if (inner_class->identifier->name == extend_classes[0]->name) {
  2447. extend_classes.remove_at(0);
  2448. found = true;
  2449. subclass = inner_class;
  2450. break;
  2451. }
  2452. }
  2453. if (!found) {
  2454. subclass = nullptr;
  2455. break;
  2456. }
  2457. }
  2458. }
  2459. } else if (subclass->extends.size() == 1) {
  2460. *r_base_type = subclass->extends[0]->name;
  2461. subclass = nullptr;
  2462. } else {
  2463. break;
  2464. }
  2465. } else {
  2466. *r_base_type = "RefCounted";
  2467. subclass = nullptr;
  2468. }
  2469. }
  2470. }
  2471. if (r_icon_path) {
  2472. *r_icon_path = c->simplified_icon_path;
  2473. }
  2474. return c->identifier != nullptr ? String(c->identifier->name) : String();
  2475. }
  2476. thread_local GDScriptLanguage::CallStack GDScriptLanguage::_call_stack;
  2477. GDScriptLanguage::GDScriptLanguage() {
  2478. calls = 0;
  2479. ERR_FAIL_COND(singleton);
  2480. singleton = this;
  2481. strings._init = StaticCString::create("_init");
  2482. strings._static_init = StaticCString::create("_static_init");
  2483. strings._notification = StaticCString::create("_notification");
  2484. strings._set = StaticCString::create("_set");
  2485. strings._get = StaticCString::create("_get");
  2486. strings._get_property_list = StaticCString::create("_get_property_list");
  2487. strings._validate_property = StaticCString::create("_validate_property");
  2488. strings._property_can_revert = StaticCString::create("_property_can_revert");
  2489. strings._property_get_revert = StaticCString::create("_property_get_revert");
  2490. strings._script_source = StaticCString::create("script/source");
  2491. _debug_parse_err_line = -1;
  2492. _debug_parse_err_file = "";
  2493. #ifdef DEBUG_ENABLED
  2494. profiling = false;
  2495. profile_native_calls = false;
  2496. script_frame_time = 0;
  2497. #endif
  2498. int dmcs = GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/settings/gdscript/max_call_stack", PROPERTY_HINT_RANGE, "512," + itos(GDScriptFunction::MAX_CALL_DEPTH - 1) + ",1"), 1024);
  2499. if (EngineDebugger::is_active()) {
  2500. //debugging enabled!
  2501. _debug_max_call_stack = dmcs;
  2502. } else {
  2503. _debug_max_call_stack = 0;
  2504. }
  2505. #ifdef DEBUG_ENABLED
  2506. GLOBAL_DEF("debug/gdscript/warnings/enable", true);
  2507. GLOBAL_DEF("debug/gdscript/warnings/exclude_addons", true);
  2508. for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
  2509. GDScriptWarning::Code code = (GDScriptWarning::Code)i;
  2510. Variant default_enabled = GDScriptWarning::get_default_value(code);
  2511. String path = GDScriptWarning::get_settings_path_from_code(code);
  2512. GLOBAL_DEF(GDScriptWarning::get_property_info(code), default_enabled);
  2513. }
  2514. #endif // DEBUG_ENABLED
  2515. }
  2516. GDScriptLanguage::~GDScriptLanguage() {
  2517. singleton = nullptr;
  2518. }
  2519. void GDScriptLanguage::add_orphan_subclass(const String &p_qualified_name, const ObjectID &p_subclass) {
  2520. orphan_subclasses[p_qualified_name] = p_subclass;
  2521. }
  2522. Ref<GDScript> GDScriptLanguage::get_orphan_subclass(const String &p_qualified_name) {
  2523. HashMap<String, ObjectID>::Iterator orphan_subclass_element = orphan_subclasses.find(p_qualified_name);
  2524. if (!orphan_subclass_element) {
  2525. return Ref<GDScript>();
  2526. }
  2527. ObjectID orphan_subclass = orphan_subclass_element->value;
  2528. Object *obj = ObjectDB::get_instance(orphan_subclass);
  2529. orphan_subclasses.remove(orphan_subclass_element);
  2530. if (!obj) {
  2531. return Ref<GDScript>();
  2532. }
  2533. return Ref<GDScript>(Object::cast_to<GDScript>(obj));
  2534. }
  2535. Ref<GDScript> GDScriptLanguage::get_script_by_fully_qualified_name(const String &p_name) {
  2536. {
  2537. MutexLock lock(mutex);
  2538. SelfList<GDScript> *elem = script_list.first();
  2539. while (elem) {
  2540. GDScript *scr = elem->self();
  2541. if (scr->fully_qualified_name == p_name) {
  2542. return scr;
  2543. }
  2544. elem = elem->next();
  2545. }
  2546. }
  2547. Ref<GDScript> scr;
  2548. scr.instantiate();
  2549. scr->fully_qualified_name = p_name;
  2550. return scr;
  2551. }
  2552. /*************** RESOURCE ***************/
  2553. Ref<Resource> ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  2554. Error err;
  2555. bool ignoring = p_cache_mode == CACHE_MODE_IGNORE || p_cache_mode == CACHE_MODE_IGNORE_DEEP;
  2556. Ref<GDScript> scr = GDScriptCache::get_full_script(p_original_path, err, "", ignoring);
  2557. if (err && scr.is_valid()) {
  2558. // If !scr.is_valid(), the error was likely from scr->load_source_code(), which already generates an error.
  2559. ERR_PRINT_ED(vformat(R"(Failed to load script "%s" with error "%s".)", p_original_path, error_names[err]));
  2560. }
  2561. if (r_error) {
  2562. // Don't fail loading because of parsing error.
  2563. *r_error = scr.is_valid() ? OK : err;
  2564. }
  2565. return scr;
  2566. }
  2567. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  2568. p_extensions->push_back("gd");
  2569. p_extensions->push_back("gdc");
  2570. }
  2571. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  2572. return (p_type == "Script" || p_type == "GDScript");
  2573. }
  2574. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  2575. String el = p_path.get_extension().to_lower();
  2576. if (el == "gd" || el == "gdc") {
  2577. return "GDScript";
  2578. }
  2579. return "";
  2580. }
  2581. void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  2582. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
  2583. ERR_FAIL_COND_MSG(file.is_null(), "Cannot open file '" + p_path + "'.");
  2584. String source = file->get_as_utf8_string();
  2585. if (source.is_empty()) {
  2586. return;
  2587. }
  2588. GDScriptParser parser;
  2589. if (OK != parser.parse(source, p_path, false)) {
  2590. return;
  2591. }
  2592. for (const String &E : parser.get_dependencies()) {
  2593. p_dependencies->push_back(E);
  2594. }
  2595. }
  2596. Error ResourceFormatSaverGDScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  2597. Ref<GDScript> sqscr = p_resource;
  2598. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2599. String source = sqscr->get_source_code();
  2600. {
  2601. Error err;
  2602. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2603. ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'.");
  2604. file->store_string(source);
  2605. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2606. return ERR_CANT_CREATE;
  2607. }
  2608. }
  2609. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2610. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, true);
  2611. }
  2612. return OK;
  2613. }
  2614. void ResourceFormatSaverGDScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  2615. if (Object::cast_to<GDScript>(*p_resource)) {
  2616. p_extensions->push_back("gd");
  2617. }
  2618. }
  2619. bool ResourceFormatSaverGDScript::recognize(const Ref<Resource> &p_resource) const {
  2620. return Object::cast_to<GDScript>(*p_resource) != nullptr;
  2621. }