gdscript.cpp 66 KB

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