gdscript.cpp 83 KB

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