gd_script.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  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_config.h"
  33. #include "global_constants.h"
  34. #include "io/file_access_encrypted.h"
  35. #include "os/file_access.h"
  36. #include "os/os.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. #endif
  425. return false;
  426. }
  427. void GDScript::update_exports() {
  428. #ifdef TOOLS_ENABLED
  429. _update_exports();
  430. Set<ObjectID> copy = inheriters_cache; //might get modified
  431. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  432. for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
  433. Object *id = ObjectDB::get_instance(E->get());
  434. if (!id)
  435. continue;
  436. GDScript *s = id->cast_to<GDScript>();
  437. if (!s)
  438. continue;
  439. s->update_exports();
  440. }
  441. #endif
  442. }
  443. void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) {
  444. p_sc->path = p_path;
  445. for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) {
  446. _set_subclass_path(E->get(), p_path);
  447. }
  448. }
  449. Error GDScript::reload(bool p_keep_state) {
  450. #ifndef NO_THREADS
  451. GDScriptLanguage::singleton->lock->lock();
  452. #endif
  453. bool has_instances = instances.size();
  454. #ifndef NO_THREADS
  455. GDScriptLanguage::singleton->lock->unlock();
  456. #endif
  457. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  458. String basedir = path;
  459. if (basedir == "")
  460. basedir = get_path();
  461. if (basedir != "")
  462. basedir = basedir.get_base_dir();
  463. if (basedir.find("res://") == -1 && basedir.find("user://") == -1) {
  464. //loading a template, don't parse
  465. return OK;
  466. }
  467. valid = false;
  468. GDParser parser;
  469. Error err = parser.parse(source, basedir, false, path);
  470. if (err) {
  471. if (ScriptDebugger::get_singleton()) {
  472. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error());
  473. }
  474. _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);
  475. ERR_FAIL_V(ERR_PARSE_ERROR);
  476. }
  477. bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script();
  478. GDCompiler compiler;
  479. err = compiler.compile(&parser, this, p_keep_state);
  480. if (err) {
  481. if (can_run) {
  482. if (ScriptDebugger::get_singleton()) {
  483. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
  484. }
  485. _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);
  486. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  487. } else {
  488. return err;
  489. }
  490. }
  491. valid = true;
  492. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  493. _set_subclass_path(E->get(), path);
  494. }
  495. #ifdef TOOLS_ENABLED
  496. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  497. _update_placeholder(E->get());
  498. }*/
  499. #endif
  500. return OK;
  501. }
  502. String GDScript::get_node_type() const {
  503. return ""; // ?
  504. }
  505. ScriptLanguage *GDScript::get_language() const {
  506. return GDScriptLanguage::get_singleton();
  507. }
  508. Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  509. GDScript *top = this;
  510. while (top) {
  511. Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method);
  512. if (E) {
  513. if (!E->get()->is_static()) {
  514. WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data());
  515. }
  516. return E->get()->call(NULL, p_args, p_argcount, r_error);
  517. }
  518. top = top->_base;
  519. }
  520. //none found, regular
  521. return Script::call(p_method, p_args, p_argcount, r_error);
  522. }
  523. bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
  524. {
  525. const GDScript *top = this;
  526. while (top) {
  527. {
  528. const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
  529. if (E) {
  530. r_ret = E->get();
  531. return true;
  532. }
  533. }
  534. {
  535. const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name);
  536. if (E) {
  537. r_ret = E->get();
  538. return true;
  539. }
  540. }
  541. top = top->_base;
  542. }
  543. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  544. r_ret = get_source_code();
  545. return true;
  546. }
  547. }
  548. return false;
  549. }
  550. bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
  551. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  552. set_source_code(p_value);
  553. reload();
  554. } else
  555. return false;
  556. return true;
  557. }
  558. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  559. p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
  560. }
  561. void GDScript::_bind_methods() {
  562. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new"));
  563. ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
  564. }
  565. Vector<uint8_t> GDScript::get_as_byte_code() const {
  566. GDTokenizerBuffer tokenizer;
  567. return tokenizer.parse_code_string(source);
  568. };
  569. Error GDScript::load_byte_code(const String &p_path) {
  570. Vector<uint8_t> bytecode;
  571. if (p_path.ends_with("gde")) {
  572. FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
  573. ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN);
  574. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  575. ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN);
  576. Vector<uint8_t> key;
  577. key.resize(32);
  578. for (int i = 0; i < key.size(); i++) {
  579. key[i] = script_encryption_key[i];
  580. }
  581. Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
  582. ERR_FAIL_COND_V(err, err);
  583. bytecode.resize(fae->get_len());
  584. fae->get_buffer(bytecode.ptr(), bytecode.size());
  585. memdelete(fae);
  586. } else {
  587. bytecode = FileAccess::get_file_as_array(p_path);
  588. }
  589. ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
  590. path = p_path;
  591. String basedir = path;
  592. if (basedir == "")
  593. basedir = get_path();
  594. if (basedir != "")
  595. basedir = basedir.get_base_dir();
  596. valid = false;
  597. GDParser parser;
  598. Error err = parser.parse_bytecode(bytecode, basedir, get_path());
  599. if (err) {
  600. _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);
  601. ERR_FAIL_V(ERR_PARSE_ERROR);
  602. }
  603. GDCompiler compiler;
  604. err = compiler.compile(&parser, this);
  605. if (err) {
  606. _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);
  607. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  608. }
  609. valid = true;
  610. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  611. _set_subclass_path(E->get(), path);
  612. }
  613. return OK;
  614. }
  615. Error GDScript::load_source_code(const String &p_path) {
  616. PoolVector<uint8_t> sourcef;
  617. Error err;
  618. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  619. if (err) {
  620. ERR_FAIL_COND_V(err, err);
  621. }
  622. int len = f->get_len();
  623. sourcef.resize(len + 1);
  624. PoolVector<uint8_t>::Write w = sourcef.write();
  625. int r = f->get_buffer(w.ptr(), len);
  626. f->close();
  627. memdelete(f);
  628. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  629. w[len] = 0;
  630. String s;
  631. if (s.parse_utf8((const char *)w.ptr())) {
  632. 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.");
  633. ERR_FAIL_V(ERR_INVALID_DATA);
  634. }
  635. source = s;
  636. #ifdef TOOLS_ENABLED
  637. source_changed_cache = true;
  638. #endif
  639. //print_line("LSC :"+get_path());
  640. path = p_path;
  641. return OK;
  642. }
  643. const Map<StringName, GDFunction *> &GDScript::debug_get_member_functions() const {
  644. return member_functions;
  645. }
  646. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  647. for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  648. if (E->get().index == p_idx)
  649. return E->key();
  650. }
  651. return "<error>";
  652. }
  653. Ref<GDScript> GDScript::get_base() const {
  654. return base;
  655. }
  656. bool GDScript::has_script_signal(const StringName &p_signal) const {
  657. if (_signals.has(p_signal))
  658. return true;
  659. if (base.is_valid()) {
  660. return base->has_script_signal(p_signal);
  661. }
  662. #ifdef TOOLS_ENABLED
  663. else if (base_cache.is_valid()) {
  664. return base_cache->has_script_signal(p_signal);
  665. }
  666. #endif
  667. return false;
  668. }
  669. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  670. for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) {
  671. MethodInfo mi;
  672. mi.name = E->key();
  673. for (int i = 0; i < E->get().size(); i++) {
  674. PropertyInfo arg;
  675. arg.name = E->get()[i];
  676. mi.arguments.push_back(arg);
  677. }
  678. r_signals->push_back(mi);
  679. }
  680. if (base.is_valid()) {
  681. base->get_script_signal_list(r_signals);
  682. }
  683. #ifdef TOOLS_ENABLED
  684. else if (base_cache.is_valid()) {
  685. base_cache->get_script_signal_list(r_signals);
  686. }
  687. #endif
  688. }
  689. GDScript::GDScript()
  690. : script_list(this) {
  691. _static_ref = this;
  692. valid = false;
  693. subclass_count = 0;
  694. initializer = NULL;
  695. _base = NULL;
  696. _owner = NULL;
  697. tool = false;
  698. #ifdef TOOLS_ENABLED
  699. source_changed_cache = false;
  700. #endif
  701. #ifdef DEBUG_ENABLED
  702. if (GDScriptLanguage::get_singleton()->lock) {
  703. GDScriptLanguage::get_singleton()->lock->lock();
  704. }
  705. GDScriptLanguage::get_singleton()->script_list.add(&script_list);
  706. if (GDScriptLanguage::get_singleton()->lock) {
  707. GDScriptLanguage::get_singleton()->lock->unlock();
  708. }
  709. #endif
  710. }
  711. GDScript::~GDScript() {
  712. for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  713. memdelete(E->get());
  714. }
  715. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  716. E->get()->_owner = NULL; //bye, you are no longer owned cause I died
  717. }
  718. #ifdef DEBUG_ENABLED
  719. if (GDScriptLanguage::get_singleton()->lock) {
  720. GDScriptLanguage::get_singleton()->lock->lock();
  721. }
  722. GDScriptLanguage::get_singleton()->script_list.remove(&script_list);
  723. if (GDScriptLanguage::get_singleton()->lock) {
  724. GDScriptLanguage::get_singleton()->lock->unlock();
  725. }
  726. #endif
  727. }
  728. //////////////////////////////
  729. // INSTANCE //
  730. //////////////////////////////
  731. bool GDInstance::set(const StringName &p_name, const Variant &p_value) {
  732. //member
  733. {
  734. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  735. if (E) {
  736. if (E->get().setter) {
  737. const Variant *val = &p_value;
  738. Variant::CallError err;
  739. call(E->get().setter, &val, 1, err);
  740. if (err.error == Variant::CallError::CALL_OK) {
  741. return true; //function exists, call was successful
  742. }
  743. } else
  744. members[E->get().index] = p_value;
  745. return true;
  746. }
  747. }
  748. GDScript *sptr = script.ptr();
  749. while (sptr) {
  750. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  751. if (E) {
  752. Variant name = p_name;
  753. const Variant *args[2] = { &name, &p_value };
  754. Variant::CallError err;
  755. Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
  756. if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
  757. return true;
  758. }
  759. sptr = sptr->_base;
  760. }
  761. return false;
  762. }
  763. bool GDInstance::get(const StringName &p_name, Variant &r_ret) const {
  764. const GDScript *sptr = script.ptr();
  765. while (sptr) {
  766. {
  767. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  768. if (E) {
  769. if (E->get().getter) {
  770. Variant::CallError err;
  771. r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err);
  772. if (err.error == Variant::CallError::CALL_OK) {
  773. return true;
  774. }
  775. }
  776. r_ret = members[E->get().index];
  777. return true; //index found
  778. }
  779. }
  780. {
  781. const GDScript *sl = sptr;
  782. while (sl) {
  783. const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
  784. if (E) {
  785. r_ret = E->get();
  786. return true; //index found
  787. }
  788. sl = sl->_base;
  789. }
  790. }
  791. {
  792. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  793. if (E) {
  794. Variant name = p_name;
  795. const Variant *args[1] = { &name };
  796. Variant::CallError err;
  797. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err);
  798. if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  799. r_ret = ret;
  800. return true;
  801. }
  802. }
  803. }
  804. sptr = sptr->_base;
  805. }
  806. return false;
  807. }
  808. Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  809. const GDScript *sptr = script.ptr();
  810. while (sptr) {
  811. if (sptr->member_info.has(p_name)) {
  812. if (r_is_valid)
  813. *r_is_valid = true;
  814. return sptr->member_info[p_name].type;
  815. }
  816. sptr = sptr->_base;
  817. }
  818. if (r_is_valid)
  819. *r_is_valid = false;
  820. return Variant::NIL;
  821. }
  822. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  823. // exported members, not doen yet!
  824. const GDScript *sptr = script.ptr();
  825. List<PropertyInfo> props;
  826. while (sptr) {
  827. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  828. if (E) {
  829. Variant::CallError err;
  830. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err);
  831. if (err.error == Variant::CallError::CALL_OK) {
  832. if (ret.get_type() != Variant::ARRAY) {
  833. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  834. ERR_FAIL();
  835. }
  836. Array arr = ret;
  837. for (int i = 0; i < arr.size(); i++) {
  838. Dictionary d = arr[i];
  839. ERR_CONTINUE(!d.has("name"));
  840. ERR_CONTINUE(!d.has("type"));
  841. PropertyInfo pinfo;
  842. pinfo.type = Variant::Type(d["type"].operator int());
  843. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  844. pinfo.name = d["name"];
  845. ERR_CONTINUE(pinfo.name == "");
  846. if (d.has("hint"))
  847. pinfo.hint = PropertyHint(d["hint"].operator int());
  848. if (d.has("hint_string"))
  849. pinfo.hint_string = d["hint_string"];
  850. if (d.has("usage"))
  851. pinfo.usage = d["usage"];
  852. props.push_back(pinfo);
  853. }
  854. }
  855. }
  856. //instance a fake script for editing the values
  857. Vector<_GDScriptMemberSort> msort;
  858. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  859. _GDScriptMemberSort ms;
  860. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  861. ms.index = sptr->member_indices[E->key()].index;
  862. ms.name = E->key();
  863. msort.push_back(ms);
  864. }
  865. msort.sort();
  866. msort.invert();
  867. for (int i = 0; i < msort.size(); i++) {
  868. props.push_front(sptr->member_info[msort[i].name]);
  869. }
  870. #if 0
  871. if (sptr->member_functions.has("_get_property_list")) {
  872. Variant::CallError err;
  873. GDFunction *f = const_cast<GDFunction*>(sptr->member_functions["_get_property_list"]);
  874. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  875. if (plv.get_type()!=Variant::ARRAY) {
  876. ERR_PRINT("_get_property_list: expected array returned");
  877. } else {
  878. Array pl=plv;
  879. for(int i=0;i<pl.size();i++) {
  880. Dictionary p = pl[i];
  881. PropertyInfo pinfo;
  882. if (!p.has("name")) {
  883. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  884. continue;
  885. }
  886. if (!p.has("type")) {
  887. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  888. continue;
  889. }
  890. pinfo.name=p["name"];
  891. pinfo.type=Variant::Type(int(p["type"]));
  892. if (p.has("hint"))
  893. pinfo.hint=PropertyHint(int(p["hint"]));
  894. if (p.has("hint_string"))
  895. pinfo.hint_string=p["hint_string"];
  896. if (p.has("usage"))
  897. pinfo.usage=p["usage"];
  898. props.push_back(pinfo);
  899. }
  900. }
  901. }
  902. #endif
  903. sptr = sptr->_base;
  904. }
  905. //props.invert();
  906. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  907. p_properties->push_back(E->get());
  908. }
  909. }
  910. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  911. const GDScript *sptr = script.ptr();
  912. while (sptr) {
  913. for (Map<StringName, GDFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) {
  914. MethodInfo mi;
  915. mi.name = E->key();
  916. mi.flags |= METHOD_FLAG_FROM_SCRIPT;
  917. for (int i = 0; i < E->get()->get_argument_count(); i++)
  918. mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
  919. p_list->push_back(mi);
  920. }
  921. sptr = sptr->_base;
  922. }
  923. }
  924. bool GDInstance::has_method(const StringName &p_method) const {
  925. const GDScript *sptr = script.ptr();
  926. while (sptr) {
  927. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  928. if (E)
  929. return true;
  930. sptr = sptr->_base;
  931. }
  932. return false;
  933. }
  934. Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  935. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  936. GDScript *sptr = script.ptr();
  937. while (sptr) {
  938. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  939. if (E) {
  940. return E->get()->call(this, p_args, p_argcount, r_error);
  941. }
  942. sptr = sptr->_base;
  943. }
  944. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  945. return Variant();
  946. }
  947. void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  948. GDScript *sptr = script.ptr();
  949. Variant::CallError ce;
  950. while (sptr) {
  951. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  952. if (E) {
  953. E->get()->call(this, p_args, p_argcount, ce);
  954. }
  955. sptr = sptr->_base;
  956. }
  957. }
  958. void GDInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {
  959. if (sptr->_base)
  960. _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
  961. Variant::CallError ce;
  962. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  963. if (E) {
  964. E->get()->call(this, p_args, p_argcount, ce);
  965. }
  966. }
  967. void GDInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  968. if (script.ptr()) {
  969. _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
  970. }
  971. }
  972. void GDInstance::notification(int p_notification) {
  973. //notification is not virtual, it gets called at ALL levels just like in C.
  974. Variant value = p_notification;
  975. const Variant *args[1] = { &value };
  976. GDScript *sptr = script.ptr();
  977. while (sptr) {
  978. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  979. if (E) {
  980. Variant::CallError err;
  981. E->get()->call(this, args, 1, err);
  982. if (err.error != Variant::CallError::CALL_OK) {
  983. //print error about notification call
  984. }
  985. }
  986. sptr = sptr->_base;
  987. }
  988. }
  989. Ref<Script> GDInstance::get_script() const {
  990. return script;
  991. }
  992. ScriptLanguage *GDInstance::get_language() {
  993. return GDScriptLanguage::get_singleton();
  994. }
  995. GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName &p_method) const {
  996. const GDScript *cscript = script.ptr();
  997. while (cscript) {
  998. const Map<StringName, GDFunction *>::Element *E = cscript->member_functions.find(p_method);
  999. if (E) {
  1000. if (E->get()->get_rpc_mode() != RPC_MODE_DISABLED) {
  1001. return E->get()->get_rpc_mode();
  1002. }
  1003. }
  1004. cscript = cscript->_base;
  1005. }
  1006. return RPC_MODE_DISABLED;
  1007. }
  1008. GDInstance::RPCMode GDInstance::get_rset_mode(const StringName &p_variable) const {
  1009. const GDScript *cscript = script.ptr();
  1010. while (cscript) {
  1011. const Map<StringName, GDScript::MemberInfo>::Element *E = cscript->member_indices.find(p_variable);
  1012. if (E) {
  1013. if (E->get().rpc_mode) {
  1014. return E->get().rpc_mode;
  1015. }
  1016. }
  1017. cscript = cscript->_base;
  1018. }
  1019. return RPC_MODE_DISABLED;
  1020. }
  1021. void GDInstance::reload_members() {
  1022. #ifdef DEBUG_ENABLED
  1023. members.resize(script->member_indices.size()); //resize
  1024. Vector<Variant> new_members;
  1025. new_members.resize(script->member_indices.size());
  1026. //pass the values to the new indices
  1027. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  1028. if (member_indices_cache.has(E->key())) {
  1029. Variant value = members[member_indices_cache[E->key()]];
  1030. new_members[E->get().index] = value;
  1031. }
  1032. }
  1033. //apply
  1034. members = new_members;
  1035. //pass the values to the new indices
  1036. member_indices_cache.clear();
  1037. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  1038. member_indices_cache[E->key()] = E->get().index;
  1039. }
  1040. #endif
  1041. }
  1042. GDInstance::GDInstance() {
  1043. owner = NULL;
  1044. base_ref = false;
  1045. }
  1046. GDInstance::~GDInstance() {
  1047. if (script.is_valid() && owner) {
  1048. #ifndef NO_THREADS
  1049. GDScriptLanguage::singleton->lock->lock();
  1050. #endif
  1051. script->instances.erase(owner);
  1052. #ifndef NO_THREADS
  1053. GDScriptLanguage::singleton->lock->unlock();
  1054. #endif
  1055. }
  1056. }
  1057. /************* SCRIPT LANGUAGE **************/
  1058. /************* SCRIPT LANGUAGE **************/
  1059. /************* SCRIPT LANGUAGE **************/
  1060. /************* SCRIPT LANGUAGE **************/
  1061. /************* SCRIPT LANGUAGE **************/
  1062. GDScriptLanguage *GDScriptLanguage::singleton = NULL;
  1063. String GDScriptLanguage::get_name() const {
  1064. return "GDScript";
  1065. }
  1066. /* LANGUAGE FUNCTIONS */
  1067. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  1068. if (globals.has(p_name)) {
  1069. //overwrite existing
  1070. global_array[globals[p_name]] = p_value;
  1071. return;
  1072. }
  1073. globals[p_name] = global_array.size();
  1074. global_array.push_back(p_value);
  1075. _global_array = global_array.ptr();
  1076. }
  1077. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  1078. _add_global(p_variable, p_value);
  1079. }
  1080. void GDScriptLanguage::init() {
  1081. //populate global constants
  1082. int gcc = GlobalConstants::get_global_constant_count();
  1083. for (int i = 0; i < gcc; i++) {
  1084. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
  1085. }
  1086. _add_global(StaticCString::create("PI"), Math_PI);
  1087. _add_global(StaticCString::create("INF"), Math_INF);
  1088. _add_global(StaticCString::create("NAN"), Math_NAN);
  1089. //populate native classes
  1090. List<StringName> class_list;
  1091. ClassDB::get_class_list(&class_list);
  1092. for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
  1093. StringName n = E->get();
  1094. String s = String(n);
  1095. if (s.begins_with("_"))
  1096. n = s.substr(1, s.length());
  1097. if (globals.has(n))
  1098. continue;
  1099. Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get()));
  1100. _add_global(n, nc);
  1101. }
  1102. //populate singletons
  1103. List<GlobalConfig::Singleton> singletons;
  1104. GlobalConfig::get_singleton()->get_singletons(&singletons);
  1105. for (List<GlobalConfig::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
  1106. _add_global(E->get().name, E->get().ptr);
  1107. }
  1108. }
  1109. String GDScriptLanguage::get_type() const {
  1110. return "GDScript";
  1111. }
  1112. String GDScriptLanguage::get_extension() const {
  1113. return "gd";
  1114. }
  1115. Error GDScriptLanguage::execute_file(const String &p_path) {
  1116. // ??
  1117. return OK;
  1118. }
  1119. void GDScriptLanguage::finish() {
  1120. }
  1121. void GDScriptLanguage::profiling_start() {
  1122. #ifdef DEBUG_ENABLED
  1123. if (lock) {
  1124. lock->lock();
  1125. }
  1126. SelfList<GDFunction> *elem = function_list.first();
  1127. while (elem) {
  1128. elem->self()->profile.call_count = 0;
  1129. elem->self()->profile.self_time = 0;
  1130. elem->self()->profile.total_time = 0;
  1131. elem->self()->profile.frame_call_count = 0;
  1132. elem->self()->profile.frame_self_time = 0;
  1133. elem->self()->profile.frame_total_time = 0;
  1134. elem->self()->profile.last_frame_call_count = 0;
  1135. elem->self()->profile.last_frame_self_time = 0;
  1136. elem->self()->profile.last_frame_total_time = 0;
  1137. elem = elem->next();
  1138. }
  1139. profiling = true;
  1140. if (lock) {
  1141. lock->unlock();
  1142. }
  1143. #endif
  1144. }
  1145. void GDScriptLanguage::profiling_stop() {
  1146. #ifdef DEBUG_ENABLED
  1147. if (lock) {
  1148. lock->lock();
  1149. }
  1150. profiling = false;
  1151. if (lock) {
  1152. lock->unlock();
  1153. }
  1154. #endif
  1155. }
  1156. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1157. int current = 0;
  1158. #ifdef DEBUG_ENABLED
  1159. if (lock) {
  1160. lock->lock();
  1161. }
  1162. SelfList<GDFunction> *elem = function_list.first();
  1163. while (elem) {
  1164. if (current >= p_info_max)
  1165. break;
  1166. p_info_arr[current].call_count = elem->self()->profile.call_count;
  1167. p_info_arr[current].self_time = elem->self()->profile.self_time;
  1168. p_info_arr[current].total_time = elem->self()->profile.total_time;
  1169. p_info_arr[current].signature = elem->self()->profile.signature;
  1170. elem = elem->next();
  1171. current++;
  1172. }
  1173. if (lock) {
  1174. lock->unlock();
  1175. }
  1176. #endif
  1177. return current;
  1178. }
  1179. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1180. int current = 0;
  1181. #ifdef DEBUG_ENABLED
  1182. if (lock) {
  1183. lock->lock();
  1184. }
  1185. SelfList<GDFunction> *elem = function_list.first();
  1186. while (elem) {
  1187. if (current >= p_info_max)
  1188. break;
  1189. if (elem->self()->profile.last_frame_call_count > 0) {
  1190. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  1191. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  1192. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  1193. p_info_arr[current].signature = elem->self()->profile.signature;
  1194. //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
  1195. current++;
  1196. }
  1197. elem = elem->next();
  1198. }
  1199. if (lock) {
  1200. lock->unlock();
  1201. }
  1202. #endif
  1203. return current;
  1204. }
  1205. struct GDScriptDepSort {
  1206. //must support sorting so inheritance works properly (parent must be reloaded first)
  1207. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  1208. if (A == B)
  1209. return false; //shouldn't happen but..
  1210. const GDScript *I = B->get_base().ptr();
  1211. while (I) {
  1212. if (I == A.ptr()) {
  1213. // A is a base of B
  1214. return true;
  1215. }
  1216. I = I->get_base().ptr();
  1217. }
  1218. return false; //not a base
  1219. }
  1220. };
  1221. void GDScriptLanguage::reload_all_scripts() {
  1222. #ifdef DEBUG_ENABLED
  1223. print_line("RELOAD ALL SCRIPTS");
  1224. if (lock) {
  1225. lock->lock();
  1226. }
  1227. List<Ref<GDScript> > scripts;
  1228. SelfList<GDScript> *elem = script_list.first();
  1229. while (elem) {
  1230. if (elem->self()->get_path().is_resource_file()) {
  1231. print_line("FOUND: " + elem->self()->get_path());
  1232. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1233. }
  1234. elem = elem->next();
  1235. }
  1236. if (lock) {
  1237. lock->unlock();
  1238. }
  1239. //as scripts are going to be reloaded, must proceed without locking here
  1240. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1241. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1242. print_line("RELOADING: " + E->get()->get_path());
  1243. E->get()->load_source_code(E->get()->get_path());
  1244. E->get()->reload(true);
  1245. }
  1246. #endif
  1247. }
  1248. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  1249. #ifdef DEBUG_ENABLED
  1250. if (lock) {
  1251. lock->lock();
  1252. }
  1253. List<Ref<GDScript> > scripts;
  1254. SelfList<GDScript> *elem = script_list.first();
  1255. while (elem) {
  1256. if (elem->self()->get_path().is_resource_file()) {
  1257. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1258. }
  1259. elem = elem->next();
  1260. }
  1261. if (lock) {
  1262. lock->unlock();
  1263. }
  1264. //when someone asks you why dynamically typed languages are easier to write....
  1265. Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  1266. //as scripts are going to be reloaded, must proceed without locking here
  1267. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1268. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1269. bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
  1270. if (!reload)
  1271. continue;
  1272. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  1273. if (!p_soft_reload) {
  1274. //save state and remove script from instances
  1275. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  1276. while (E->get()->instances.front()) {
  1277. Object *obj = E->get()->instances.front()->get();
  1278. //save instance info
  1279. List<Pair<StringName, Variant> > state;
  1280. if (obj->get_script_instance()) {
  1281. obj->get_script_instance()->get_property_state(state);
  1282. map[obj->get_instance_ID()] = state;
  1283. obj->set_script(RefPtr());
  1284. }
  1285. }
  1286. //same thing for placeholders
  1287. #ifdef TOOLS_ENABLED
  1288. while (E->get()->placeholders.size()) {
  1289. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  1290. //save instance info
  1291. List<Pair<StringName, Variant> > state;
  1292. if (obj->get_script_instance()) {
  1293. obj->get_script_instance()->get_property_state(state);
  1294. map[obj->get_instance_ID()] = state;
  1295. obj->set_script(RefPtr());
  1296. } else {
  1297. // no instance found. Let's remove it so we don't loop forever
  1298. E->get()->placeholders.erase(E->get()->placeholders.front()->get());
  1299. }
  1300. }
  1301. #endif
  1302. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  1303. map[F->key()] = F->get(); //pending to reload, use this one instead
  1304. }
  1305. }
  1306. }
  1307. for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  1308. Ref<GDScript> scr = E->key();
  1309. scr->reload(p_soft_reload);
  1310. //restore state if saved
  1311. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  1312. Object *obj = ObjectDB::get_instance(F->key());
  1313. if (!obj)
  1314. continue;
  1315. if (!p_soft_reload) {
  1316. //clear it just in case (may be a pending reload state)
  1317. obj->set_script(RefPtr());
  1318. }
  1319. obj->set_script(scr.get_ref_ptr());
  1320. if (!obj->get_script_instance()) {
  1321. //failed, save reload state for next time if not saved
  1322. if (!scr->pending_reload_state.has(obj->get_instance_ID())) {
  1323. scr->pending_reload_state[obj->get_instance_ID()] = F->get();
  1324. }
  1325. continue;
  1326. }
  1327. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  1328. obj->get_script_instance()->set(G->get().first, G->get().second);
  1329. }
  1330. scr->pending_reload_state.erase(obj->get_instance_ID()); //as it reloaded, remove pending state
  1331. }
  1332. //if instance states were saved, set them!
  1333. }
  1334. #endif
  1335. }
  1336. void GDScriptLanguage::frame() {
  1337. //print_line("calls: "+itos(calls));
  1338. calls = 0;
  1339. #ifdef DEBUG_ENABLED
  1340. if (profiling) {
  1341. if (lock) {
  1342. lock->lock();
  1343. }
  1344. SelfList<GDFunction> *elem = function_list.first();
  1345. while (elem) {
  1346. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
  1347. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
  1348. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
  1349. elem->self()->profile.frame_call_count = 0;
  1350. elem->self()->profile.frame_self_time = 0;
  1351. elem->self()->profile.frame_total_time = 0;
  1352. elem = elem->next();
  1353. }
  1354. if (lock) {
  1355. lock->unlock();
  1356. }
  1357. }
  1358. #endif
  1359. }
  1360. /* EDITOR FUNCTIONS */
  1361. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1362. static const char *_reserved_words[] = {
  1363. // operators
  1364. "and",
  1365. "in",
  1366. "not",
  1367. "or",
  1368. // types and values
  1369. "false",
  1370. "float",
  1371. "int",
  1372. "bool",
  1373. "null",
  1374. "PI",
  1375. "INF",
  1376. "NAN",
  1377. "self",
  1378. "true",
  1379. // functions
  1380. "assert",
  1381. "breakpoint",
  1382. "class",
  1383. "extends",
  1384. "is",
  1385. "func",
  1386. "preload",
  1387. "setget",
  1388. "signal",
  1389. "tool",
  1390. "yield",
  1391. // var
  1392. "const",
  1393. "enum",
  1394. "export",
  1395. "onready",
  1396. "static",
  1397. "var",
  1398. // control flow
  1399. "break",
  1400. "continue",
  1401. "if",
  1402. "elif",
  1403. "else",
  1404. "for",
  1405. "pass",
  1406. "return",
  1407. "match",
  1408. "while",
  1409. "remote",
  1410. "sync",
  1411. "master",
  1412. "slave",
  1413. 0
  1414. };
  1415. const char **w = _reserved_words;
  1416. while (*w) {
  1417. p_words->push_back(*w);
  1418. w++;
  1419. }
  1420. for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
  1421. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1422. }
  1423. }
  1424. GDScriptLanguage::GDScriptLanguage() {
  1425. calls = 0;
  1426. ERR_FAIL_COND(singleton);
  1427. singleton = this;
  1428. strings._init = StaticCString::create("_init");
  1429. strings._notification = StaticCString::create("_notification");
  1430. strings._set = StaticCString::create("_set");
  1431. strings._get = StaticCString::create("_get");
  1432. strings._get_property_list = StaticCString::create("_get_property_list");
  1433. strings._script_source = StaticCString::create("script/source");
  1434. _debug_parse_err_line = -1;
  1435. _debug_parse_err_file = "";
  1436. #ifdef NO_THREADS
  1437. lock = NULL;
  1438. #else
  1439. lock = Mutex::create();
  1440. #endif
  1441. profiling = false;
  1442. script_frame_time = 0;
  1443. _debug_call_stack_pos = 0;
  1444. int dmcs = GLOBAL_DEF("debug/settings/gdscript/max_call_stack", 1024);
  1445. if (ScriptDebugger::get_singleton()) {
  1446. //debugging enabled!
  1447. _debug_max_call_stack = dmcs;
  1448. if (_debug_max_call_stack < 1024)
  1449. _debug_max_call_stack = 1024;
  1450. _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
  1451. } else {
  1452. _debug_max_call_stack = 0;
  1453. _call_stack = NULL;
  1454. }
  1455. }
  1456. GDScriptLanguage::~GDScriptLanguage() {
  1457. if (lock) {
  1458. memdelete(lock);
  1459. lock = NULL;
  1460. }
  1461. if (_call_stack) {
  1462. memdelete_arr(_call_stack);
  1463. }
  1464. singleton = NULL;
  1465. }
  1466. /*************** RESOURCE ***************/
  1467. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1468. if (r_error)
  1469. *r_error = ERR_FILE_CANT_OPEN;
  1470. GDScript *script = memnew(GDScript);
  1471. Ref<GDScript> scriptres(script);
  1472. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1473. script->set_script_path(p_original_path); // script needs this.
  1474. script->set_path(p_original_path);
  1475. Error err = script->load_byte_code(p_path);
  1476. if (err != OK) {
  1477. ERR_FAIL_COND_V(err != OK, RES());
  1478. }
  1479. } else {
  1480. Error err = script->load_source_code(p_path);
  1481. if (err != OK) {
  1482. ERR_FAIL_COND_V(err != OK, RES());
  1483. }
  1484. script->set_script_path(p_original_path); // script needs this.
  1485. script->set_path(p_original_path);
  1486. //script->set_name(p_path.get_file());
  1487. script->reload();
  1488. }
  1489. if (r_error)
  1490. *r_error = OK;
  1491. return scriptres;
  1492. }
  1493. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1494. p_extensions->push_back("gd");
  1495. p_extensions->push_back("gdc");
  1496. p_extensions->push_back("gde");
  1497. }
  1498. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  1499. return (p_type == "Script" || p_type == "GDScript");
  1500. }
  1501. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1502. String el = p_path.get_extension().to_lower();
  1503. if (el == "gd" || el == "gdc" || el == "gde")
  1504. return "GDScript";
  1505. return "";
  1506. }
  1507. Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1508. Ref<GDScript> sqscr = p_resource;
  1509. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1510. String source = sqscr->get_source_code();
  1511. Error err;
  1512. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1513. if (err) {
  1514. ERR_FAIL_COND_V(err, err);
  1515. }
  1516. file->store_string(source);
  1517. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1518. memdelete(file);
  1519. return ERR_CANT_CREATE;
  1520. }
  1521. file->close();
  1522. memdelete(file);
  1523. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1524. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1525. }
  1526. return OK;
  1527. }
  1528. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1529. if (p_resource->cast_to<GDScript>()) {
  1530. p_extensions->push_back("gd");
  1531. }
  1532. }
  1533. bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
  1534. return p_resource->cast_to<GDScript>() != NULL;
  1535. }