gdscript.cpp 64 KB

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