gdscript.cpp 65 KB

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