gdscript.cpp 57 KB

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