gd_script.cpp 44 KB

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