gdscript.cpp 57 KB

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