gd_script.cpp 63 KB

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