gdscript.cpp 67 KB

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