gdscript.cpp 56 KB

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