gdscript.cpp 82 KB

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