gd_script.cpp 57 KB

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