gdscript.cpp 84 KB

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