gd_script.cpp 45 KB

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