gdscript.cpp 66 KB

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