gd_script.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  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. #ifdef DEBUG_ENABLED
  619. if (GDScriptLanguage::get_singleton()->lock) {
  620. GDScriptLanguage::get_singleton()->lock->lock();
  621. }
  622. GDScriptLanguage::get_singleton()->script_list.remove(&script_list);
  623. if (GDScriptLanguage::get_singleton()->lock) {
  624. GDScriptLanguage::get_singleton()->lock->unlock();
  625. }
  626. #endif
  627. }
  628. //////////////////////////////
  629. // INSTANCE //
  630. //////////////////////////////
  631. bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
  632. //member
  633. {
  634. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  635. if (E) {
  636. if (E->get().setter) {
  637. const Variant *val=&p_value;
  638. Variant::CallError err;
  639. call(E->get().setter,&val,1,err);
  640. if (err.error==Variant::CallError::CALL_OK) {
  641. return true; //function exists, call was successful
  642. }
  643. }
  644. else
  645. members[E->get().index] = p_value;
  646. return true;
  647. }
  648. }
  649. GDScript *sptr=script.ptr();
  650. while(sptr) {
  651. Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  652. if (E) {
  653. Variant name=p_name;
  654. const Variant *args[2]={&name,&p_value};
  655. Variant::CallError err;
  656. Variant ret = E->get()->call(this,(const Variant**)args,2,err);
  657. if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool())
  658. return true;
  659. }
  660. sptr = sptr->_base;
  661. }
  662. return false;
  663. }
  664. bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
  665. const GDScript *sptr=script.ptr();
  666. while(sptr) {
  667. {
  668. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  669. if (E) {
  670. if (E->get().getter) {
  671. Variant::CallError err;
  672. r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err);
  673. if (err.error==Variant::CallError::CALL_OK) {
  674. return true;
  675. }
  676. }
  677. r_ret=members[E->get().index];
  678. return true; //index found
  679. }
  680. }
  681. {
  682. const Map<StringName,Variant>::Element *E = script->constants.find(p_name);
  683. if (E) {
  684. r_ret=E->get();
  685. return true; //index found
  686. }
  687. }
  688. {
  689. const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  690. if (E) {
  691. Variant name=p_name;
  692. const Variant *args[1]={&name};
  693. Variant::CallError err;
  694. Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err);
  695. if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
  696. r_ret=ret;
  697. return true;
  698. }
  699. }
  700. }
  701. sptr = sptr->_base;
  702. }
  703. return false;
  704. }
  705. Variant::Type GDInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const {
  706. const GDScript *sptr=script.ptr();
  707. while(sptr) {
  708. if (sptr->member_info.has(p_name)) {
  709. if (r_is_valid)
  710. *r_is_valid=true;
  711. return sptr->member_info[p_name].type;
  712. }
  713. sptr = sptr->_base;
  714. }
  715. if (r_is_valid)
  716. *r_is_valid=false;
  717. return Variant::NIL;
  718. }
  719. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  720. // exported members, not doen yet!
  721. const GDScript *sptr=script.ptr();
  722. List<PropertyInfo> props;
  723. while(sptr) {
  724. const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  725. if (E) {
  726. Variant::CallError err;
  727. Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),NULL,0,err);
  728. if (err.error==Variant::CallError::CALL_OK) {
  729. if (ret.get_type()!=Variant::ARRAY) {
  730. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  731. ERR_FAIL();
  732. }
  733. Array arr = ret;
  734. for(int i=0;i<arr.size();i++) {
  735. Dictionary d = arr[i];
  736. ERR_CONTINUE(!d.has("name"));
  737. ERR_CONTINUE(!d.has("type"));
  738. PropertyInfo pinfo;
  739. pinfo.type = Variant::Type( d["type"].operator int());
  740. ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX );
  741. pinfo.name = d["name"];
  742. ERR_CONTINUE(pinfo.name=="");
  743. if (d.has("hint"))
  744. pinfo.hint=PropertyHint(d["hint"].operator int());
  745. if (d.has("hint_string"))
  746. pinfo.hint_string=d["hint_string"];
  747. if (d.has("usage"))
  748. pinfo.usage=d["usage"];
  749. props.push_back(pinfo);
  750. }
  751. }
  752. }
  753. //instance a fake script for editing the values
  754. Vector<_GDScriptMemberSort> msort;
  755. for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
  756. _GDScriptMemberSort ms;
  757. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  758. ms.index=sptr->member_indices[E->key()].index;
  759. ms.name=E->key();
  760. msort.push_back(ms);
  761. }
  762. msort.sort();
  763. msort.invert();
  764. for(int i=0;i<msort.size();i++) {
  765. props.push_front(sptr->member_info[msort[i].name]);
  766. }
  767. #if 0
  768. if (sptr->member_functions.has("_get_property_list")) {
  769. Variant::CallError err;
  770. GDFunction *f = const_cast<GDFunction*>(sptr->member_functions["_get_property_list"]);
  771. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  772. if (plv.get_type()!=Variant::ARRAY) {
  773. ERR_PRINT("_get_property_list: expected array returned");
  774. } else {
  775. Array pl=plv;
  776. for(int i=0;i<pl.size();i++) {
  777. Dictionary p = pl[i];
  778. PropertyInfo pinfo;
  779. if (!p.has("name")) {
  780. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  781. continue;
  782. }
  783. if (!p.has("type")) {
  784. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  785. continue;
  786. }
  787. pinfo.name=p["name"];
  788. pinfo.type=Variant::Type(int(p["type"]));
  789. if (p.has("hint"))
  790. pinfo.hint=PropertyHint(int(p["hint"]));
  791. if (p.has("hint_string"))
  792. pinfo.hint_string=p["hint_string"];
  793. if (p.has("usage"))
  794. pinfo.usage=p["usage"];
  795. props.push_back(pinfo);
  796. }
  797. }
  798. }
  799. #endif
  800. sptr = sptr->_base;
  801. }
  802. //props.invert();
  803. for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  804. p_properties->push_back(E->get());
  805. }
  806. }
  807. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  808. const GDScript *sptr=script.ptr();
  809. while(sptr) {
  810. for (Map<StringName,GDFunction*>::Element *E = sptr->member_functions.front();E;E=E->next()) {
  811. MethodInfo mi;
  812. mi.name=E->key();
  813. mi.flags|=METHOD_FLAG_FROM_SCRIPT;
  814. for(int i=0;i<E->get()->get_argument_count();i++)
  815. mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
  816. p_list->push_back(mi);
  817. }
  818. sptr = sptr->_base;
  819. }
  820. }
  821. bool GDInstance::has_method(const StringName& p_method) const {
  822. const GDScript *sptr=script.ptr();
  823. while(sptr) {
  824. const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
  825. if (E)
  826. return true;
  827. sptr = sptr->_base;
  828. }
  829. return false;
  830. }
  831. Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  832. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  833. GDScript *sptr=script.ptr();
  834. while(sptr) {
  835. Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
  836. if (E) {
  837. return E->get()->call(this,p_args,p_argcount,r_error);
  838. }
  839. sptr = sptr->_base;
  840. }
  841. r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  842. return Variant();
  843. }
  844. void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
  845. GDScript *sptr=script.ptr();
  846. Variant::CallError ce;
  847. while(sptr) {
  848. Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
  849. if (E) {
  850. E->get()->call(this,p_args,p_argcount,ce);
  851. }
  852. sptr = sptr->_base;
  853. }
  854. }
  855. void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) {
  856. if (sptr->_base)
  857. _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount);
  858. Variant::CallError ce;
  859. Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
  860. if (E) {
  861. E->get()->call(this,p_args,p_argcount,ce);
  862. }
  863. }
  864. void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
  865. if (script.ptr()) {
  866. _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount);
  867. }
  868. }
  869. void GDInstance::notification(int p_notification) {
  870. //notification is not virutal, it gets called at ALL levels just like in C.
  871. Variant value=p_notification;
  872. const Variant *args[1]={&value };
  873. GDScript *sptr=script.ptr();
  874. while(sptr) {
  875. Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  876. if (E) {
  877. Variant::CallError err;
  878. E->get()->call(this,args,1,err);
  879. if (err.error!=Variant::CallError::CALL_OK) {
  880. //print error about notification call
  881. }
  882. }
  883. sptr = sptr->_base;
  884. }
  885. }
  886. Ref<Script> GDInstance::get_script() const {
  887. return script;
  888. }
  889. ScriptLanguage *GDInstance::get_language() {
  890. return GDScriptLanguage::get_singleton();
  891. }
  892. void GDInstance::reload_members() {
  893. #ifdef DEBUG_ENABLED
  894. members.resize(script->member_indices.size()); //resize
  895. Vector<Variant> new_members;
  896. new_members.resize(script->member_indices.size());
  897. //pass the values to the new indices
  898. for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) {
  899. if (member_indices_cache.has(E->key())) {
  900. Variant value = members[member_indices_cache[E->key()]];
  901. new_members[E->get().index]=value;
  902. }
  903. }
  904. //apply
  905. members=new_members;
  906. //pass the values to the new indices
  907. member_indices_cache.clear();
  908. for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) {
  909. member_indices_cache[E->key()]=E->get().index;
  910. }
  911. #endif
  912. }
  913. GDInstance::GDInstance() {
  914. owner=NULL;
  915. base_ref=false;
  916. }
  917. GDInstance::~GDInstance() {
  918. if (script.is_valid() && owner) {
  919. script->instances.erase(owner);
  920. }
  921. }
  922. /************* SCRIPT LANGUAGE **************/
  923. /************* SCRIPT LANGUAGE **************/
  924. /************* SCRIPT LANGUAGE **************/
  925. /************* SCRIPT LANGUAGE **************/
  926. /************* SCRIPT LANGUAGE **************/
  927. GDScriptLanguage *GDScriptLanguage::singleton=NULL;
  928. String GDScriptLanguage::get_name() const {
  929. return "GDScript";
  930. }
  931. /* LANGUAGE FUNCTIONS */
  932. void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) {
  933. if (globals.has(p_name)) {
  934. //overwrite existing
  935. global_array[globals[p_name]]=p_value;
  936. return;
  937. }
  938. globals[p_name]=global_array.size();
  939. global_array.push_back(p_value);
  940. _global_array=global_array.ptr();
  941. }
  942. void GDScriptLanguage::add_global_constant(const StringName& p_variable,const Variant& p_value) {
  943. _add_global(p_variable,p_value);
  944. }
  945. void GDScriptLanguage::init() {
  946. //populate global constants
  947. int gcc=GlobalConstants::get_global_constant_count();
  948. for(int i=0;i<gcc;i++) {
  949. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i));
  950. }
  951. _add_global(StaticCString::create("PI"),Math_PI);
  952. //populate native classes
  953. List<StringName> class_list;
  954. ObjectTypeDB::get_type_list(&class_list);
  955. for(List<StringName>::Element *E=class_list.front();E;E=E->next()) {
  956. StringName n = E->get();
  957. String s = String(n);
  958. if (s.begins_with("_"))
  959. n=s.substr(1,s.length());
  960. if (globals.has(n))
  961. continue;
  962. Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) );
  963. _add_global(n,nc);
  964. }
  965. //populate singletons
  966. List<Globals::Singleton> singletons;
  967. Globals::get_singleton()->get_singletons(&singletons);
  968. for(List<Globals::Singleton>::Element *E=singletons.front();E;E=E->next()) {
  969. _add_global(E->get().name,E->get().ptr);
  970. }
  971. }
  972. String GDScriptLanguage::get_type() const {
  973. return "GDScript";
  974. }
  975. String GDScriptLanguage::get_extension() const {
  976. return "gd";
  977. }
  978. Error GDScriptLanguage::execute_file(const String& p_path) {
  979. // ??
  980. return OK;
  981. }
  982. void GDScriptLanguage::finish() {
  983. }
  984. void GDScriptLanguage::profiling_start() {
  985. #ifdef DEBUG_ENABLED
  986. if (lock) {
  987. lock->lock();
  988. }
  989. SelfList<GDFunction> *elem=function_list.first();
  990. while(elem) {
  991. elem->self()->profile.call_count=0;
  992. elem->self()->profile.self_time=0;
  993. elem->self()->profile.total_time=0;
  994. elem->self()->profile.frame_call_count=0;
  995. elem->self()->profile.frame_self_time=0;
  996. elem->self()->profile.frame_total_time=0;
  997. elem->self()->profile.last_frame_call_count=0;
  998. elem->self()->profile.last_frame_self_time=0;
  999. elem->self()->profile.last_frame_total_time=0;
  1000. elem=elem->next();
  1001. }
  1002. profiling=true;
  1003. if (lock) {
  1004. lock->unlock();
  1005. }
  1006. #endif
  1007. }
  1008. void GDScriptLanguage::profiling_stop() {
  1009. #ifdef DEBUG_ENABLED
  1010. if (lock) {
  1011. lock->lock();
  1012. }
  1013. profiling=false;
  1014. if (lock) {
  1015. lock->unlock();
  1016. }
  1017. #endif
  1018. }
  1019. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max) {
  1020. int current=0;
  1021. #ifdef DEBUG_ENABLED
  1022. if (lock) {
  1023. lock->lock();
  1024. }
  1025. SelfList<GDFunction> *elem=function_list.first();
  1026. while(elem) {
  1027. if (current>=p_info_max)
  1028. break;
  1029. p_info_arr[current].call_count=elem->self()->profile.call_count;
  1030. p_info_arr[current].self_time=elem->self()->profile.self_time;
  1031. p_info_arr[current].total_time=elem->self()->profile.total_time;
  1032. p_info_arr[current].signature=elem->self()->profile.signature;
  1033. elem=elem->next();
  1034. current++;
  1035. }
  1036. if (lock) {
  1037. lock->unlock();
  1038. }
  1039. #endif
  1040. return current;
  1041. }
  1042. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max) {
  1043. int current=0;
  1044. #ifdef DEBUG_ENABLED
  1045. if (lock) {
  1046. lock->lock();
  1047. }
  1048. SelfList<GDFunction> *elem=function_list.first();
  1049. while(elem) {
  1050. if (current>=p_info_max)
  1051. break;
  1052. if (elem->self()->profile.last_frame_call_count>0) {
  1053. p_info_arr[current].call_count=elem->self()->profile.last_frame_call_count;
  1054. p_info_arr[current].self_time=elem->self()->profile.last_frame_self_time;
  1055. p_info_arr[current].total_time=elem->self()->profile.last_frame_total_time;
  1056. p_info_arr[current].signature=elem->self()->profile.signature;
  1057. //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
  1058. current++;
  1059. }
  1060. elem=elem->next();
  1061. }
  1062. if (lock) {
  1063. lock->unlock();
  1064. }
  1065. #endif
  1066. return current;
  1067. }
  1068. struct GDScriptDepSort {
  1069. //must support sorting so inheritance works properly (parent must be reloaded first)
  1070. bool operator()(const Ref<GDScript> &A, const Ref<GDScript>& B) const {
  1071. if (A==B)
  1072. return false; //shouldn't happen but..
  1073. const GDScript *I=B->get_base().ptr();
  1074. while(I) {
  1075. if (I==A.ptr()) {
  1076. // A is a base of B
  1077. return true;
  1078. }
  1079. I=I->get_base().ptr();
  1080. }
  1081. return false; //not a base
  1082. }
  1083. };
  1084. void GDScriptLanguage::reload_all_scripts() {
  1085. #ifdef DEBUG_ENABLED
  1086. print_line("RELOAD ALL SCRIPTS");
  1087. if (lock) {
  1088. lock->lock();
  1089. }
  1090. List<Ref<GDScript> > scripts;
  1091. SelfList<GDScript> *elem=script_list.first();
  1092. while(elem) {
  1093. if (elem->self()->get_path().is_resource_file()) {
  1094. print_line("FOUND: "+elem->self()->get_path());
  1095. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1096. }
  1097. elem=elem->next();
  1098. }
  1099. if (lock) {
  1100. lock->unlock();
  1101. }
  1102. //as scripts are going to be reloaded, must proceed without locking here
  1103. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1104. for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) {
  1105. print_line("RELOADING: "+E->get()->get_path());
  1106. E->get()->load_source_code(E->get()->get_path());
  1107. E->get()->reload(true);
  1108. }
  1109. #endif
  1110. }
  1111. void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload) {
  1112. #ifdef DEBUG_ENABLED
  1113. if (lock) {
  1114. lock->lock();
  1115. }
  1116. List<Ref<GDScript> > scripts;
  1117. SelfList<GDScript> *elem=script_list.first();
  1118. while(elem) {
  1119. if (elem->self()->get_path().is_resource_file()) {
  1120. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1121. }
  1122. elem=elem->next();
  1123. }
  1124. if (lock) {
  1125. lock->unlock();
  1126. }
  1127. //when someone asks you why dynamically typed languages are easier to write....
  1128. Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > > to_reload;
  1129. //as scripts are going to be reloaded, must proceed without locking here
  1130. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1131. for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) {
  1132. bool reload = E->get()==p_script || to_reload.has(E->get()->get_base());
  1133. if (!reload)
  1134. continue;
  1135. to_reload.insert(E->get(),Map<ObjectID,List<Pair<StringName,Variant> > >());
  1136. if (!p_soft_reload) {
  1137. //save state and remove script from instances
  1138. Map<ObjectID,List<Pair<StringName,Variant> > >& map = to_reload[E->get()];
  1139. while(E->get()->instances.front()) {
  1140. Object *obj = E->get()->instances.front()->get();
  1141. //save instance info
  1142. List<Pair<StringName,Variant> > state;
  1143. if (obj->get_script_instance()) {
  1144. obj->get_script_instance()->get_property_state(state);
  1145. map[obj->get_instance_ID()]=state;
  1146. obj->set_script(RefPtr());
  1147. }
  1148. }
  1149. //same thing for placeholders
  1150. #ifdef TOOLS_ENABLED
  1151. while(E->get()->placeholders.size()) {
  1152. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  1153. //save instance info
  1154. List<Pair<StringName,Variant> > state;
  1155. if (obj->get_script_instance()) {
  1156. obj->get_script_instance()->get_property_state(state);
  1157. map[obj->get_instance_ID()]=state;
  1158. obj->set_script(RefPtr());
  1159. }
  1160. }
  1161. #endif
  1162. }
  1163. }
  1164. for(Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > >::Element *E=to_reload.front();E;E=E->next()) {
  1165. Ref<GDScript> scr = E->key();
  1166. scr->reload(true);
  1167. //restore state if saved
  1168. for (Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get().front();F;F=F->next()) {
  1169. Object *obj = ObjectDB::get_instance(F->key());
  1170. if (!obj)
  1171. continue;
  1172. obj->set_script(scr.get_ref_ptr());
  1173. if (!obj->get_script_instance())
  1174. continue;
  1175. for (List<Pair<StringName,Variant> >::Element *G=F->get().front();G;G=G->next()) {
  1176. obj->get_script_instance()->set(G->get().first,G->get().second);
  1177. }
  1178. }
  1179. //if instance states were saved, set them!
  1180. }
  1181. #endif
  1182. }
  1183. void GDScriptLanguage::frame() {
  1184. // print_line("calls: "+itos(calls));
  1185. calls=0;
  1186. #ifdef DEBUG_ENABLED
  1187. if (profiling) {
  1188. if (lock) {
  1189. lock->lock();
  1190. }
  1191. SelfList<GDFunction> *elem=function_list.first();
  1192. while(elem) {
  1193. elem->self()->profile.last_frame_call_count=elem->self()->profile.frame_call_count;
  1194. elem->self()->profile.last_frame_self_time=elem->self()->profile.frame_self_time;
  1195. elem->self()->profile.last_frame_total_time=elem->self()->profile.frame_total_time;
  1196. elem->self()->profile.frame_call_count=0;
  1197. elem->self()->profile.frame_self_time=0;
  1198. elem->self()->profile.frame_total_time=0;
  1199. elem=elem->next();
  1200. }
  1201. if (lock) {
  1202. lock->unlock();
  1203. }
  1204. }
  1205. #endif
  1206. }
  1207. /* EDITOR FUNCTIONS */
  1208. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1209. static const char *_reserved_words[]={
  1210. // operators
  1211. "and",
  1212. "in",
  1213. "not",
  1214. "or",
  1215. // types and values
  1216. "false",
  1217. "float",
  1218. "int",
  1219. "null",
  1220. "PI",
  1221. "self",
  1222. "true",
  1223. // functions
  1224. "assert",
  1225. "breakpoint",
  1226. "class",
  1227. "extends",
  1228. "func",
  1229. "preload",
  1230. "setget",
  1231. "signal",
  1232. "tool",
  1233. "yield",
  1234. // var
  1235. "const",
  1236. "enum",
  1237. "export",
  1238. "onready",
  1239. "static",
  1240. "var",
  1241. // control flow
  1242. "break",
  1243. "continue",
  1244. "if",
  1245. "elif",
  1246. "else",
  1247. "for",
  1248. "pass",
  1249. "return",
  1250. "while",
  1251. 0};
  1252. const char **w=_reserved_words;
  1253. while (*w) {
  1254. p_words->push_back(*w);
  1255. w++;
  1256. }
  1257. for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
  1258. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1259. }
  1260. }
  1261. GDScriptLanguage::GDScriptLanguage() {
  1262. calls=0;
  1263. ERR_FAIL_COND(singleton);
  1264. singleton=this;
  1265. strings._init = StaticCString::create("_init");
  1266. strings._notification = StaticCString::create("_notification");
  1267. strings._set= StaticCString::create("_set");
  1268. strings._get= StaticCString::create("_get");
  1269. strings._get_property_list= StaticCString::create("_get_property_list");
  1270. strings._script_source=StaticCString::create("script/source");
  1271. _debug_parse_err_line=-1;
  1272. _debug_parse_err_file="";
  1273. #ifdef NO_THREADS
  1274. lock=NULL;
  1275. #else
  1276. lock = Mutex::create();
  1277. #endif
  1278. profiling=false;
  1279. script_frame_time=0;
  1280. _debug_call_stack_pos=0;
  1281. int dmcs=GLOBAL_DEF("debug/script_max_call_stack",1024);
  1282. if (ScriptDebugger::get_singleton()) {
  1283. //debugging enabled!
  1284. _debug_max_call_stack = dmcs;
  1285. if (_debug_max_call_stack<1024)
  1286. _debug_max_call_stack=1024;
  1287. _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
  1288. } else {
  1289. _debug_max_call_stack=0;
  1290. _call_stack=NULL;
  1291. }
  1292. }
  1293. GDScriptLanguage::~GDScriptLanguage() {
  1294. if (lock) {
  1295. memdelete(lock);
  1296. lock=NULL;
  1297. }
  1298. if (_call_stack) {
  1299. memdelete_arr(_call_stack);
  1300. }
  1301. singleton=NULL;
  1302. }
  1303. /*************** RESOURCE ***************/
  1304. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_original_path, Error *r_error) {
  1305. if (r_error)
  1306. *r_error=ERR_FILE_CANT_OPEN;
  1307. GDScript *script = memnew( GDScript );
  1308. Ref<GDScript> scriptres(script);
  1309. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1310. script->set_script_path(p_original_path); // script needs this.
  1311. script->set_path(p_original_path);
  1312. Error err = script->load_byte_code(p_path);
  1313. if (err!=OK) {
  1314. ERR_FAIL_COND_V(err!=OK, RES());
  1315. }
  1316. } else {
  1317. Error err = script->load_source_code(p_path);
  1318. if (err!=OK) {
  1319. ERR_FAIL_COND_V(err!=OK, RES());
  1320. }
  1321. script->set_script_path(p_original_path); // script needs this.
  1322. script->set_path(p_original_path);
  1323. //script->set_name(p_path.get_file());
  1324. script->reload();
  1325. }
  1326. if (r_error)
  1327. *r_error=OK;
  1328. return scriptres;
  1329. }
  1330. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1331. p_extensions->push_back("gd");
  1332. p_extensions->push_back("gdc");
  1333. p_extensions->push_back("gde");
  1334. }
  1335. bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const {
  1336. return (p_type=="Script" || p_type=="GDScript");
  1337. }
  1338. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1339. String el = p_path.extension().to_lower();
  1340. if (el=="gd" || el=="gdc" || el=="gde")
  1341. return "GDScript";
  1342. return "";
  1343. }
  1344. Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
  1345. Ref<GDScript> sqscr = p_resource;
  1346. ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER);
  1347. String source = sqscr->get_source_code();
  1348. Error err;
  1349. FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
  1350. if (err) {
  1351. ERR_FAIL_COND_V(err,err);
  1352. }
  1353. file->store_string(source);
  1354. if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) {
  1355. memdelete(file);
  1356. return ERR_CANT_CREATE;
  1357. }
  1358. file->close();
  1359. memdelete(file);
  1360. return OK;
  1361. }
  1362. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
  1363. if (p_resource->cast_to<GDScript>()) {
  1364. p_extensions->push_back("gd");
  1365. }
  1366. }
  1367. bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const {
  1368. return p_resource->cast_to<GDScript>()!=NULL;
  1369. }