gdscript.cpp 66 KB

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