gd_script.cpp 47 KB

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