gdscript.cpp 59 KB

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