gdscript.cpp 74 KB

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