gdscript.cpp 87 KB

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