gdscript.cpp 67 KB

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