gdscript.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348
  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 (const KeyValue<StringName, MemberInfo> &E : member_indices) {
  110. instance->member_indices_cache[E.key] = E.value.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 KeyValue<StringName, GDScriptFunction *> &E : current->member_functions) {
  222. GDScriptFunction *func = E.value;
  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 (const KeyValue<StringName, PropertyInfo> &E : sptr->member_info) {
  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 (const KeyValue<StringName, Variant> &E : member_default_values_cache) {
  354. values[E.key] = E.value;
  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 (const KeyValue<String, DocData::EnumDoc> &E : doc_enums) {
  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], doc_signals[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 (const KeyValue<StringName, Variant> &E : constants) {
  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 (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  513. E.value->_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 (KeyValue<StringName, Ref<GDScript>> &E : p_sc->subclasses) {
  674. _set_subclass_path(E.value, 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(), false, 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(), false, 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(), false, 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(), false, ERR_HANDLER_WARNING, si);
  753. }
  754. }
  755. #endif
  756. valid = true;
  757. for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  758. _set_subclass_path(E.value, 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 (const KeyValue<StringName, Variant> &E : constants) {
  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 KeyValue<StringName, MemberInfo> &E : member_indices) {
  877. if (E.value.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 KeyValue<StringName, Vector<StringName>> &E : _signals) {
  916. MethodInfo mi;
  917. mi.name = E.key;
  918. for (int i = 0; i < E.value.size(); i++) {
  919. PropertyInfo arg;
  920. arg.name = E.value[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 (KeyValue<StringName, Ref<GDScript>> &E : subclasses) {
  970. E.value->_owner = nullptr; //bye, you are no longer owned cause I died
  971. ClassRefWithName subclass;
  972. subclass.id = E.value->get_instance_id();
  973. subclass.fully_qualified_name = E.value->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 (KeyValue<StringName, GDScriptFunction *> &E : cscript->member_functions) {
  1002. Multiplayer::RPCConfig config = E.value->get_rpc_config();
  1003. if (config.rpc_mode != Multiplayer::RPC_MODE_DISABLED) {
  1004. config.name = E.value->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 (const KeyValue<StringName, GDScriptFunction *> &E : member_functions) {
  1033. memdelete(E.value);
  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. } else {
  1068. return false;
  1069. }
  1070. } else {
  1071. if (member->data_type.has_type) {
  1072. if (member->data_type.builtin_type == Variant::ARRAY && member->data_type.has_container_element_type()) {
  1073. // Typed array.
  1074. if (p_value.get_type() == Variant::ARRAY) {
  1075. return VariantInternal::get_array(&members.write[member->index])->typed_assign(p_value);
  1076. } else {
  1077. return false;
  1078. }
  1079. } else if (!member->data_type.is_type(p_value)) {
  1080. // Try conversion
  1081. Callable::CallError ce;
  1082. const Variant *value = &p_value;
  1083. Variant converted;
  1084. Variant::construct(member->data_type.builtin_type, converted, &value, 1, ce);
  1085. if (ce.error == Callable::CallError::CALL_OK) {
  1086. members.write[member->index] = converted;
  1087. return true;
  1088. } else {
  1089. return false;
  1090. }
  1091. }
  1092. }
  1093. members.write[member->index] = p_value;
  1094. }
  1095. return true;
  1096. }
  1097. }
  1098. GDScript *sptr = script.ptr();
  1099. while (sptr) {
  1100. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  1101. if (E) {
  1102. Variant name = p_name;
  1103. const Variant *args[2] = { &name, &p_value };
  1104. Callable::CallError err;
  1105. Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
  1106. if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
  1107. return true;
  1108. }
  1109. }
  1110. sptr = sptr->_base;
  1111. }
  1112. return false;
  1113. }
  1114. bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
  1115. const GDScript *sptr = script.ptr();
  1116. while (sptr) {
  1117. {
  1118. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  1119. if (E) {
  1120. if (E->get().getter) {
  1121. Callable::CallError err;
  1122. r_ret = const_cast<GDScriptInstance *>(this)->call(E->get().getter, nullptr, 0, err);
  1123. if (err.error == Callable::CallError::CALL_OK) {
  1124. return true;
  1125. }
  1126. }
  1127. r_ret = members[E->get().index];
  1128. return true; //index found
  1129. }
  1130. }
  1131. {
  1132. const GDScript *sl = sptr;
  1133. while (sl) {
  1134. const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
  1135. if (E) {
  1136. r_ret = E->get();
  1137. return true; //index found
  1138. }
  1139. sl = sl->_base;
  1140. }
  1141. }
  1142. {
  1143. // Signals.
  1144. const GDScript *sl = sptr;
  1145. while (sl) {
  1146. const Map<StringName, Vector<StringName>>::Element *E = sl->_signals.find(p_name);
  1147. if (E) {
  1148. r_ret = Signal(this->owner, E->key());
  1149. return true; //index found
  1150. }
  1151. sl = sl->_base;
  1152. }
  1153. }
  1154. {
  1155. // Methods.
  1156. const GDScript *sl = sptr;
  1157. while (sl) {
  1158. const Map<StringName, GDScriptFunction *>::Element *E = sl->member_functions.find(p_name);
  1159. if (E) {
  1160. r_ret = Callable(this->owner, E->key());
  1161. return true; //index found
  1162. }
  1163. sl = sl->_base;
  1164. }
  1165. }
  1166. {
  1167. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  1168. if (E) {
  1169. Variant name = p_name;
  1170. const Variant *args[1] = { &name };
  1171. Callable::CallError err;
  1172. Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), (const Variant **)args, 1, err);
  1173. if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  1174. r_ret = ret;
  1175. return true;
  1176. }
  1177. }
  1178. }
  1179. sptr = sptr->_base;
  1180. }
  1181. return false;
  1182. }
  1183. Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1184. const GDScript *sptr = script.ptr();
  1185. while (sptr) {
  1186. if (sptr->member_info.has(p_name)) {
  1187. if (r_is_valid) {
  1188. *r_is_valid = true;
  1189. }
  1190. return sptr->member_info[p_name].type;
  1191. }
  1192. sptr = sptr->_base;
  1193. }
  1194. if (r_is_valid) {
  1195. *r_is_valid = false;
  1196. }
  1197. return Variant::NIL;
  1198. }
  1199. void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1200. // exported members, not done yet!
  1201. const GDScript *sptr = script.ptr();
  1202. List<PropertyInfo> props;
  1203. while (sptr) {
  1204. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  1205. if (E) {
  1206. Callable::CallError err;
  1207. Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), nullptr, 0, err);
  1208. if (err.error == Callable::CallError::CALL_OK) {
  1209. ERR_FAIL_COND_MSG(ret.get_type() != Variant::ARRAY, "Wrong type for _get_property_list, must be an array of dictionaries.");
  1210. Array arr = ret;
  1211. for (int i = 0; i < arr.size(); i++) {
  1212. Dictionary d = arr[i];
  1213. ERR_CONTINUE(!d.has("name"));
  1214. ERR_CONTINUE(!d.has("type"));
  1215. PropertyInfo pinfo;
  1216. pinfo.type = Variant::Type(d["type"].operator int());
  1217. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  1218. pinfo.name = d["name"];
  1219. ERR_CONTINUE(pinfo.name == "");
  1220. if (d.has("hint")) {
  1221. pinfo.hint = PropertyHint(d["hint"].operator int());
  1222. }
  1223. if (d.has("hint_string")) {
  1224. pinfo.hint_string = d["hint_string"];
  1225. }
  1226. if (d.has("usage")) {
  1227. pinfo.usage = d["usage"];
  1228. }
  1229. props.push_back(pinfo);
  1230. }
  1231. }
  1232. }
  1233. //instance a fake script for editing the values
  1234. Vector<_GDScriptMemberSort> msort;
  1235. for (const KeyValue<StringName, PropertyInfo> &F : sptr->member_info) {
  1236. _GDScriptMemberSort ms;
  1237. ERR_CONTINUE(!sptr->member_indices.has(F.key));
  1238. ms.index = sptr->member_indices[F.key].index;
  1239. ms.name = F.key;
  1240. msort.push_back(ms);
  1241. }
  1242. msort.sort();
  1243. msort.reverse();
  1244. for (int i = 0; i < msort.size(); i++) {
  1245. props.push_front(sptr->member_info[msort[i].name]);
  1246. }
  1247. sptr = sptr->_base;
  1248. }
  1249. for (const PropertyInfo &E : props) {
  1250. p_properties->push_back(E);
  1251. }
  1252. }
  1253. void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
  1254. const GDScript *sptr = script.ptr();
  1255. while (sptr) {
  1256. for (const KeyValue<StringName, GDScriptFunction *> &E : sptr->member_functions) {
  1257. MethodInfo mi;
  1258. mi.name = E.key;
  1259. mi.flags |= METHOD_FLAG_FROM_SCRIPT;
  1260. for (int i = 0; i < E.value->get_argument_count(); i++) {
  1261. mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
  1262. }
  1263. p_list->push_back(mi);
  1264. }
  1265. sptr = sptr->_base;
  1266. }
  1267. }
  1268. bool GDScriptInstance::has_method(const StringName &p_method) const {
  1269. const GDScript *sptr = script.ptr();
  1270. while (sptr) {
  1271. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  1272. if (E) {
  1273. return true;
  1274. }
  1275. sptr = sptr->_base;
  1276. }
  1277. return false;
  1278. }
  1279. Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1280. GDScript *sptr = script.ptr();
  1281. while (sptr) {
  1282. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  1283. if (E) {
  1284. return E->get()->call(this, p_args, p_argcount, r_error);
  1285. }
  1286. sptr = sptr->_base;
  1287. }
  1288. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1289. return Variant();
  1290. }
  1291. void GDScriptInstance::notification(int p_notification) {
  1292. //notification is not virtual, it gets called at ALL levels just like in C.
  1293. Variant value = p_notification;
  1294. const Variant *args[1] = { &value };
  1295. GDScript *sptr = script.ptr();
  1296. while (sptr) {
  1297. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  1298. if (E) {
  1299. Callable::CallError err;
  1300. E->get()->call(this, args, 1, err);
  1301. if (err.error != Callable::CallError::CALL_OK) {
  1302. //print error about notification call
  1303. }
  1304. }
  1305. sptr = sptr->_base;
  1306. }
  1307. }
  1308. String GDScriptInstance::to_string(bool *r_valid) {
  1309. if (has_method(CoreStringNames::get_singleton()->_to_string)) {
  1310. Callable::CallError ce;
  1311. Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce);
  1312. if (ce.error == Callable::CallError::CALL_OK) {
  1313. if (ret.get_type() != Variant::STRING) {
  1314. if (r_valid) {
  1315. *r_valid = false;
  1316. }
  1317. ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String.");
  1318. }
  1319. if (r_valid) {
  1320. *r_valid = true;
  1321. }
  1322. return ret.operator String();
  1323. }
  1324. }
  1325. if (r_valid) {
  1326. *r_valid = false;
  1327. }
  1328. return String();
  1329. }
  1330. Ref<Script> GDScriptInstance::get_script() const {
  1331. return script;
  1332. }
  1333. ScriptLanguage *GDScriptInstance::get_language() {
  1334. return GDScriptLanguage::get_singleton();
  1335. }
  1336. const Vector<Multiplayer::RPCConfig> GDScriptInstance::get_rpc_methods() const {
  1337. return script->get_rpc_methods();
  1338. }
  1339. void GDScriptInstance::reload_members() {
  1340. #ifdef DEBUG_ENABLED
  1341. members.resize(script->member_indices.size()); //resize
  1342. Vector<Variant> new_members;
  1343. new_members.resize(script->member_indices.size());
  1344. //pass the values to the new indices
  1345. for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
  1346. if (member_indices_cache.has(E.key)) {
  1347. Variant value = members[member_indices_cache[E.key]];
  1348. new_members.write[E.value.index] = value;
  1349. }
  1350. }
  1351. //apply
  1352. members = new_members;
  1353. //pass the values to the new indices
  1354. member_indices_cache.clear();
  1355. for (const KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
  1356. member_indices_cache[E.key] = E.value.index;
  1357. }
  1358. #endif
  1359. }
  1360. GDScriptInstance::GDScriptInstance() {
  1361. owner = nullptr;
  1362. base_ref_counted = false;
  1363. }
  1364. GDScriptInstance::~GDScriptInstance() {
  1365. MutexLock lock(GDScriptLanguage::get_singleton()->lock);
  1366. while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
  1367. // Order matters since clearing the stack may already cause
  1368. // the GDSCriptFunctionState to be destroyed and thus removed from the list.
  1369. pending_func_states.remove(E);
  1370. E->self()->_clear_stack();
  1371. }
  1372. if (script.is_valid() && owner) {
  1373. script->instances.erase(owner);
  1374. }
  1375. }
  1376. /************* SCRIPT LANGUAGE **************/
  1377. GDScriptLanguage *GDScriptLanguage::singleton = nullptr;
  1378. String GDScriptLanguage::get_name() const {
  1379. return "GDScript";
  1380. }
  1381. /* LANGUAGE FUNCTIONS */
  1382. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  1383. if (globals.has(p_name)) {
  1384. //overwrite existing
  1385. global_array.write[globals[p_name]] = p_value;
  1386. return;
  1387. }
  1388. globals[p_name] = global_array.size();
  1389. global_array.push_back(p_value);
  1390. _global_array = global_array.ptrw();
  1391. }
  1392. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  1393. _add_global(p_variable, p_value);
  1394. }
  1395. void GDScriptLanguage::add_named_global_constant(const StringName &p_name, const Variant &p_value) {
  1396. named_globals[p_name] = p_value;
  1397. }
  1398. void GDScriptLanguage::remove_named_global_constant(const StringName &p_name) {
  1399. ERR_FAIL_COND(!named_globals.has(p_name));
  1400. named_globals.erase(p_name);
  1401. }
  1402. void GDScriptLanguage::init() {
  1403. //populate global constants
  1404. int gcc = CoreConstants::get_global_constant_count();
  1405. for (int i = 0; i < gcc; i++) {
  1406. _add_global(StaticCString::create(CoreConstants::get_global_constant_name(i)), CoreConstants::get_global_constant_value(i));
  1407. }
  1408. _add_global(StaticCString::create("PI"), Math_PI);
  1409. _add_global(StaticCString::create("TAU"), Math_TAU);
  1410. _add_global(StaticCString::create("INF"), INFINITY);
  1411. _add_global(StaticCString::create("NAN"), NAN);
  1412. //populate native classes
  1413. List<StringName> class_list;
  1414. ClassDB::get_class_list(&class_list);
  1415. for (const StringName &n : class_list) {
  1416. if (globals.has(n)) {
  1417. continue;
  1418. }
  1419. Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(n));
  1420. _add_global(n, nc);
  1421. }
  1422. //populate singletons
  1423. List<Engine::Singleton> singletons;
  1424. Engine::get_singleton()->get_singletons(&singletons);
  1425. for (const Engine::Singleton &E : singletons) {
  1426. _add_global(E.name, E.ptr);
  1427. }
  1428. #ifdef TESTS_ENABLED
  1429. GDScriptTests::GDScriptTestRunner::handle_cmdline();
  1430. #endif
  1431. }
  1432. String GDScriptLanguage::get_type() const {
  1433. return "GDScript";
  1434. }
  1435. String GDScriptLanguage::get_extension() const {
  1436. return "gd";
  1437. }
  1438. Error GDScriptLanguage::execute_file(const String &p_path) {
  1439. // ??
  1440. return OK;
  1441. }
  1442. void GDScriptLanguage::finish() {
  1443. }
  1444. void GDScriptLanguage::profiling_start() {
  1445. #ifdef DEBUG_ENABLED
  1446. MutexLock lock(this->lock);
  1447. SelfList<GDScriptFunction> *elem = function_list.first();
  1448. while (elem) {
  1449. elem->self()->profile.call_count = 0;
  1450. elem->self()->profile.self_time = 0;
  1451. elem->self()->profile.total_time = 0;
  1452. elem->self()->profile.frame_call_count = 0;
  1453. elem->self()->profile.frame_self_time = 0;
  1454. elem->self()->profile.frame_total_time = 0;
  1455. elem->self()->profile.last_frame_call_count = 0;
  1456. elem->self()->profile.last_frame_self_time = 0;
  1457. elem->self()->profile.last_frame_total_time = 0;
  1458. elem = elem->next();
  1459. }
  1460. profiling = true;
  1461. #endif
  1462. }
  1463. void GDScriptLanguage::profiling_stop() {
  1464. #ifdef DEBUG_ENABLED
  1465. MutexLock lock(this->lock);
  1466. profiling = false;
  1467. #endif
  1468. }
  1469. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1470. int current = 0;
  1471. #ifdef DEBUG_ENABLED
  1472. MutexLock lock(this->lock);
  1473. SelfList<GDScriptFunction> *elem = function_list.first();
  1474. while (elem) {
  1475. if (current >= p_info_max) {
  1476. break;
  1477. }
  1478. p_info_arr[current].call_count = elem->self()->profile.call_count;
  1479. p_info_arr[current].self_time = elem->self()->profile.self_time;
  1480. p_info_arr[current].total_time = elem->self()->profile.total_time;
  1481. p_info_arr[current].signature = elem->self()->profile.signature;
  1482. elem = elem->next();
  1483. current++;
  1484. }
  1485. #endif
  1486. return current;
  1487. }
  1488. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1489. int current = 0;
  1490. #ifdef DEBUG_ENABLED
  1491. MutexLock lock(this->lock);
  1492. SelfList<GDScriptFunction> *elem = function_list.first();
  1493. while (elem) {
  1494. if (current >= p_info_max) {
  1495. break;
  1496. }
  1497. if (elem->self()->profile.last_frame_call_count > 0) {
  1498. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  1499. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  1500. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  1501. p_info_arr[current].signature = elem->self()->profile.signature;
  1502. current++;
  1503. }
  1504. elem = elem->next();
  1505. }
  1506. #endif
  1507. return current;
  1508. }
  1509. struct GDScriptDepSort {
  1510. //must support sorting so inheritance works properly (parent must be reloaded first)
  1511. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  1512. if (A == B) {
  1513. return false; //shouldn't happen but..
  1514. }
  1515. const GDScript *I = B->get_base().ptr();
  1516. while (I) {
  1517. if (I == A.ptr()) {
  1518. // A is a base of B
  1519. return true;
  1520. }
  1521. I = I->get_base().ptr();
  1522. }
  1523. return false; //not a base
  1524. }
  1525. };
  1526. void GDScriptLanguage::reload_all_scripts() {
  1527. #ifdef DEBUG_ENABLED
  1528. print_verbose("GDScript: Reloading all scripts");
  1529. List<Ref<GDScript>> scripts;
  1530. {
  1531. MutexLock lock(this->lock);
  1532. SelfList<GDScript> *elem = script_list.first();
  1533. while (elem) {
  1534. if (elem->self()->get_path().is_resource_file()) {
  1535. print_verbose("GDScript: Found: " + elem->self()->get_path());
  1536. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1537. }
  1538. elem = elem->next();
  1539. }
  1540. }
  1541. //as scripts are going to be reloaded, must proceed without locking here
  1542. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1543. for (Ref<GDScript> &script : scripts) {
  1544. print_verbose("GDScript: Reloading: " + script->get_path());
  1545. script->load_source_code(script->get_path());
  1546. script->reload(true);
  1547. }
  1548. #endif
  1549. }
  1550. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  1551. #ifdef DEBUG_ENABLED
  1552. List<Ref<GDScript>> scripts;
  1553. {
  1554. MutexLock lock(this->lock);
  1555. SelfList<GDScript> *elem = script_list.first();
  1556. while (elem) {
  1557. if (elem->self()->get_path().is_resource_file()) {
  1558. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1559. }
  1560. elem = elem->next();
  1561. }
  1562. }
  1563. //when someone asks you why dynamically typed languages are easier to write....
  1564. Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant>>>> to_reload;
  1565. //as scripts are going to be reloaded, must proceed without locking here
  1566. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1567. for (Ref<GDScript> &script : scripts) {
  1568. bool reload = script == p_script || to_reload.has(script->get_base());
  1569. if (!reload) {
  1570. continue;
  1571. }
  1572. to_reload.insert(script, Map<ObjectID, List<Pair<StringName, Variant>>>());
  1573. if (!p_soft_reload) {
  1574. //save state and remove script from instances
  1575. Map<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[script];
  1576. while (script->instances.front()) {
  1577. Object *obj = script->instances.front()->get();
  1578. //save instance info
  1579. List<Pair<StringName, Variant>> state;
  1580. if (obj->get_script_instance()) {
  1581. obj->get_script_instance()->get_property_state(state);
  1582. map[obj->get_instance_id()] = state;
  1583. obj->set_script(Variant());
  1584. }
  1585. }
  1586. //same thing for placeholders
  1587. #ifdef TOOLS_ENABLED
  1588. while (script->placeholders.size()) {
  1589. Object *obj = script->placeholders.front()->get()->get_owner();
  1590. //save instance info
  1591. if (obj->get_script_instance()) {
  1592. map.insert(obj->get_instance_id(), List<Pair<StringName, Variant>>());
  1593. List<Pair<StringName, Variant>> &state = map[obj->get_instance_id()];
  1594. obj->get_script_instance()->get_property_state(state);
  1595. obj->set_script(Variant());
  1596. } else {
  1597. // no instance found. Let's remove it so we don't loop forever
  1598. script->placeholders.erase(script->placeholders.front()->get());
  1599. }
  1600. }
  1601. #endif
  1602. for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : script->pending_reload_state) {
  1603. map[F.key] = F.value; //pending to reload, use this one instead
  1604. }
  1605. }
  1606. }
  1607. for (KeyValue<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant>>>> &E : to_reload) {
  1608. Ref<GDScript> scr = E.key;
  1609. scr->reload(p_soft_reload);
  1610. //restore state if saved
  1611. for (KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : E.value) {
  1612. List<Pair<StringName, Variant>> &saved_state = F.value;
  1613. Object *obj = ObjectDB::get_instance(F.key);
  1614. if (!obj) {
  1615. continue;
  1616. }
  1617. if (!p_soft_reload) {
  1618. //clear it just in case (may be a pending reload state)
  1619. obj->set_script(Variant());
  1620. }
  1621. obj->set_script(scr);
  1622. ScriptInstance *script_instance = obj->get_script_instance();
  1623. if (!script_instance) {
  1624. //failed, save reload state for next time if not saved
  1625. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  1626. scr->pending_reload_state[obj->get_instance_id()] = saved_state;
  1627. }
  1628. continue;
  1629. }
  1630. if (script_instance->is_placeholder() && scr->is_placeholder_fallback_enabled()) {
  1631. PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_instance);
  1632. for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
  1633. placeholder->property_set_fallback(G->get().first, G->get().second);
  1634. }
  1635. } else {
  1636. for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
  1637. script_instance->set(G->get().first, G->get().second);
  1638. }
  1639. }
  1640. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  1641. }
  1642. //if instance states were saved, set them!
  1643. }
  1644. #endif
  1645. }
  1646. void GDScriptLanguage::frame() {
  1647. calls = 0;
  1648. #ifdef DEBUG_ENABLED
  1649. if (profiling) {
  1650. MutexLock lock(this->lock);
  1651. SelfList<GDScriptFunction> *elem = function_list.first();
  1652. while (elem) {
  1653. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
  1654. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
  1655. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
  1656. elem->self()->profile.frame_call_count = 0;
  1657. elem->self()->profile.frame_self_time = 0;
  1658. elem->self()->profile.frame_total_time = 0;
  1659. elem = elem->next();
  1660. }
  1661. }
  1662. #endif
  1663. }
  1664. /* EDITOR FUNCTIONS */
  1665. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1666. // TODO: Add annotations here?
  1667. static const char *_reserved_words[] = {
  1668. // operators
  1669. "and",
  1670. "in",
  1671. "not",
  1672. "or",
  1673. // types and values
  1674. "false",
  1675. "float",
  1676. "int",
  1677. "bool",
  1678. "null",
  1679. "PI",
  1680. "TAU",
  1681. "INF",
  1682. "NAN",
  1683. "self",
  1684. "true",
  1685. "void",
  1686. // functions
  1687. "as",
  1688. "assert",
  1689. "await",
  1690. "breakpoint",
  1691. "class",
  1692. "class_name",
  1693. "extends",
  1694. "is",
  1695. "func",
  1696. "preload",
  1697. "signal",
  1698. "super",
  1699. "trait",
  1700. "yield",
  1701. // var
  1702. "const",
  1703. "enum",
  1704. "static",
  1705. "var",
  1706. // control flow
  1707. "break",
  1708. "continue",
  1709. "if",
  1710. "elif",
  1711. "else",
  1712. "for",
  1713. "pass",
  1714. "return",
  1715. "match",
  1716. "while",
  1717. nullptr
  1718. };
  1719. const char **w = _reserved_words;
  1720. while (*w) {
  1721. p_words->push_back(*w);
  1722. w++;
  1723. }
  1724. List<StringName> functions;
  1725. GDScriptUtilityFunctions::get_function_list(&functions);
  1726. for (const StringName &E : functions) {
  1727. p_words->push_back(String(E));
  1728. }
  1729. }
  1730. bool GDScriptLanguage::is_control_flow_keyword(String p_keyword) const {
  1731. return p_keyword == "break" ||
  1732. p_keyword == "continue" ||
  1733. p_keyword == "elif" ||
  1734. p_keyword == "else" ||
  1735. p_keyword == "if" ||
  1736. p_keyword == "for" ||
  1737. p_keyword == "match" ||
  1738. p_keyword == "pass" ||
  1739. p_keyword == "return" ||
  1740. p_keyword == "while";
  1741. }
  1742. bool GDScriptLanguage::handles_global_class_type(const String &p_type) const {
  1743. return p_type == "GDScript";
  1744. }
  1745. String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
  1746. Vector<uint8_t> sourcef;
  1747. Error err;
  1748. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
  1749. if (err) {
  1750. return String();
  1751. }
  1752. String source = f->get_as_utf8_string();
  1753. GDScriptParser parser;
  1754. err = parser.parse(source, p_path, false);
  1755. // TODO: Simplify this code by using the analyzer to get full inheritance.
  1756. if (err == OK) {
  1757. const GDScriptParser::ClassNode *c = parser.get_tree();
  1758. if (r_icon_path) {
  1759. if (c->icon_path.is_empty() || c->icon_path.is_absolute_path()) {
  1760. *r_icon_path = c->icon_path;
  1761. } else if (c->icon_path.is_relative_path()) {
  1762. *r_icon_path = p_path.get_base_dir().plus_file(c->icon_path).simplify_path();
  1763. }
  1764. }
  1765. if (r_base_type) {
  1766. const GDScriptParser::ClassNode *subclass = c;
  1767. String path = p_path;
  1768. GDScriptParser subparser;
  1769. while (subclass) {
  1770. if (subclass->extends_used) {
  1771. if (!subclass->extends_path.is_empty()) {
  1772. if (subclass->extends.size() == 0) {
  1773. get_global_class_name(subclass->extends_path, r_base_type);
  1774. subclass = nullptr;
  1775. break;
  1776. } else {
  1777. Vector<StringName> extend_classes = subclass->extends;
  1778. FileAccessRef subfile = FileAccess::open(subclass->extends_path, FileAccess::READ);
  1779. if (!subfile) {
  1780. break;
  1781. }
  1782. String subsource = subfile->get_as_utf8_string();
  1783. if (subsource.is_empty()) {
  1784. break;
  1785. }
  1786. String subpath = subclass->extends_path;
  1787. if (subpath.is_relative_path()) {
  1788. subpath = path.get_base_dir().plus_file(subpath).simplify_path();
  1789. }
  1790. if (OK != subparser.parse(subsource, subpath, false)) {
  1791. break;
  1792. }
  1793. path = subpath;
  1794. subclass = subparser.get_tree();
  1795. while (extend_classes.size() > 0) {
  1796. bool found = false;
  1797. for (int i = 0; i < subclass->members.size(); i++) {
  1798. if (subclass->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
  1799. continue;
  1800. }
  1801. const GDScriptParser::ClassNode *inner_class = subclass->members[i].m_class;
  1802. if (inner_class->identifier->name == extend_classes[0]) {
  1803. extend_classes.remove(0);
  1804. found = true;
  1805. subclass = inner_class;
  1806. break;
  1807. }
  1808. }
  1809. if (!found) {
  1810. subclass = nullptr;
  1811. break;
  1812. }
  1813. }
  1814. }
  1815. } else if (subclass->extends.size() == 1) {
  1816. *r_base_type = subclass->extends[0];
  1817. subclass = nullptr;
  1818. } else {
  1819. break;
  1820. }
  1821. } else {
  1822. *r_base_type = "RefCounted";
  1823. subclass = nullptr;
  1824. }
  1825. }
  1826. }
  1827. return c->identifier != nullptr ? String(c->identifier->name) : String();
  1828. }
  1829. return String();
  1830. }
  1831. GDScriptLanguage::GDScriptLanguage() {
  1832. calls = 0;
  1833. ERR_FAIL_COND(singleton);
  1834. singleton = this;
  1835. strings._init = StaticCString::create("_init");
  1836. strings._notification = StaticCString::create("_notification");
  1837. strings._set = StaticCString::create("_set");
  1838. strings._get = StaticCString::create("_get");
  1839. strings._get_property_list = StaticCString::create("_get_property_list");
  1840. strings._script_source = StaticCString::create("script/source");
  1841. _debug_parse_err_line = -1;
  1842. _debug_parse_err_file = "";
  1843. profiling = false;
  1844. script_frame_time = 0;
  1845. _debug_call_stack_pos = 0;
  1846. int dmcs = GLOBAL_DEF("debug/settings/gdscript/max_call_stack", 1024);
  1847. 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
  1848. if (EngineDebugger::is_active()) {
  1849. //debugging enabled!
  1850. _debug_max_call_stack = dmcs;
  1851. _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
  1852. } else {
  1853. _debug_max_call_stack = 0;
  1854. _call_stack = nullptr;
  1855. }
  1856. #ifdef DEBUG_ENABLED
  1857. GLOBAL_DEF("debug/gdscript/warnings/enable", true);
  1858. GLOBAL_DEF("debug/gdscript/warnings/treat_warnings_as_errors", false);
  1859. GLOBAL_DEF("debug/gdscript/warnings/exclude_addons", true);
  1860. GLOBAL_DEF("debug/gdscript/completion/autocomplete_setters_and_getters", false);
  1861. for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
  1862. String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower();
  1863. bool default_enabled = !warning.begins_with("unsafe_");
  1864. GLOBAL_DEF("debug/gdscript/warnings/" + warning, default_enabled);
  1865. }
  1866. #endif // DEBUG_ENABLED
  1867. }
  1868. GDScriptLanguage::~GDScriptLanguage() {
  1869. if (_call_stack) {
  1870. memdelete_arr(_call_stack);
  1871. }
  1872. // Clear dependencies between scripts, to ensure cyclic references are broken (to avoid leaks at exit).
  1873. SelfList<GDScript> *s = script_list.first();
  1874. while (s) {
  1875. GDScript *script = s->self();
  1876. // This ensures the current script is not released before we can check what's the next one
  1877. // in the list (we can't get the next upfront because we don't know if the reference breaking
  1878. // will cause it -or any other after it, for that matter- to be released so the next one
  1879. // is not the same as before).
  1880. script->reference();
  1881. for (KeyValue<StringName, GDScriptFunction *> &E : script->member_functions) {
  1882. GDScriptFunction *func = E.value;
  1883. for (int i = 0; i < func->argument_types.size(); i++) {
  1884. func->argument_types.write[i].script_type_ref = Ref<Script>();
  1885. }
  1886. func->return_type.script_type_ref = Ref<Script>();
  1887. }
  1888. for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) {
  1889. E.value.data_type.script_type_ref = Ref<Script>();
  1890. }
  1891. s = s->next();
  1892. script->unreference();
  1893. }
  1894. singleton = nullptr;
  1895. }
  1896. void GDScriptLanguage::add_orphan_subclass(const String &p_qualified_name, const ObjectID &p_subclass) {
  1897. orphan_subclasses[p_qualified_name] = p_subclass;
  1898. }
  1899. Ref<GDScript> GDScriptLanguage::get_orphan_subclass(const String &p_qualified_name) {
  1900. Map<String, ObjectID>::Element *orphan_subclass_element = orphan_subclasses.find(p_qualified_name);
  1901. if (!orphan_subclass_element) {
  1902. return Ref<GDScript>();
  1903. }
  1904. ObjectID orphan_subclass = orphan_subclass_element->get();
  1905. Object *obj = ObjectDB::get_instance(orphan_subclass);
  1906. orphan_subclasses.erase(orphan_subclass_element);
  1907. if (!obj) {
  1908. return Ref<GDScript>();
  1909. }
  1910. return Ref<GDScript>(Object::cast_to<GDScript>(obj));
  1911. }
  1912. /*************** RESOURCE ***************/
  1913. 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) {
  1914. if (r_error) {
  1915. *r_error = ERR_FILE_CANT_OPEN;
  1916. }
  1917. Error err;
  1918. Ref<GDScript> script = GDScriptCache::get_full_script(p_path, err);
  1919. // TODO: Reintroduce binary and encrypted scripts.
  1920. if (script.is_null()) {
  1921. // Don't fail loading because of parsing error.
  1922. script.instantiate();
  1923. }
  1924. if (r_error) {
  1925. *r_error = OK;
  1926. }
  1927. return script;
  1928. }
  1929. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1930. p_extensions->push_back("gd");
  1931. // TODO: Reintroduce binary and encrypted scripts.
  1932. // p_extensions->push_back("gdc");
  1933. // p_extensions->push_back("gde");
  1934. }
  1935. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  1936. return (p_type == "Script" || p_type == "GDScript");
  1937. }
  1938. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1939. String el = p_path.get_extension().to_lower();
  1940. // TODO: Reintroduce binary and encrypted scripts.
  1941. if (el == "gd" /*|| el == "gdc" || el == "gde"*/) {
  1942. return "GDScript";
  1943. }
  1944. return "";
  1945. }
  1946. void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  1947. FileAccessRef file = FileAccess::open(p_path, FileAccess::READ);
  1948. ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_path + "'.");
  1949. String source = file->get_as_utf8_string();
  1950. if (source.is_empty()) {
  1951. return;
  1952. }
  1953. GDScriptParser parser;
  1954. if (OK != parser.parse(source, p_path, false)) {
  1955. return;
  1956. }
  1957. for (const String &E : parser.get_dependencies()) {
  1958. p_dependencies->push_back(E);
  1959. }
  1960. }
  1961. Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1962. Ref<GDScript> sqscr = p_resource;
  1963. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1964. String source = sqscr->get_source_code();
  1965. Error err;
  1966. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1967. ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'.");
  1968. file->store_string(source);
  1969. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1970. memdelete(file);
  1971. return ERR_CANT_CREATE;
  1972. }
  1973. file->close();
  1974. memdelete(file);
  1975. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1976. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1977. }
  1978. return OK;
  1979. }
  1980. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1981. if (Object::cast_to<GDScript>(*p_resource)) {
  1982. p_extensions->push_back("gd");
  1983. }
  1984. }
  1985. bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
  1986. return Object::cast_to<GDScript>(*p_resource) != nullptr;
  1987. }