gd_script.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  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. Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self, Variant *p_stack,String& r_error) const{
  36. int address = p_address&ADDR_MASK;
  37. //sequential table (jump table generated by compiler)
  38. switch((p_address&ADDR_TYPE_MASK)>>ADDR_BITS) {
  39. case ADDR_TYPE_SELF: {
  40. if (!p_instance) {
  41. r_error="Cannot access self without instance.";
  42. return NULL;
  43. }
  44. return &self;
  45. } break;
  46. case ADDR_TYPE_CLASS: {
  47. return &p_script->_static_ref;
  48. } break;
  49. case ADDR_TYPE_MEMBER: {
  50. //member indexing is O(1)
  51. if (!p_instance) {
  52. r_error="Cannot access member without instance.";
  53. return NULL;
  54. }
  55. return &p_instance->members[address];
  56. } break;
  57. case ADDR_TYPE_CLASS_CONSTANT: {
  58. //todo change to index!
  59. GDScript *o=p_script;
  60. ERR_FAIL_INDEX_V(address,_global_names_count,NULL);
  61. const StringName *sn = &_global_names_ptr[address];
  62. while(o) {
  63. GDScript *s=o;
  64. while(s) {
  65. Map<StringName,Variant>::Element *E=s->constants.find(*sn);
  66. if (E) {
  67. return &E->get();
  68. }
  69. s=s->_base;
  70. }
  71. o=o->_owner;
  72. }
  73. ERR_EXPLAIN("GDCompiler bug..");
  74. ERR_FAIL_V(NULL);
  75. } break;
  76. case ADDR_TYPE_LOCAL_CONSTANT: {
  77. ERR_FAIL_INDEX_V(address,_constant_count,NULL);
  78. return &_constants_ptr[address];
  79. } break;
  80. case ADDR_TYPE_STACK:
  81. case ADDR_TYPE_STACK_VARIABLE: {
  82. ERR_FAIL_INDEX_V(address,_stack_size,NULL);
  83. return &p_stack[address];
  84. } break;
  85. case ADDR_TYPE_GLOBAL: {
  86. ERR_FAIL_INDEX_V(address,GDScriptLanguage::get_singleton()->get_global_array_size(),NULL);
  87. return &GDScriptLanguage::get_singleton()->get_global_array()[address];
  88. } break;
  89. case ADDR_TYPE_NIL: {
  90. return &nil;
  91. } break;
  92. }
  93. ERR_EXPLAIN("Bad Code! (Addressing Mode)");
  94. ERR_FAIL_V(NULL);
  95. return NULL;
  96. }
  97. String GDFunction::_get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const {
  98. String err_text;
  99. if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
  100. int errorarg=p_err.argument;
  101. err_text="Invalid type in "+p_where+". Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(p_err.expected)+".";
  102. } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
  103. err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
  104. } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
  105. err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
  106. } else if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
  107. err_text="Invalid call. Nonexistent "+p_where+".";
  108. } else if (p_err.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
  109. err_text="Attempt to call "+p_where+" on a null instance.";
  110. } else {
  111. err_text="Bug, call error: #"+itos(p_err.error);
  112. }
  113. return err_text;
  114. }
  115. static String _get_var_type(const Variant* p_type) {
  116. String basestr;
  117. if (p_type->get_type()==Variant::OBJECT) {
  118. Object *bobj = *p_type;
  119. if (!bobj) {
  120. basestr = "null instance";
  121. } else {
  122. #ifdef DEBUG_ENABLED
  123. if (ObjectDB::instance_validate(bobj)) {
  124. if (bobj->get_script_instance())
  125. basestr= bobj->get_type()+" ("+bobj->get_script_instance()->get_script()->get_path().get_file()+")";
  126. else
  127. basestr = bobj->get_type();
  128. } else {
  129. basestr="previously freed instance";
  130. }
  131. #else
  132. basestr="Object";
  133. #endif
  134. }
  135. } else {
  136. basestr = Variant::get_type_name(p_type->get_type());
  137. }
  138. return basestr;
  139. }
  140. Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError& r_err, CallState *p_state) {
  141. if (!_code_ptr) {
  142. return Variant();
  143. }
  144. r_err.error=Variant::CallError::CALL_OK;
  145. Variant self;
  146. Variant retvalue;
  147. Variant *stack = NULL;
  148. Variant **call_args;
  149. int defarg=0;
  150. #ifdef DEBUG_ENABLED
  151. //GDScriptLanguage::get_singleton()->calls++;
  152. #endif
  153. uint32_t alloca_size=0;
  154. GDScript *_class;
  155. int ip=0;
  156. int line=_initial_line;
  157. if (p_state) {
  158. //use existing (supplied) state (yielded)
  159. stack=(Variant*)p_state->stack.ptr();
  160. call_args=(Variant**)&p_state->stack[sizeof(Variant)*p_state->stack_size];
  161. line=p_state->line;
  162. ip=p_state->ip;
  163. alloca_size=p_state->stack.size();
  164. _class=p_state->_class;
  165. p_instance=p_state->instance;
  166. defarg=p_state->defarg;
  167. self=p_state->self;
  168. //stack[p_state->result_pos]=p_state->result; //assign stack with result
  169. } else {
  170. if (p_argcount!=_argument_count) {
  171. if (p_argcount>_argument_count) {
  172. r_err.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  173. r_err.argument=_argument_count;
  174. return Variant();
  175. } else if (p_argcount < _argument_count - _default_arg_count) {
  176. r_err.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  177. r_err.argument=_argument_count - _default_arg_count;
  178. return Variant();
  179. } else {
  180. defarg=_argument_count-p_argcount;
  181. }
  182. }
  183. alloca_size = sizeof(Variant*)*_call_size + sizeof(Variant)*_stack_size;
  184. if (alloca_size) {
  185. uint8_t *aptr = (uint8_t*)alloca(alloca_size);
  186. if (_stack_size) {
  187. stack=(Variant*)aptr;
  188. for(int i=0;i<p_argcount;i++)
  189. memnew_placement(&stack[i],Variant(*p_args[i]));
  190. for(int i=p_argcount;i<_stack_size;i++)
  191. memnew_placement(&stack[i],Variant);
  192. } else {
  193. stack=NULL;
  194. }
  195. if (_call_size) {
  196. call_args = (Variant**)&aptr[sizeof(Variant)*_stack_size];
  197. } else {
  198. call_args=NULL;
  199. }
  200. } else {
  201. stack=NULL;
  202. call_args=NULL;
  203. }
  204. if (p_instance) {
  205. if (p_instance->base_ref && static_cast<Reference*>(p_instance->owner)->is_referenced()) {
  206. self=REF(static_cast<Reference*>(p_instance->owner));
  207. } else {
  208. self=p_instance->owner;
  209. }
  210. _class=p_instance->script.ptr();
  211. } else {
  212. _class=_script;
  213. }
  214. }
  215. String err_text;
  216. #ifdef DEBUG_ENABLED
  217. if (ScriptDebugger::get_singleton())
  218. GDScriptLanguage::get_singleton()->enter_function(p_instance,this,stack,&ip,&line);
  219. #define CHECK_SPACE(m_space)\
  220. ERR_BREAK((ip+m_space)>_code_size)
  221. #define GET_VARIANT_PTR(m_v,m_code_ofs) \
  222. Variant *m_v; \
  223. m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);\
  224. if (!m_v)\
  225. break;
  226. #else
  227. #define CHECK_SPACE(m_space)
  228. #define GET_VARIANT_PTR(m_v,m_code_ofs) \
  229. Variant *m_v; \
  230. m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);
  231. #endif
  232. bool exit_ok=false;
  233. while(ip<_code_size) {
  234. int last_opcode=_code_ptr[ip];
  235. switch(_code_ptr[ip]) {
  236. case OPCODE_OPERATOR: {
  237. CHECK_SPACE(5);
  238. bool valid;
  239. Variant::Operator op = (Variant::Operator)_code_ptr[ip+1];
  240. ERR_BREAK(op>=Variant::OP_MAX);
  241. GET_VARIANT_PTR(a,2);
  242. GET_VARIANT_PTR(b,3);
  243. GET_VARIANT_PTR(dst,4);
  244. #ifdef DEBUG_ENABLED
  245. Variant ret;
  246. Variant::evaluate(op,*a,*b,ret,valid);
  247. #else
  248. Variant::evaluate(op,*a,*b,*dst,valid);
  249. #endif
  250. if (!valid) {
  251. #ifdef DEBUG_ENABLED
  252. if (ret.get_type()==Variant::STRING) {
  253. //return a string when invalid with the error
  254. err_text=ret;
  255. err_text += " in operator '"+Variant::get_operator_name(op)+"'.";
  256. } else {
  257. err_text="Invalid operands '"+Variant::get_type_name(a->get_type())+"' and '"+Variant::get_type_name(b->get_type())+"' in operator '"+Variant::get_operator_name(op)+"'.";
  258. }
  259. #endif
  260. break;
  261. }
  262. #ifdef DEBUG_ENABLED
  263. *dst=ret;
  264. #endif
  265. ip+=5;
  266. } continue;
  267. case OPCODE_EXTENDS_TEST: {
  268. CHECK_SPACE(4);
  269. GET_VARIANT_PTR(a,1);
  270. GET_VARIANT_PTR(b,2);
  271. GET_VARIANT_PTR(dst,3);
  272. #ifdef DEBUG_ENABLED
  273. if (a->get_type()!=Variant::OBJECT || a->operator Object*()==NULL) {
  274. err_text="Left operand of 'extends' is not an instance of anything.";
  275. break;
  276. }
  277. if (b->get_type()!=Variant::OBJECT || b->operator Object*()==NULL) {
  278. err_text="Right operand of 'extends' is not a class.";
  279. break;
  280. }
  281. #endif
  282. Object *obj_A = *a;
  283. Object *obj_B = *b;
  284. GDScript *scr_B = obj_B->cast_to<GDScript>();
  285. bool extends_ok=false;
  286. if (scr_B) {
  287. //if B is a script, the only valid condition is that A has an instance which inherits from the script
  288. //in other situation, this shoul return false.
  289. if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language()==GDScriptLanguage::get_singleton()) {
  290. GDInstance *ins = static_cast<GDInstance*>(obj_A->get_script_instance());
  291. GDScript *cmp = ins->script.ptr();
  292. //bool found=false;
  293. while(cmp) {
  294. if (cmp==scr_B) {
  295. //inherits from script, all ok
  296. extends_ok=true;
  297. break;
  298. }
  299. cmp=cmp->_base;
  300. }
  301. }
  302. } else {
  303. GDNativeClass *nc= obj_B->cast_to<GDNativeClass>();
  304. if (!nc) {
  305. err_text="Right operand of 'extends' is not a class (type: '"+obj_B->get_type()+"').";
  306. break;
  307. }
  308. extends_ok=ObjectTypeDB::is_type(obj_A->get_type_name(),nc->get_name());
  309. }
  310. *dst=extends_ok;
  311. ip+=4;
  312. } continue;
  313. case OPCODE_SET: {
  314. CHECK_SPACE(3);
  315. GET_VARIANT_PTR(dst,1);
  316. GET_VARIANT_PTR(index,2);
  317. GET_VARIANT_PTR(value,3);
  318. bool valid;
  319. dst->set(*index,*value,&valid);
  320. if (!valid) {
  321. String v = index->operator String();
  322. if (v!="") {
  323. v="'"+v+"'";
  324. } else {
  325. v="of type '"+_get_var_type(index)+"'";
  326. }
  327. err_text="Invalid set index "+v+" (on base: '"+_get_var_type(dst)+"').";
  328. break;
  329. }
  330. ip+=4;
  331. } continue;
  332. case OPCODE_GET: {
  333. CHECK_SPACE(3);
  334. GET_VARIANT_PTR(src,1);
  335. GET_VARIANT_PTR(index,2);
  336. GET_VARIANT_PTR(dst,3);
  337. bool valid;
  338. #ifdef DEBUG_ENABLED
  339. //allow better error message in cases where src and dst are the same stack position
  340. Variant ret = src->get(*index,&valid);
  341. #else
  342. *dst = src->get(*index,&valid);
  343. #endif
  344. if (!valid) {
  345. String v = index->operator String();
  346. if (v!="") {
  347. v="'"+v+"'";
  348. } else {
  349. v="of type '"+_get_var_type(index)+"'";
  350. }
  351. err_text="Invalid get index "+v+" (on base: '"+_get_var_type(src)+"').";
  352. break;
  353. }
  354. #ifdef DEBUG_ENABLED
  355. *dst=ret;
  356. #endif
  357. ip+=4;
  358. } continue;
  359. case OPCODE_SET_NAMED: {
  360. CHECK_SPACE(3);
  361. GET_VARIANT_PTR(dst,1);
  362. GET_VARIANT_PTR(value,3);
  363. int indexname = _code_ptr[ip+2];
  364. ERR_BREAK(indexname<0 || indexname>=_global_names_count);
  365. const StringName *index = &_global_names_ptr[indexname];
  366. bool valid;
  367. dst->set_named(*index,*value,&valid);
  368. if (!valid) {
  369. String err_type;
  370. err_text="Invalid set index '"+String(*index)+"' (on base: '"+_get_var_type(dst)+"').";
  371. break;
  372. }
  373. ip+=4;
  374. } continue;
  375. case OPCODE_GET_NAMED: {
  376. CHECK_SPACE(3);
  377. GET_VARIANT_PTR(src,1);
  378. GET_VARIANT_PTR(dst,3);
  379. int indexname = _code_ptr[ip+2];
  380. ERR_BREAK(indexname<0 || indexname>=_global_names_count);
  381. const StringName *index = &_global_names_ptr[indexname];
  382. bool valid;
  383. #ifdef DEBUG_ENABLED
  384. //allow better error message in cases where src and dst are the same stack position
  385. Variant ret = src->get_named(*index,&valid);
  386. #else
  387. *dst = src->get_named(*index,&valid);
  388. #endif
  389. if (!valid) {
  390. if (src->has_method(*index)) {
  391. err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"'). Did you mean '."+index->operator String()+"()' ?";
  392. } else {
  393. err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"').";
  394. }
  395. break;
  396. }
  397. #ifdef DEBUG_ENABLED
  398. *dst=ret;
  399. #endif
  400. ip+=4;
  401. } continue;
  402. case OPCODE_ASSIGN: {
  403. CHECK_SPACE(3);
  404. GET_VARIANT_PTR(dst,1);
  405. GET_VARIANT_PTR(src,2);
  406. *dst = *src;
  407. ip+=3;
  408. } continue;
  409. case OPCODE_ASSIGN_TRUE: {
  410. CHECK_SPACE(2);
  411. GET_VARIANT_PTR(dst,1);
  412. *dst = true;
  413. ip+=2;
  414. } continue;
  415. case OPCODE_ASSIGN_FALSE: {
  416. CHECK_SPACE(2);
  417. GET_VARIANT_PTR(dst,1);
  418. *dst = false;
  419. ip+=2;
  420. } continue;
  421. case OPCODE_CONSTRUCT: {
  422. CHECK_SPACE(2);
  423. Variant::Type t=Variant::Type(_code_ptr[ip+1]);
  424. int argc=_code_ptr[ip+2];
  425. CHECK_SPACE(argc+2);
  426. Variant **argptrs = call_args;
  427. for(int i=0;i<argc;i++) {
  428. GET_VARIANT_PTR(v,3+i);
  429. argptrs[i]=v;
  430. }
  431. GET_VARIANT_PTR(dst,3+argc);
  432. Variant::CallError err;
  433. *dst = Variant::construct(t,(const Variant**)argptrs,argc,err);
  434. if (err.error!=Variant::CallError::CALL_OK) {
  435. err_text=_get_call_error(err,"'"+Variant::get_type_name(t)+"' constructor",(const Variant**)argptrs);
  436. break;
  437. }
  438. ip+=4+argc;
  439. //construct a basic type
  440. } continue;
  441. case OPCODE_CONSTRUCT_ARRAY: {
  442. CHECK_SPACE(1);
  443. int argc=_code_ptr[ip+1];
  444. Array array(true); //arrays are always shared
  445. array.resize(argc);
  446. CHECK_SPACE(argc+2);
  447. for(int i=0;i<argc;i++) {
  448. GET_VARIANT_PTR(v,2+i);
  449. array[i]=*v;
  450. }
  451. GET_VARIANT_PTR(dst,2+argc);
  452. *dst=array;
  453. ip+=3+argc;
  454. } continue;
  455. case OPCODE_CONSTRUCT_DICTIONARY: {
  456. CHECK_SPACE(1);
  457. int argc=_code_ptr[ip+1];
  458. Dictionary dict(true); //arrays are always shared
  459. CHECK_SPACE(argc*2+2);
  460. for(int i=0;i<argc;i++) {
  461. GET_VARIANT_PTR(k,2+i*2+0);
  462. GET_VARIANT_PTR(v,2+i*2+1);
  463. dict[*k]=*v;
  464. }
  465. GET_VARIANT_PTR(dst,2+argc*2);
  466. *dst=dict;
  467. ip+=3+argc*2;
  468. } continue;
  469. case OPCODE_CALL_RETURN:
  470. case OPCODE_CALL: {
  471. CHECK_SPACE(4);
  472. bool call_ret = _code_ptr[ip]==OPCODE_CALL_RETURN;
  473. int argc=_code_ptr[ip+1];
  474. GET_VARIANT_PTR(base,2);
  475. int nameg=_code_ptr[ip+3];
  476. ERR_BREAK(nameg<0 || nameg>=_global_names_count);
  477. const StringName *methodname = &_global_names_ptr[nameg];
  478. ERR_BREAK(argc<0);
  479. ip+=4;
  480. CHECK_SPACE(argc+1);
  481. Variant **argptrs = call_args;
  482. for(int i=0;i<argc;i++) {
  483. GET_VARIANT_PTR(v,i);
  484. argptrs[i]=v;
  485. }
  486. Variant::CallError err;
  487. if (call_ret) {
  488. GET_VARIANT_PTR(ret,argc);
  489. *ret = base->call(*methodname,(const Variant**)argptrs,argc,err);
  490. } else {
  491. base->call(*methodname,(const Variant**)argptrs,argc,err);
  492. }
  493. if (err.error!=Variant::CallError::CALL_OK) {
  494. String methodstr = *methodname;
  495. String basestr = _get_var_type(base);
  496. if (methodstr=="call") {
  497. if (argc>=1) {
  498. methodstr=String(*argptrs[0])+" (via call)";
  499. if (err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
  500. err.argument-=1;
  501. }
  502. }
  503. } if (methodstr=="free") {
  504. if (err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
  505. if (base->is_ref()) {
  506. err_text="Attempted to free a reference.";
  507. break;
  508. } else if (base->get_type()==Variant::OBJECT) {
  509. err_text="Attempted to free a locked object (calling or emitting).";
  510. break;
  511. }
  512. }
  513. }
  514. err_text=_get_call_error(err,"function '"+methodstr+"' in base '"+basestr+"'",(const Variant**)argptrs);
  515. break;
  516. }
  517. //_call_func(NULL,base,*methodname,ip,argc,p_instance,stack);
  518. ip+=argc+1;
  519. } continue;
  520. case OPCODE_CALL_BUILT_IN: {
  521. CHECK_SPACE(4);
  522. GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip+1]);
  523. int argc=_code_ptr[ip+2];
  524. ERR_BREAK(argc<0);
  525. ip+=3;
  526. CHECK_SPACE(argc+1);
  527. Variant **argptrs = call_args;
  528. for(int i=0;i<argc;i++) {
  529. GET_VARIANT_PTR(v,i);
  530. argptrs[i]=v;
  531. }
  532. GET_VARIANT_PTR(dst,argc);
  533. Variant::CallError err;
  534. GDFunctions::call(func,(const Variant**)argptrs,argc,*dst,err);
  535. if (err.error!=Variant::CallError::CALL_OK) {
  536. String methodstr = GDFunctions::get_func_name(func);
  537. err_text=_get_call_error(err,"built-in function '"+methodstr+"'",(const Variant**)argptrs);
  538. break;
  539. }
  540. ip+=argc+1;
  541. } continue;
  542. case OPCODE_CALL_SELF: {
  543. } break;
  544. case OPCODE_CALL_SELF_BASE: {
  545. CHECK_SPACE(2);
  546. int self_fun = _code_ptr[ip+1];
  547. #ifdef DEBUG_ENABLED
  548. if (self_fun<0 || self_fun>=_global_names_count) {
  549. err_text="compiler bug, function name not found";
  550. break;
  551. }
  552. #endif
  553. const StringName *methodname = &_global_names_ptr[self_fun];
  554. int argc=_code_ptr[ip+2];
  555. CHECK_SPACE(2+argc+1);
  556. Variant **argptrs = call_args;
  557. for(int i=0;i<argc;i++) {
  558. GET_VARIANT_PTR(v,i+3);
  559. argptrs[i]=v;
  560. }
  561. GET_VARIANT_PTR(dst,argc+3);
  562. const GDScript *gds = _script;
  563. const Map<StringName,GDFunction>::Element *E=NULL;
  564. while (gds->base.ptr()) {
  565. gds=gds->base.ptr();
  566. E=gds->member_functions.find(*methodname);
  567. if (E)
  568. break;
  569. }
  570. Variant::CallError err;
  571. if (E) {
  572. *dst=((GDFunction*)&E->get())->call(p_instance,(const Variant**)argptrs,argc,err);
  573. } else if (gds->native.ptr()) {
  574. if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
  575. MethodBind *mb = ObjectTypeDB::get_method(gds->native->get_name(),*methodname);
  576. if (!mb) {
  577. err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  578. } else {
  579. *dst=mb->call(p_instance->owner,(const Variant**)argptrs,argc,err);
  580. }
  581. } else {
  582. err.error=Variant::CallError::CALL_OK;
  583. }
  584. } else {
  585. if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
  586. err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  587. } else {
  588. err.error=Variant::CallError::CALL_OK;
  589. }
  590. }
  591. if (err.error!=Variant::CallError::CALL_OK) {
  592. String methodstr = *methodname;
  593. err_text=_get_call_error(err,"function '"+methodstr+"'",(const Variant**)argptrs);
  594. break;
  595. }
  596. ip+=4+argc;
  597. } continue;
  598. case OPCODE_YIELD:
  599. case OPCODE_YIELD_SIGNAL: {
  600. int ipofs=1;
  601. if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) {
  602. CHECK_SPACE(4);
  603. ipofs+=2;
  604. } else {
  605. CHECK_SPACE(2);
  606. }
  607. Ref<GDFunctionState> gdfs = memnew( GDFunctionState );
  608. gdfs->function=this;
  609. gdfs->state.stack.resize(alloca_size);
  610. //copy variant stack
  611. for(int i=0;i<_stack_size;i++) {
  612. memnew_placement(&gdfs->state.stack[sizeof(Variant)*i],Variant(stack[i]));
  613. }
  614. gdfs->state.stack_size=_stack_size;
  615. gdfs->state.self=self;
  616. gdfs->state.alloca_size=alloca_size;
  617. gdfs->state._class=_class;
  618. gdfs->state.ip=ip+ipofs;
  619. gdfs->state.line=line;
  620. //gdfs->state.result_pos=ip+ipofs-1;
  621. gdfs->state.defarg=defarg;
  622. gdfs->state.instance=p_instance;
  623. gdfs->function=this;
  624. retvalue=gdfs;
  625. if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) {
  626. GET_VARIANT_PTR(argobj,1);
  627. GET_VARIANT_PTR(argname,2);
  628. //do the oneshot connect
  629. if (argobj->get_type()!=Variant::OBJECT) {
  630. err_text="First argument of yield() not of type object.";
  631. break;
  632. }
  633. if (argname->get_type()!=Variant::STRING) {
  634. err_text="Second argument of yield() not a string (for signal name).";
  635. break;
  636. }
  637. Object *obj=argobj->operator Object *();
  638. String signal = argname->operator String();
  639. #ifdef DEBUG_ENABLED
  640. if (!obj) {
  641. err_text="First argument of yield() is null.";
  642. break;
  643. }
  644. if (ScriptDebugger::get_singleton()) {
  645. if (!ObjectDB::instance_validate(obj)) {
  646. err_text="First argument of yield() is a previously freed instance.";
  647. break;
  648. }
  649. }
  650. if (signal.length()==0) {
  651. err_text="Second argument of yield() is an empty string (for signal name).";
  652. break;
  653. }
  654. #endif
  655. Error err = obj->connect(signal,gdfs.ptr(),"_signal_callback",varray(gdfs),Object::CONNECT_ONESHOT);
  656. if (err!=OK) {
  657. err_text="Error connecting to signal: "+signal+" during yield().";
  658. break;
  659. }
  660. }
  661. exit_ok=true;
  662. } break;
  663. case OPCODE_YIELD_RESUME: {
  664. CHECK_SPACE(2);
  665. if (!p_state) {
  666. err_text=("Invalid Resume (bug?)");
  667. break;
  668. }
  669. GET_VARIANT_PTR(result,1);
  670. *result=p_state->result;
  671. ip+=2;
  672. } continue;
  673. case OPCODE_JUMP: {
  674. CHECK_SPACE(2);
  675. int to = _code_ptr[ip+1];
  676. ERR_BREAK(to<0 || to>_code_size);
  677. ip=to;
  678. } continue;
  679. case OPCODE_JUMP_IF: {
  680. CHECK_SPACE(3);
  681. GET_VARIANT_PTR(test,1);
  682. bool valid;
  683. bool result = test->booleanize(valid);
  684. #ifdef DEBUG_ENABLED
  685. if (!valid) {
  686. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  687. break;
  688. }
  689. #endif
  690. if (result) {
  691. int to = _code_ptr[ip+2];
  692. ERR_BREAK(to<0 || to>_code_size);
  693. ip=to;
  694. continue;
  695. }
  696. ip+=3;
  697. } continue;
  698. case OPCODE_JUMP_IF_NOT: {
  699. CHECK_SPACE(3);
  700. GET_VARIANT_PTR(test,1);
  701. bool valid;
  702. bool result = test->booleanize(valid);
  703. #ifdef DEBUG_ENABLED
  704. if (!valid) {
  705. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  706. break;
  707. }
  708. #endif
  709. if (!result) {
  710. int to = _code_ptr[ip+2];
  711. ERR_BREAK(to<0 || to>_code_size);
  712. ip=to;
  713. continue;
  714. }
  715. ip+=3;
  716. } continue;
  717. case OPCODE_JUMP_TO_DEF_ARGUMENT: {
  718. CHECK_SPACE(2);
  719. ip=_default_arg_ptr[defarg];
  720. } continue;
  721. case OPCODE_RETURN: {
  722. CHECK_SPACE(2);
  723. GET_VARIANT_PTR(r,1);
  724. retvalue=*r;
  725. exit_ok=true;
  726. } break;
  727. case OPCODE_ITERATE_BEGIN: {
  728. CHECK_SPACE(8); //space for this an regular iterate
  729. GET_VARIANT_PTR(counter,1);
  730. GET_VARIANT_PTR(container,2);
  731. bool valid;
  732. if (!container->iter_init(*counter,valid)) {
  733. if (!valid) {
  734. err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"'.";
  735. break;
  736. }
  737. int jumpto=_code_ptr[ip+3];
  738. ERR_BREAK(jumpto<0 || jumpto>_code_size);
  739. ip=jumpto;
  740. continue;
  741. }
  742. GET_VARIANT_PTR(iterator,4);
  743. *iterator=container->iter_get(*counter,valid);
  744. if (!valid) {
  745. err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"'.";
  746. break;
  747. }
  748. ip+=5; //skip regular iterate which is always next
  749. } continue;
  750. case OPCODE_ITERATE: {
  751. CHECK_SPACE(4);
  752. GET_VARIANT_PTR(counter,1);
  753. GET_VARIANT_PTR(container,2);
  754. bool valid;
  755. if (!container->iter_next(*counter,valid)) {
  756. if (!valid) {
  757. err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"' (type changed since first iteration?).";
  758. break;
  759. }
  760. int jumpto=_code_ptr[ip+3];
  761. ERR_BREAK(jumpto<0 || jumpto>_code_size);
  762. ip=jumpto;
  763. continue;
  764. }
  765. GET_VARIANT_PTR(iterator,4);
  766. *iterator=container->iter_get(*counter,valid);
  767. if (!valid) {
  768. err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"' (but was obtained on first iteration?).";
  769. break;
  770. }
  771. ip+=5; //loop again
  772. } continue;
  773. case OPCODE_ASSERT: {
  774. CHECK_SPACE(2);
  775. GET_VARIANT_PTR(test,1);
  776. #ifdef DEBUG_ENABLED
  777. bool valid;
  778. bool result = test->booleanize(valid);
  779. if (!valid) {
  780. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  781. break;
  782. }
  783. if (!result) {
  784. err_text="Assertion failed.";
  785. break;
  786. }
  787. #endif
  788. ip+=2;
  789. } continue;
  790. case OPCODE_BREAKPOINT: {
  791. #ifdef DEBUG_ENABLED
  792. if (ScriptDebugger::get_singleton()) {
  793. GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement",true);
  794. }
  795. #endif
  796. ip+=1;
  797. } continue;
  798. case OPCODE_LINE: {
  799. CHECK_SPACE(2);
  800. line=_code_ptr[ip+1];
  801. ip+=2;
  802. if (ScriptDebugger::get_singleton()) {
  803. // line
  804. bool do_break=false;
  805. if (ScriptDebugger::get_singleton()->get_lines_left()>0) {
  806. if (ScriptDebugger::get_singleton()->get_depth()<=0)
  807. ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 );
  808. if (ScriptDebugger::get_singleton()->get_lines_left()<=0)
  809. do_break=true;
  810. }
  811. if (ScriptDebugger::get_singleton()->is_breakpoint(line,source))
  812. do_break=true;
  813. if (do_break) {
  814. GDScriptLanguage::get_singleton()->debug_break("Breakpoint",true);
  815. }
  816. ScriptDebugger::get_singleton()->line_poll();
  817. }
  818. } continue;
  819. case OPCODE_END: {
  820. exit_ok=true;
  821. break;
  822. } break;
  823. default: {
  824. err_text="Illegal opcode "+itos(_code_ptr[ip])+" at address "+itos(ip);
  825. } break;
  826. }
  827. if (exit_ok)
  828. break;
  829. //error
  830. // function, file, line, error, explanation
  831. String err_file;
  832. if (p_instance)
  833. err_file=p_instance->script->path;
  834. else if (_class)
  835. err_file=_class->path;
  836. if (err_file=="")
  837. err_file="<built-in>";
  838. String err_func = name;
  839. if (p_instance && p_instance->script->name!="")
  840. err_func=p_instance->script->name+"."+err_func;
  841. int err_line=line;
  842. if (err_text=="") {
  843. err_text="Internal Script Error! - opcode #"+itos(last_opcode)+" (report please).";
  844. }
  845. if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) {
  846. // debugger break did not happen
  847. _err_print_error(err_func.utf8().get_data(),err_file.utf8().get_data(),err_line,err_text.utf8().get_data());
  848. }
  849. break;
  850. }
  851. if (ScriptDebugger::get_singleton())
  852. GDScriptLanguage::get_singleton()->exit_function();
  853. if (_stack_size) {
  854. //free stack
  855. for(int i=0;i<_stack_size;i++)
  856. stack[i].~Variant();
  857. }
  858. return retvalue;
  859. }
  860. const int* GDFunction::get_code() const {
  861. return _code_ptr;
  862. }
  863. int GDFunction::get_code_size() const{
  864. return _code_size;
  865. }
  866. Variant GDFunction::get_constant(int p_idx) const {
  867. ERR_FAIL_INDEX_V(p_idx,constants.size(),"<errconst>");
  868. return constants[p_idx];
  869. }
  870. StringName GDFunction::get_global_name(int p_idx) const {
  871. ERR_FAIL_INDEX_V(p_idx,global_names.size(),"<errgname>");
  872. return global_names[p_idx];
  873. }
  874. int GDFunction::get_default_argument_count() const {
  875. return default_arguments.size();
  876. }
  877. int GDFunction::get_default_argument_addr(int p_arg) const{
  878. ERR_FAIL_INDEX_V(p_arg,default_arguments.size(),-1);
  879. return default_arguments[p_arg];
  880. }
  881. StringName GDFunction::get_name() const {
  882. return name;
  883. }
  884. int GDFunction::get_max_stack_size() const {
  885. return _stack_size;
  886. }
  887. struct _GDFKC {
  888. int order;
  889. List<int> pos;
  890. };
  891. struct _GDFKCS {
  892. int order;
  893. StringName id;
  894. int pos;
  895. bool operator<(const _GDFKCS &p_r) const {
  896. return order<p_r.order;
  897. }
  898. };
  899. void GDFunction::debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const {
  900. int oc=0;
  901. Map<StringName,_GDFKC> sdmap;
  902. for( const List<StackDebug>::Element *E=stack_debug.front();E;E=E->next()) {
  903. const StackDebug &sd=E->get();
  904. if (sd.line>p_line)
  905. break;
  906. if (sd.added) {
  907. if (!sdmap.has(sd.identifier)) {
  908. _GDFKC d;
  909. d.order=oc++;
  910. d.pos.push_back(sd.pos);
  911. sdmap[sd.identifier]=d;
  912. } else {
  913. sdmap[sd.identifier].pos.push_back(sd.pos);
  914. }
  915. } else {
  916. ERR_CONTINUE(!sdmap.has(sd.identifier));
  917. sdmap[sd.identifier].pos.pop_back();
  918. if (sdmap[sd.identifier].pos.empty())
  919. sdmap.erase(sd.identifier);
  920. }
  921. }
  922. List<_GDFKCS> stackpositions;
  923. for(Map<StringName,_GDFKC>::Element *E=sdmap.front();E;E=E->next() ) {
  924. _GDFKCS spp;
  925. spp.id=E->key();
  926. spp.order=E->get().order;
  927. spp.pos=E->get().pos.back()->get();
  928. stackpositions.push_back(spp);
  929. }
  930. stackpositions.sort();
  931. for(List<_GDFKCS>::Element *E=stackpositions.front();E;E=E->next()) {
  932. Pair<StringName,int> p;
  933. p.first=E->get().id;
  934. p.second=E->get().pos;
  935. r_stackvars->push_back(p);
  936. }
  937. }
  938. #if 0
  939. void GDFunction::clear() {
  940. name=StringName();
  941. constants.clear();
  942. _stack_size=0;
  943. code.clear();
  944. _constants_ptr=NULL;
  945. _constant_count=0;
  946. _global_names_ptr=NULL;
  947. _global_names_count=0;
  948. _code_ptr=NULL;
  949. _code_size=0;
  950. }
  951. #endif
  952. GDFunction::GDFunction() {
  953. _stack_size=0;
  954. _call_size=0;
  955. name="<anonymous>";
  956. #ifdef DEBUG_ENABLED
  957. _func_cname=NULL;
  958. #endif
  959. }
  960. /////////////////////
  961. Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
  962. Variant arg;
  963. r_error.error=Variant::CallError::CALL_OK;
  964. ERR_FAIL_COND_V(!function,Variant());
  965. if (p_argcount==0) {
  966. r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  967. r_error.argument=1;
  968. return Variant();
  969. } else if (p_argcount==1) {
  970. //noooneee
  971. } else if (p_argcount==2) {
  972. arg=*p_args[0];
  973. } else {
  974. Array extra_args;
  975. for(int i=0;i<p_argcount-1;i++) {
  976. extra_args.push_back(*p_args[i]);
  977. }
  978. arg=extra_args;
  979. }
  980. Ref<GDFunctionState> self = *p_args[p_argcount-1];
  981. if (self.is_null()) {
  982. r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
  983. r_error.argument=p_argcount-1;
  984. r_error.expected=Variant::OBJECT;
  985. return Variant();
  986. }
  987. state.result=arg;
  988. Variant ret = function->call(NULL,NULL,0,r_error,&state);
  989. function=NULL; //cleaned up;
  990. state.result=Variant();
  991. return ret;
  992. }
  993. bool GDFunctionState::is_valid() const {
  994. return function!=NULL;
  995. }
  996. Variant GDFunctionState::resume(const Variant& p_arg) {
  997. ERR_FAIL_COND_V(!function,Variant());
  998. state.result=p_arg;
  999. Variant::CallError err;
  1000. Variant ret = function->call(NULL,NULL,0,err,&state);
  1001. function=NULL; //cleaned up;
  1002. state.result=Variant();
  1003. return ret;
  1004. }
  1005. void GDFunctionState::_bind_methods() {
  1006. ObjectTypeDB::bind_method(_MD("resume:Variant","arg"),&GDFunctionState::resume,DEFVAL(Variant()));
  1007. ObjectTypeDB::bind_method(_MD("is_valid"),&GDFunctionState::is_valid);
  1008. ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"_signal_callback",&GDFunctionState::_signal_callback,MethodInfo("_signal_callback"));
  1009. }
  1010. GDFunctionState::GDFunctionState() {
  1011. function=NULL;
  1012. }
  1013. GDFunctionState::~GDFunctionState() {
  1014. if (function!=NULL) {
  1015. //never called, deinitialize stack
  1016. for(int i=0;i<state.stack_size;i++) {
  1017. Variant *v=(Variant*)&state.stack[sizeof(Variant)*i];
  1018. v->~Variant();
  1019. }
  1020. }
  1021. }
  1022. ///////////////////////////
  1023. GDNativeClass::GDNativeClass(const StringName& p_name) {
  1024. name=p_name;
  1025. }
  1026. /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){
  1027. }*/
  1028. bool GDNativeClass::_get(const StringName& p_name,Variant &r_ret) const {
  1029. bool ok;
  1030. int v = ObjectTypeDB::get_integer_constant(name, p_name, &ok);
  1031. if (ok) {
  1032. r_ret=v;
  1033. return true;
  1034. } else {
  1035. return false;
  1036. }
  1037. }
  1038. void GDNativeClass::_bind_methods() {
  1039. ObjectTypeDB::bind_method(_MD("new"),&GDNativeClass::_new);
  1040. }
  1041. Variant GDNativeClass::_new() {
  1042. Object *o = instance();
  1043. if (!o) {
  1044. ERR_EXPLAIN("Class type: '"+String(name)+"' is not instantiable.");
  1045. ERR_FAIL_COND_V(!o,Variant());
  1046. }
  1047. Reference *ref = o->cast_to<Reference>();
  1048. if (ref) {
  1049. return REF(ref);
  1050. } else {
  1051. return o;
  1052. }
  1053. }
  1054. Object *GDNativeClass::instance() {
  1055. return ObjectTypeDB::instance(name);
  1056. }
  1057. GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError& r_error) {
  1058. /* STEP 1, CREATE */
  1059. GDInstance* instance = memnew( GDInstance );
  1060. instance->base_ref=p_isref;
  1061. instance->members.resize(member_indices.size());
  1062. instance->script=Ref<GDScript>(this);
  1063. instance->owner=p_owner;
  1064. instance->owner->set_script_instance(instance);
  1065. /* STEP 2, INITIALIZE AND CONSRTUCT */
  1066. instances.insert(instance->owner);
  1067. initializer->call(instance,p_args,p_argcount,r_error);
  1068. if (r_error.error!=Variant::CallError::CALL_OK) {
  1069. instance->script=Ref<GDScript>();
  1070. instance->owner->set_script_instance(NULL);
  1071. instances.erase(p_owner);
  1072. ERR_FAIL_COND_V(r_error.error!=Variant::CallError::CALL_OK, NULL); //error constructing
  1073. }
  1074. //@TODO make thread safe
  1075. return instance;
  1076. }
  1077. Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) {
  1078. /* STEP 1, CREATE */
  1079. r_error.error=Variant::CallError::CALL_OK;
  1080. REF ref;
  1081. Object *owner=NULL;
  1082. GDScript *_baseptr=this;
  1083. while (_baseptr->_base) {
  1084. _baseptr=_baseptr->_base;
  1085. }
  1086. if (_baseptr->native.ptr()) {
  1087. owner=_baseptr->native->instance();
  1088. } else {
  1089. owner=memnew( Reference ); //by default, no base means use reference
  1090. }
  1091. Reference *r=owner->cast_to<Reference>();
  1092. if (r) {
  1093. ref=REF(r);
  1094. }
  1095. GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL,r_error);
  1096. if (!instance) {
  1097. if (ref.is_null()) {
  1098. memdelete(owner); //no owner, sorry
  1099. }
  1100. return Variant();
  1101. }
  1102. if (ref.is_valid()) {
  1103. return ref;
  1104. } else {
  1105. return owner;
  1106. }
  1107. }
  1108. bool GDScript::can_instance() const {
  1109. //return valid; //any script in GDscript can instance
  1110. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  1111. }
  1112. StringName GDScript::get_instance_base_type() const {
  1113. if (native.is_valid())
  1114. return native->get_name();
  1115. if (base.is_valid())
  1116. return base->get_instance_base_type();
  1117. return StringName();
  1118. }
  1119. struct _GDScriptMemberSort {
  1120. int index;
  1121. StringName name;
  1122. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; }
  1123. };
  1124. #ifdef TOOLS_ENABLED
  1125. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1126. placeholders.erase(p_placeholder);
  1127. }
  1128. /*
  1129. void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
  1130. List<PropertyInfo> plist;
  1131. GDScript *scr=this;
  1132. Map<StringName,Variant> default_values;
  1133. while(scr) {
  1134. Vector<_GDScriptMemberSort> msort;
  1135. for(Map<StringName,PropertyInfo>::Element *E=scr->member_info.front();E;E=E->next()) {
  1136. _GDScriptMemberSort ms;
  1137. ERR_CONTINUE(!scr->member_indices.has(E->key()));
  1138. ms.index=scr->member_indices[E->key()].index;
  1139. ms.name=E->key();
  1140. msort.push_back(ms);
  1141. }
  1142. msort.sort();
  1143. msort.invert();
  1144. for(int i=0;i<msort.size();i++) {
  1145. plist.push_front(scr->member_info[msort[i].name]);
  1146. if (scr->member_default_values.has(msort[i].name))
  1147. default_values[msort[i].name]=scr->member_default_values[msort[i].name];
  1148. else {
  1149. Variant::CallError err;
  1150. default_values[msort[i].name]=Variant::construct(scr->member_info[msort[i].name].type,NULL,0,err);
  1151. }
  1152. }
  1153. scr=scr->_base;
  1154. }
  1155. p_placeholder->update(plist,default_values);
  1156. }*/
  1157. #endif
  1158. bool GDScript::get_property_default_value(const StringName& p_property, Variant &r_value) const {
  1159. #ifdef TOOLS_ENABLED
  1160. //for (const Map<StringName,Variant>::Element *I=member_default_values.front();I;I=I->next()) {
  1161. // print_line("\t"+String(String(I->key())+":"+String(I->get())));
  1162. //}
  1163. const Map<StringName,Variant>::Element *E=member_default_values_cache.find(p_property);
  1164. if (E) {
  1165. r_value=E->get();
  1166. return true;
  1167. }
  1168. if (base_cache.is_valid()) {
  1169. return base_cache->get_property_default_value(p_property,r_value);
  1170. }
  1171. #endif
  1172. return false;
  1173. }
  1174. ScriptInstance* GDScript::instance_create(Object *p_this) {
  1175. if (!tool && !ScriptServer::is_scripting_enabled()) {
  1176. #ifdef TOOLS_ENABLED
  1177. //instance a fake script for editing the values
  1178. //plist.invert();
  1179. /*print_line("CREATING PLACEHOLDER");
  1180. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  1181. print_line(E->get().name);
  1182. }*/
  1183. PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) );
  1184. placeholders.insert(si);
  1185. //_update_placeholder(si);
  1186. _update_exports();
  1187. return si;
  1188. #else
  1189. return NULL;
  1190. #endif
  1191. }
  1192. GDScript *top=this;
  1193. while(top->_base)
  1194. top=top->_base;
  1195. if (top->native.is_valid()) {
  1196. if (!ObjectTypeDB::is_type(p_this->get_type_name(),top->native->get_name())) {
  1197. if (ScriptDebugger::get_singleton()) {
  1198. 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()+"'");
  1199. }
  1200. 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()+"'");
  1201. ERR_FAIL_V(NULL);
  1202. }
  1203. }
  1204. Variant::CallError unchecked_error;
  1205. return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>(),unchecked_error);
  1206. }
  1207. bool GDScript::instance_has(const Object *p_this) const {
  1208. return instances.has((Object*)p_this);
  1209. }
  1210. bool GDScript::has_source_code() const {
  1211. return source!="";
  1212. }
  1213. String GDScript::get_source_code() const {
  1214. return source;
  1215. }
  1216. void GDScript::set_source_code(const String& p_code) {
  1217. if (source==p_code)
  1218. return;
  1219. source=p_code;
  1220. #ifdef TOOLS_ENABLED
  1221. source_changed_cache=true;
  1222. //print_line("SC CHANGED "+get_path());
  1223. #endif
  1224. }
  1225. #ifdef TOOLS_ENABLED
  1226. void GDScript::_update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames) {
  1227. if (base_cache.is_valid()) {
  1228. base_cache->_update_exports_values(values,propnames);
  1229. }
  1230. for(Map<StringName,Variant>::Element *E=member_default_values_cache.front();E;E=E->next()) {
  1231. values[E->key()]=E->get();
  1232. }
  1233. for (List<PropertyInfo>::Element *E=members_cache.front();E;E=E->next()) {
  1234. propnames.push_back(E->get());
  1235. }
  1236. }
  1237. #endif
  1238. bool GDScript::_update_exports() {
  1239. #ifdef TOOLS_ENABLED
  1240. bool changed=false;
  1241. if (source_changed_cache) {
  1242. //print_line("updating source for "+get_path());
  1243. source_changed_cache=false;
  1244. changed=true;
  1245. String basedir=path;
  1246. if (basedir=="")
  1247. basedir=get_path();
  1248. if (basedir!="")
  1249. basedir=basedir.get_base_dir();
  1250. GDParser parser;
  1251. Error err = parser.parse(source,basedir,true,path);
  1252. if (err==OK) {
  1253. const GDParser::Node* root = parser.get_parse_tree();
  1254. ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false);
  1255. const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode*>(root);
  1256. if (base_cache.is_valid()) {
  1257. base_cache->inheriters_cache.erase(get_instance_ID());
  1258. base_cache=Ref<GDScript>();
  1259. }
  1260. if (c->extends_used && String(c->extends_file)!="" && String(c->extends_file) != get_path()) {
  1261. String path = c->extends_file;
  1262. if (path.is_rel_path()) {
  1263. String base = get_path();
  1264. if (base=="" || base.is_rel_path()) {
  1265. ERR_PRINT(("Could not resolve relative path for parent class: "+path).utf8().get_data());
  1266. } else {
  1267. path=base.get_base_dir().plus_file(path);
  1268. }
  1269. }
  1270. if (path!=get_path()) {
  1271. Ref<GDScript> bf = ResourceLoader::load(path);
  1272. if (bf.is_valid()) {
  1273. //print_line("parent is: "+bf->get_path());
  1274. base_cache=bf;
  1275. bf->inheriters_cache.insert(get_instance_ID());
  1276. //bf->_update_exports(p_instances,true,false);
  1277. }
  1278. } else {
  1279. ERR_PRINT(("Path extending itself in "+path).utf8().get_data());
  1280. }
  1281. }
  1282. members_cache.clear();;
  1283. member_default_values_cache.clear();
  1284. for(int i=0;i<c->variables.size();i++) {
  1285. if (c->variables[i]._export.type==Variant::NIL)
  1286. continue;
  1287. members_cache.push_back(c->variables[i]._export);
  1288. //print_line("found "+c->variables[i]._export.name);
  1289. member_default_values_cache[c->variables[i].identifier]=c->variables[i].default_value;
  1290. }
  1291. _signals.clear();
  1292. for(int i=0;i<c->_signals.size();i++) {
  1293. _signals[c->_signals[i].name]=c->_signals[i].arguments;
  1294. }
  1295. }
  1296. } else {
  1297. //print_line("unchaged is "+get_path());
  1298. }
  1299. if (base_cache.is_valid()) {
  1300. if (base_cache->_update_exports()) {
  1301. changed = true;
  1302. }
  1303. }
  1304. if (/*changed &&*/ placeholders.size()) { //hm :(
  1305. //print_line("updating placeholders for "+get_path());
  1306. //update placeholders if any
  1307. Map<StringName,Variant> values;
  1308. List<PropertyInfo> propnames;
  1309. _update_exports_values(values,propnames);
  1310. for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  1311. E->get()->update(propnames,values);
  1312. }
  1313. }
  1314. return changed;
  1315. #endif
  1316. return false;
  1317. }
  1318. void GDScript::update_exports() {
  1319. #ifdef TOOLS_ENABLED
  1320. _update_exports();
  1321. Set<ObjectID> copy=inheriters_cache; //might get modified
  1322. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  1323. for(Set<ObjectID>::Element *E=copy.front();E;E=E->next()) {
  1324. Object *id=ObjectDB::get_instance(E->get());
  1325. if (!id)
  1326. continue;
  1327. GDScript *s=id->cast_to<GDScript>();
  1328. if (!s)
  1329. continue;
  1330. s->update_exports();
  1331. }
  1332. #endif
  1333. }
  1334. void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) {
  1335. p_sc->path=p_path;
  1336. for(Map<StringName,Ref<GDScript> >::Element *E=p_sc->subclasses.front();E;E=E->next()) {
  1337. _set_subclass_path(E->get(),p_path);
  1338. }
  1339. }
  1340. Error GDScript::reload() {
  1341. ERR_FAIL_COND_V(instances.size(),ERR_ALREADY_IN_USE);
  1342. String basedir=path;
  1343. if (basedir=="")
  1344. basedir=get_path();
  1345. if (basedir!="")
  1346. basedir=basedir.get_base_dir();
  1347. valid=false;
  1348. GDParser parser;
  1349. Error err = parser.parse(source,basedir,false,path);
  1350. if (err) {
  1351. if (ScriptDebugger::get_singleton()) {
  1352. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),parser.get_error_line(),"Parser Error: "+parser.get_error());
  1353. }
  1354. _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());
  1355. ERR_FAIL_V(ERR_PARSE_ERROR);
  1356. }
  1357. GDCompiler compiler;
  1358. err = compiler.compile(&parser,this);
  1359. if (err) {
  1360. if (ScriptDebugger::get_singleton()) {
  1361. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error());
  1362. }
  1363. _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());
  1364. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  1365. }
  1366. valid=true;
  1367. for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
  1368. _set_subclass_path(E->get(),path);
  1369. }
  1370. #ifdef TOOLS_ENABLED
  1371. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  1372. _update_placeholder(E->get());
  1373. }*/
  1374. #endif
  1375. return OK;
  1376. }
  1377. String GDScript::get_node_type() const {
  1378. return ""; // ?
  1379. }
  1380. ScriptLanguage *GDScript::get_language() const {
  1381. return GDScriptLanguage::get_singleton();
  1382. }
  1383. Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1384. GDScript *top=this;
  1385. while(top) {
  1386. Map<StringName,GDFunction>::Element *E=top->member_functions.find(p_method);
  1387. if (E) {
  1388. if (!E->get().is_static()) {
  1389. WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data());
  1390. }
  1391. return E->get().call(NULL,p_args,p_argcount,r_error);
  1392. }
  1393. top=top->_base;
  1394. }
  1395. //none found, regular
  1396. return Script::call(p_method,p_args,p_argcount,r_error);
  1397. }
  1398. bool GDScript::_get(const StringName& p_name,Variant &r_ret) const {
  1399. {
  1400. const GDScript *top=this;
  1401. while(top) {
  1402. {
  1403. const Map<StringName,Variant>::Element *E=top->constants.find(p_name);
  1404. if (E) {
  1405. r_ret= E->get();
  1406. return true;
  1407. }
  1408. }
  1409. {
  1410. const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name);
  1411. if (E) {
  1412. r_ret=E->get();
  1413. return true;
  1414. }
  1415. }
  1416. top=top->_base;
  1417. }
  1418. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1419. r_ret=get_source_code();
  1420. return true;
  1421. }
  1422. }
  1423. return false;
  1424. }
  1425. bool GDScript::_set(const StringName& p_name, const Variant& p_value) {
  1426. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1427. set_source_code(p_value);
  1428. reload();
  1429. } else
  1430. return false;
  1431. return true;
  1432. }
  1433. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1434. p_properties->push_back( PropertyInfo(Variant::STRING,"script/source",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
  1435. }
  1436. void GDScript::_bind_methods() {
  1437. ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo("new"));
  1438. ObjectTypeDB::bind_method(_MD("get_as_byte_code"),&GDScript::get_as_byte_code);
  1439. }
  1440. Vector<uint8_t> GDScript::get_as_byte_code() const {
  1441. GDTokenizerBuffer tokenizer;
  1442. return tokenizer.parse_code_string(source);
  1443. };
  1444. Error GDScript::load_byte_code(const String& p_path) {
  1445. Vector<uint8_t> bytecode;
  1446. if (p_path.ends_with("gde")) {
  1447. FileAccess *fa = FileAccess::open(p_path,FileAccess::READ);
  1448. ERR_FAIL_COND_V(!fa,ERR_CANT_OPEN);
  1449. FileAccessEncrypted *fae = memnew( FileAccessEncrypted );
  1450. ERR_FAIL_COND_V(!fae,ERR_CANT_OPEN);
  1451. Vector<uint8_t> key;
  1452. key.resize(32);
  1453. for(int i=0;i<key.size();i++) {
  1454. key[i]=script_encryption_key[i];
  1455. }
  1456. Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_READ);
  1457. ERR_FAIL_COND_V(err,err);
  1458. bytecode.resize(fae->get_len());
  1459. fae->get_buffer(bytecode.ptr(),bytecode.size());
  1460. memdelete(fae);
  1461. } else {
  1462. bytecode = FileAccess::get_file_as_array(p_path);
  1463. }
  1464. ERR_FAIL_COND_V(bytecode.size()==0,ERR_PARSE_ERROR);
  1465. path=p_path;
  1466. String basedir=path;
  1467. if (basedir=="")
  1468. basedir=get_path();
  1469. if (basedir!="")
  1470. basedir=basedir.get_base_dir();
  1471. valid=false;
  1472. GDParser parser;
  1473. Error err = parser.parse_bytecode(bytecode,basedir,get_path());
  1474. if (err) {
  1475. _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());
  1476. ERR_FAIL_V(ERR_PARSE_ERROR);
  1477. }
  1478. GDCompiler compiler;
  1479. err = compiler.compile(&parser,this);
  1480. if (err) {
  1481. _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());
  1482. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  1483. }
  1484. valid=true;
  1485. for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
  1486. _set_subclass_path(E->get(),path);
  1487. }
  1488. return OK;
  1489. }
  1490. Error GDScript::load_source_code(const String& p_path) {
  1491. DVector<uint8_t> sourcef;
  1492. Error err;
  1493. FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err);
  1494. if (err) {
  1495. ERR_FAIL_COND_V(err,err);
  1496. }
  1497. int len = f->get_len();
  1498. sourcef.resize(len+1);
  1499. DVector<uint8_t>::Write w = sourcef.write();
  1500. int r = f->get_buffer(w.ptr(),len);
  1501. f->close();
  1502. memdelete(f);
  1503. ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN);
  1504. w[len]=0;
  1505. String s;
  1506. if (s.parse_utf8((const char*)w.ptr())) {
  1507. 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.");
  1508. ERR_FAIL_V(ERR_INVALID_DATA);
  1509. }
  1510. source=s;
  1511. #ifdef TOOLS_ENABLED
  1512. source_changed_cache=true;
  1513. #endif
  1514. //print_line("LSC :"+get_path());
  1515. path=p_path;
  1516. return OK;
  1517. }
  1518. const Map<StringName,GDFunction>& GDScript::debug_get_member_functions() const {
  1519. return member_functions;
  1520. }
  1521. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  1522. for(const Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) {
  1523. if (E->get().index==p_idx)
  1524. return E->key();
  1525. }
  1526. return "<error>";
  1527. }
  1528. Ref<GDScript> GDScript::get_base() const {
  1529. return base;
  1530. }
  1531. bool GDScript::has_script_signal(const StringName& p_signal) const {
  1532. if (_signals.has(p_signal))
  1533. return true;
  1534. if (base.is_valid()) {
  1535. return base->has_script_signal(p_signal);
  1536. }
  1537. #ifdef TOOLS_ENABLED
  1538. else if (base_cache.is_valid()){
  1539. return base_cache->has_script_signal(p_signal);
  1540. }
  1541. #endif
  1542. return false;
  1543. }
  1544. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  1545. for(const Map<StringName,Vector<StringName> >::Element *E=_signals.front();E;E=E->next()) {
  1546. MethodInfo mi;
  1547. mi.name=E->key();
  1548. for(int i=0;i<E->get().size();i++) {
  1549. PropertyInfo arg;
  1550. arg.name=E->get()[i];
  1551. mi.arguments.push_back(arg);
  1552. }
  1553. r_signals->push_back(mi);
  1554. }
  1555. if (base.is_valid()) {
  1556. base->get_script_signal_list(r_signals);
  1557. }
  1558. #ifdef TOOLS_ENABLED
  1559. else if (base_cache.is_valid()){
  1560. base_cache->get_script_signal_list(r_signals);
  1561. }
  1562. #endif
  1563. }
  1564. GDScript::GDScript() {
  1565. _static_ref=this;
  1566. valid=false;
  1567. subclass_count=0;
  1568. initializer=NULL;
  1569. _base=NULL;
  1570. _owner=NULL;
  1571. tool=false;
  1572. #ifdef TOOLS_ENABLED
  1573. source_changed_cache=false;
  1574. #endif
  1575. }
  1576. //////////////////////////////
  1577. // INSTANCE //
  1578. //////////////////////////////
  1579. bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
  1580. //member
  1581. {
  1582. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  1583. if (E) {
  1584. if (E->get().setter) {
  1585. const Variant *val=&p_value;
  1586. Variant::CallError err;
  1587. call(E->get().setter,&val,1,err);
  1588. if (err.error==Variant::CallError::CALL_OK) {
  1589. return true; //function exists, call was successful
  1590. }
  1591. }
  1592. else
  1593. members[E->get().index] = p_value;
  1594. return true;
  1595. }
  1596. }
  1597. GDScript *sptr=script.ptr();
  1598. while(sptr) {
  1599. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  1600. if (E) {
  1601. Variant name=p_name;
  1602. const Variant *args[2]={&name,&p_value};
  1603. Variant::CallError err;
  1604. Variant ret = E->get().call(this,(const Variant**)args,2,err);
  1605. if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool())
  1606. return true;
  1607. }
  1608. sptr = sptr->_base;
  1609. }
  1610. return false;
  1611. }
  1612. bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
  1613. const GDScript *sptr=script.ptr();
  1614. while(sptr) {
  1615. {
  1616. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  1617. if (E) {
  1618. if (E->get().getter) {
  1619. Variant::CallError err;
  1620. r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err);
  1621. if (err.error==Variant::CallError::CALL_OK) {
  1622. return true;
  1623. }
  1624. }
  1625. r_ret=members[E->get().index];
  1626. return true; //index found
  1627. }
  1628. }
  1629. {
  1630. const Map<StringName,Variant>::Element *E = script->constants.find(p_name);
  1631. if (E) {
  1632. r_ret=E->get();
  1633. return true; //index found
  1634. }
  1635. }
  1636. {
  1637. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  1638. if (E) {
  1639. Variant name=p_name;
  1640. const Variant *args[1]={&name};
  1641. Variant::CallError err;
  1642. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err);
  1643. if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
  1644. r_ret=ret;
  1645. return true;
  1646. }
  1647. }
  1648. }
  1649. sptr = sptr->_base;
  1650. }
  1651. return false;
  1652. }
  1653. Variant::Type GDInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const {
  1654. const GDScript *sptr=script.ptr();
  1655. while(sptr) {
  1656. if (sptr->member_info.has(p_name)) {
  1657. if (r_is_valid)
  1658. *r_is_valid=true;
  1659. return sptr->member_info[p_name].type;
  1660. }
  1661. sptr = sptr->_base;
  1662. }
  1663. if (r_is_valid)
  1664. *r_is_valid=false;
  1665. return Variant::NIL;
  1666. }
  1667. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1668. // exported members, not doen yet!
  1669. const GDScript *sptr=script.ptr();
  1670. List<PropertyInfo> props;
  1671. while(sptr) {
  1672. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  1673. if (E) {
  1674. Variant::CallError err;
  1675. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),NULL,0,err);
  1676. if (err.error==Variant::CallError::CALL_OK) {
  1677. if (ret.get_type()!=Variant::ARRAY) {
  1678. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  1679. ERR_FAIL();
  1680. }
  1681. Array arr = ret;
  1682. for(int i=0;i<arr.size();i++) {
  1683. Dictionary d = arr[i];
  1684. ERR_CONTINUE(!d.has("name"));
  1685. ERR_CONTINUE(!d.has("type"));
  1686. PropertyInfo pinfo;
  1687. pinfo.type = Variant::Type( d["type"].operator int());
  1688. ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX );
  1689. pinfo.name = d["name"];
  1690. ERR_CONTINUE(pinfo.name=="");
  1691. if (d.has("hint"))
  1692. pinfo.hint=PropertyHint(d["hint"].operator int());
  1693. if (d.has("hint_string"))
  1694. pinfo.hint_string=d["hint_string"];
  1695. if (d.has("usage"))
  1696. pinfo.usage=d["usage"];
  1697. props.push_back(pinfo);
  1698. }
  1699. }
  1700. }
  1701. //instance a fake script for editing the values
  1702. Vector<_GDScriptMemberSort> msort;
  1703. for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
  1704. _GDScriptMemberSort ms;
  1705. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  1706. ms.index=sptr->member_indices[E->key()].index;
  1707. ms.name=E->key();
  1708. msort.push_back(ms);
  1709. }
  1710. msort.sort();
  1711. msort.invert();
  1712. for(int i=0;i<msort.size();i++) {
  1713. props.push_front(sptr->member_info[msort[i].name]);
  1714. }
  1715. #if 0
  1716. if (sptr->member_functions.has("_get_property_list")) {
  1717. Variant::CallError err;
  1718. GDFunction *f = const_cast<GDFunction*>(&sptr->member_functions["_get_property_list"]);
  1719. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  1720. if (plv.get_type()!=Variant::ARRAY) {
  1721. ERR_PRINT("_get_property_list: expected array returned");
  1722. } else {
  1723. Array pl=plv;
  1724. for(int i=0;i<pl.size();i++) {
  1725. Dictionary p = pl[i];
  1726. PropertyInfo pinfo;
  1727. if (!p.has("name")) {
  1728. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  1729. continue;
  1730. }
  1731. if (!p.has("type")) {
  1732. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  1733. continue;
  1734. }
  1735. pinfo.name=p["name"];
  1736. pinfo.type=Variant::Type(int(p["type"]));
  1737. if (p.has("hint"))
  1738. pinfo.hint=PropertyHint(int(p["hint"]));
  1739. if (p.has("hint_string"))
  1740. pinfo.hint_string=p["hint_string"];
  1741. if (p.has("usage"))
  1742. pinfo.usage=p["usage"];
  1743. props.push_back(pinfo);
  1744. }
  1745. }
  1746. }
  1747. #endif
  1748. sptr = sptr->_base;
  1749. }
  1750. //props.invert();
  1751. for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  1752. p_properties->push_back(E->get());
  1753. }
  1754. }
  1755. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  1756. const GDScript *sptr=script.ptr();
  1757. while(sptr) {
  1758. for (Map<StringName,GDFunction>::Element *E = sptr->member_functions.front();E;E=E->next()) {
  1759. MethodInfo mi;
  1760. mi.name=E->key();
  1761. for(int i=0;i<E->get().get_argument_count();i++)
  1762. mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
  1763. p_list->push_back(mi);
  1764. }
  1765. sptr = sptr->_base;
  1766. }
  1767. }
  1768. bool GDInstance::has_method(const StringName& p_method) const {
  1769. const GDScript *sptr=script.ptr();
  1770. while(sptr) {
  1771. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1772. if (E)
  1773. return true;
  1774. sptr = sptr->_base;
  1775. }
  1776. return false;
  1777. }
  1778. Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1779. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  1780. GDScript *sptr=script.ptr();
  1781. while(sptr) {
  1782. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1783. if (E) {
  1784. return E->get().call(this,p_args,p_argcount,r_error);
  1785. }
  1786. sptr = sptr->_base;
  1787. }
  1788. r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1789. return Variant();
  1790. }
  1791. void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1792. GDScript *sptr=script.ptr();
  1793. Variant::CallError ce;
  1794. while(sptr) {
  1795. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1796. if (E) {
  1797. E->get().call(this,p_args,p_argcount,ce);
  1798. }
  1799. sptr = sptr->_base;
  1800. }
  1801. }
  1802. void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) {
  1803. if (sptr->_base)
  1804. _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount);
  1805. Variant::CallError ce;
  1806. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1807. if (E) {
  1808. E->get().call(this,p_args,p_argcount,ce);
  1809. }
  1810. }
  1811. void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1812. if (script.ptr()) {
  1813. _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount);
  1814. }
  1815. }
  1816. void GDInstance::notification(int p_notification) {
  1817. //notification is not virutal, it gets called at ALL levels just like in C.
  1818. Variant value=p_notification;
  1819. const Variant *args[1]={&value };
  1820. GDScript *sptr=script.ptr();
  1821. while(sptr) {
  1822. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  1823. if (E) {
  1824. Variant::CallError err;
  1825. E->get().call(this,args,1,err);
  1826. if (err.error!=Variant::CallError::CALL_OK) {
  1827. //print error about notification call
  1828. }
  1829. }
  1830. sptr = sptr->_base;
  1831. }
  1832. }
  1833. Ref<Script> GDInstance::get_script() const {
  1834. return script;
  1835. }
  1836. ScriptLanguage *GDInstance::get_language() {
  1837. return GDScriptLanguage::get_singleton();
  1838. }
  1839. GDInstance::GDInstance() {
  1840. owner=NULL;
  1841. base_ref=false;
  1842. }
  1843. GDInstance::~GDInstance() {
  1844. if (script.is_valid() && owner) {
  1845. script->instances.erase(owner);
  1846. }
  1847. }
  1848. /************* SCRIPT LANGUAGE **************/
  1849. /************* SCRIPT LANGUAGE **************/
  1850. /************* SCRIPT LANGUAGE **************/
  1851. /************* SCRIPT LANGUAGE **************/
  1852. /************* SCRIPT LANGUAGE **************/
  1853. GDScriptLanguage *GDScriptLanguage::singleton=NULL;
  1854. String GDScriptLanguage::get_name() const {
  1855. return "GDScript";
  1856. }
  1857. /* LANGUAGE FUNCTIONS */
  1858. void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) {
  1859. if (globals.has(p_name)) {
  1860. //overwrite existing
  1861. global_array[globals[p_name]]=p_value;
  1862. return;
  1863. }
  1864. globals[p_name]=global_array.size();
  1865. global_array.push_back(p_value);
  1866. _global_array=global_array.ptr();
  1867. }
  1868. void GDScriptLanguage::add_global_constant(const StringName& p_variable,const Variant& p_value) {
  1869. _add_global(p_variable,p_value);
  1870. }
  1871. void GDScriptLanguage::init() {
  1872. //populate global constants
  1873. int gcc=GlobalConstants::get_global_constant_count();
  1874. for(int i=0;i<gcc;i++) {
  1875. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i));
  1876. }
  1877. _add_global(StaticCString::create("PI"),Math_PI);
  1878. //populate native classes
  1879. List<StringName> class_list;
  1880. ObjectTypeDB::get_type_list(&class_list);
  1881. for(List<StringName>::Element *E=class_list.front();E;E=E->next()) {
  1882. StringName n = E->get();
  1883. String s = String(n);
  1884. if (s.begins_with("_"))
  1885. n=s.substr(1,s.length());
  1886. if (globals.has(n))
  1887. continue;
  1888. Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) );
  1889. _add_global(n,nc);
  1890. }
  1891. //populate singletons
  1892. List<Globals::Singleton> singletons;
  1893. Globals::get_singleton()->get_singletons(&singletons);
  1894. for(List<Globals::Singleton>::Element *E=singletons.front();E;E=E->next()) {
  1895. _add_global(E->get().name,E->get().ptr);
  1896. }
  1897. }
  1898. String GDScriptLanguage::get_type() const {
  1899. return "GDScript";
  1900. }
  1901. String GDScriptLanguage::get_extension() const {
  1902. return "gd";
  1903. }
  1904. Error GDScriptLanguage::execute_file(const String& p_path) {
  1905. // ??
  1906. return OK;
  1907. }
  1908. void GDScriptLanguage::finish() {
  1909. }
  1910. void GDScriptLanguage::frame() {
  1911. // print_line("calls: "+itos(calls));
  1912. calls=0;
  1913. }
  1914. /* EDITOR FUNCTIONS */
  1915. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1916. static const char *_reserved_words[]={
  1917. "break",
  1918. "class",
  1919. "continue",
  1920. "const",
  1921. "else",
  1922. "elif",
  1923. "enum",
  1924. "extends" ,
  1925. "onready",
  1926. "for" ,
  1927. "func" ,
  1928. "if" ,
  1929. "in" ,
  1930. "null" ,
  1931. "not" ,
  1932. "return" ,
  1933. "self" ,
  1934. "while" ,
  1935. "true" ,
  1936. "false" ,
  1937. "tool",
  1938. "var",
  1939. "setget",
  1940. "pass",
  1941. "and",
  1942. "or",
  1943. "export",
  1944. "assert",
  1945. "breakpoint",
  1946. "yield",
  1947. "static",
  1948. "float",
  1949. "int",
  1950. "signal",
  1951. 0};
  1952. const char **w=_reserved_words;
  1953. while (*w) {
  1954. p_words->push_back(*w);
  1955. w++;
  1956. }
  1957. for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
  1958. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1959. }
  1960. }
  1961. GDScriptLanguage::GDScriptLanguage() {
  1962. calls=0;
  1963. ERR_FAIL_COND(singleton);
  1964. singleton=this;
  1965. strings._init = StaticCString::create("_init");
  1966. strings._notification = StaticCString::create("_notification");
  1967. strings._set= StaticCString::create("_set");
  1968. strings._get= StaticCString::create("_get");
  1969. strings._get_property_list= StaticCString::create("_get_property_list");
  1970. strings._script_source=StaticCString::create("script/source");
  1971. _debug_parse_err_line=-1;
  1972. _debug_parse_err_file="";
  1973. _debug_call_stack_pos=0;
  1974. int dmcs=GLOBAL_DEF("debug/script_max_call_stack",1024);
  1975. if (ScriptDebugger::get_singleton()) {
  1976. //debugging enabled!
  1977. _debug_max_call_stack = dmcs;
  1978. if (_debug_max_call_stack<1024)
  1979. _debug_max_call_stack=1024;
  1980. _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
  1981. } else {
  1982. _debug_max_call_stack=0;
  1983. _call_stack=NULL;
  1984. }
  1985. }
  1986. GDScriptLanguage::~GDScriptLanguage() {
  1987. if (_call_stack) {
  1988. memdelete_arr(_call_stack);
  1989. }
  1990. singleton=NULL;
  1991. }
  1992. /*************** RESOURCE ***************/
  1993. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_original_path, Error *r_error) {
  1994. if (r_error)
  1995. *r_error=ERR_FILE_CANT_OPEN;
  1996. GDScript *script = memnew( GDScript );
  1997. Ref<GDScript> scriptres(script);
  1998. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1999. script->set_script_path(p_original_path); // script needs this.
  2000. script->set_path(p_original_path);
  2001. Error err = script->load_byte_code(p_path);
  2002. if (err!=OK) {
  2003. ERR_FAIL_COND_V(err!=OK, RES());
  2004. }
  2005. } else {
  2006. Error err = script->load_source_code(p_path);
  2007. if (err!=OK) {
  2008. ERR_FAIL_COND_V(err!=OK, RES());
  2009. }
  2010. script->set_script_path(p_original_path); // script needs this.
  2011. script->set_path(p_original_path);
  2012. //script->set_name(p_path.get_file());
  2013. script->reload();
  2014. }
  2015. if (r_error)
  2016. *r_error=OK;
  2017. return scriptres;
  2018. }
  2019. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  2020. p_extensions->push_back("gd");
  2021. p_extensions->push_back("gdc");
  2022. p_extensions->push_back("gde");
  2023. }
  2024. bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const {
  2025. return (p_type=="Script" || p_type=="GDScript");
  2026. }
  2027. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  2028. String el = p_path.extension().to_lower();
  2029. if (el=="gd" || el=="gdc" || el=="gde")
  2030. return "GDScript";
  2031. return "";
  2032. }
  2033. Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
  2034. Ref<GDScript> sqscr = p_resource;
  2035. ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER);
  2036. String source = sqscr->get_source_code();
  2037. Error err;
  2038. FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
  2039. if (err) {
  2040. ERR_FAIL_COND_V(err,err);
  2041. }
  2042. file->store_string(source);
  2043. if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) {
  2044. memdelete(file);
  2045. return ERR_CANT_CREATE;
  2046. }
  2047. file->close();
  2048. memdelete(file);
  2049. return OK;
  2050. }
  2051. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
  2052. if (p_resource->cast_to<GDScript>()) {
  2053. p_extensions->push_back("gd");
  2054. }
  2055. }
  2056. bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const {
  2057. return p_resource->cast_to<GDScript>()!=NULL;
  2058. }