gd_script.cpp 47 KB

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