gd_script.cpp 49 KB

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