2
0

gd_script.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748
  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:var","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) {
  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. Variant::CallError err;
  1070. initializer->call(instance,p_args,p_argcount,err);
  1071. if (err.error!=Variant::CallError::CALL_OK) {
  1072. instance->script=Ref<GDScript>();
  1073. instance->owner->set_script_instance(NULL);
  1074. instances.erase(p_owner);
  1075. ERR_FAIL_COND_V(err.error!=Variant::CallError::CALL_OK, NULL); //error consrtucting
  1076. }
  1077. //@TODO make thread safe
  1078. return instance;
  1079. }
  1080. Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) {
  1081. /* STEP 1, CREATE */
  1082. r_error.error=Variant::CallError::CALL_OK;
  1083. REF ref;
  1084. Object *owner=NULL;
  1085. GDScript *_baseptr=this;
  1086. while (_baseptr->_base) {
  1087. _baseptr=_baseptr->_base;
  1088. }
  1089. if (_baseptr->native.ptr()) {
  1090. owner=_baseptr->native->instance();
  1091. } else {
  1092. owner=memnew( Reference ); //by default, no base means use reference
  1093. }
  1094. Reference *r=owner->cast_to<Reference>();
  1095. if (r) {
  1096. ref=REF(r);
  1097. }
  1098. GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL);
  1099. if (!instance) {
  1100. if (ref.is_null()) {
  1101. memdelete(owner); //no owner, sorry
  1102. }
  1103. return Variant();
  1104. }
  1105. if (ref.is_valid()) {
  1106. return ref;
  1107. } else {
  1108. return owner;
  1109. }
  1110. }
  1111. bool GDScript::can_instance() const {
  1112. //return valid; //any script in GDscript can instance
  1113. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  1114. }
  1115. StringName GDScript::get_instance_base_type() const {
  1116. if (native.is_valid())
  1117. return native->get_name();
  1118. if (base.is_valid())
  1119. return base->get_instance_base_type();
  1120. return StringName();
  1121. }
  1122. struct _GDScriptMemberSort {
  1123. int index;
  1124. StringName name;
  1125. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; }
  1126. };
  1127. #ifdef TOOLS_ENABLED
  1128. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1129. placeholders.erase(p_placeholder);
  1130. }
  1131. /*
  1132. void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
  1133. List<PropertyInfo> plist;
  1134. GDScript *scr=this;
  1135. Map<StringName,Variant> default_values;
  1136. while(scr) {
  1137. Vector<_GDScriptMemberSort> msort;
  1138. for(Map<StringName,PropertyInfo>::Element *E=scr->member_info.front();E;E=E->next()) {
  1139. _GDScriptMemberSort ms;
  1140. ERR_CONTINUE(!scr->member_indices.has(E->key()));
  1141. ms.index=scr->member_indices[E->key()].index;
  1142. ms.name=E->key();
  1143. msort.push_back(ms);
  1144. }
  1145. msort.sort();
  1146. msort.invert();
  1147. for(int i=0;i<msort.size();i++) {
  1148. plist.push_front(scr->member_info[msort[i].name]);
  1149. if (scr->member_default_values.has(msort[i].name))
  1150. default_values[msort[i].name]=scr->member_default_values[msort[i].name];
  1151. else {
  1152. Variant::CallError err;
  1153. default_values[msort[i].name]=Variant::construct(scr->member_info[msort[i].name].type,NULL,0,err);
  1154. }
  1155. }
  1156. scr=scr->_base;
  1157. }
  1158. p_placeholder->update(plist,default_values);
  1159. }*/
  1160. #endif
  1161. ScriptInstance* GDScript::instance_create(Object *p_this) {
  1162. if (!tool && !ScriptServer::is_scripting_enabled()) {
  1163. #ifdef TOOLS_ENABLED
  1164. //instance a fake script for editing the values
  1165. //plist.invert();
  1166. /*print_line("CREATING PLACEHOLDER");
  1167. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  1168. print_line(E->get().name);
  1169. }*/
  1170. PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) );
  1171. placeholders.insert(si);
  1172. //_update_placeholder(si);
  1173. _update_exports();
  1174. return si;
  1175. #else
  1176. return NULL;
  1177. #endif
  1178. }
  1179. GDScript *top=this;
  1180. while(top->_base)
  1181. top=top->_base;
  1182. if (top->native.is_valid()) {
  1183. if (!ObjectTypeDB::is_type(p_this->get_type_name(),top->native->get_name())) {
  1184. if (ScriptDebugger::get_singleton()) {
  1185. 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()+"'");
  1186. }
  1187. 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()+"'");
  1188. ERR_FAIL_V(NULL);
  1189. }
  1190. }
  1191. return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>());
  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. }
  1274. } else {
  1275. //print_line("unchaged is "+get_path());
  1276. }
  1277. if (base_cache.is_valid()) {
  1278. if (base_cache->_update_exports()) {
  1279. changed = true;
  1280. }
  1281. }
  1282. if (/*changed &&*/ placeholders.size()) { //hm :(
  1283. //print_line("updating placeholders for "+get_path());
  1284. //update placeholders if any
  1285. Map<StringName,Variant> values;
  1286. List<PropertyInfo> propnames;
  1287. _update_exports_values(values,propnames);
  1288. for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  1289. E->get()->update(propnames,values);
  1290. }
  1291. }
  1292. return changed;
  1293. #endif
  1294. return false;
  1295. }
  1296. void GDScript::update_exports() {
  1297. #ifdef TOOLS_ENABLED
  1298. _update_exports();
  1299. Set<ObjectID> copy=inheriters_cache; //might get modified
  1300. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  1301. for(Set<ObjectID>::Element *E=copy.front();E;E=E->next()) {
  1302. Object *id=ObjectDB::get_instance(E->get());
  1303. if (!id)
  1304. continue;
  1305. GDScript *s=id->cast_to<GDScript>();
  1306. if (!s)
  1307. continue;
  1308. s->update_exports();
  1309. }
  1310. #endif
  1311. }
  1312. void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) {
  1313. p_sc->path=p_path;
  1314. for(Map<StringName,Ref<GDScript> >::Element *E=p_sc->subclasses.front();E;E=E->next()) {
  1315. _set_subclass_path(E->get(),p_path);
  1316. }
  1317. }
  1318. Error GDScript::reload() {
  1319. ERR_FAIL_COND_V(instances.size(),ERR_ALREADY_IN_USE);
  1320. String basedir=path;
  1321. if (basedir=="")
  1322. basedir=get_path();
  1323. if (basedir!="")
  1324. basedir=basedir.get_base_dir();
  1325. valid=false;
  1326. GDParser parser;
  1327. Error err = parser.parse(source,basedir,false,path);
  1328. if (err) {
  1329. if (ScriptDebugger::get_singleton()) {
  1330. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),parser.get_error_line(),"Parser Error: "+parser.get_error());
  1331. }
  1332. _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());
  1333. ERR_FAIL_V(ERR_PARSE_ERROR);
  1334. }
  1335. GDCompiler compiler;
  1336. err = compiler.compile(&parser,this);
  1337. if (err) {
  1338. if (ScriptDebugger::get_singleton()) {
  1339. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error());
  1340. }
  1341. _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());
  1342. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  1343. }
  1344. valid=true;
  1345. for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
  1346. _set_subclass_path(E->get(),path);
  1347. }
  1348. #ifdef TOOLS_ENABLED
  1349. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  1350. _update_placeholder(E->get());
  1351. }*/
  1352. #endif
  1353. return OK;
  1354. }
  1355. String GDScript::get_node_type() const {
  1356. return ""; // ?
  1357. }
  1358. ScriptLanguage *GDScript::get_language() const {
  1359. return GDScriptLanguage::get_singleton();
  1360. }
  1361. Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1362. GDScript *top=this;
  1363. while(top) {
  1364. Map<StringName,GDFunction>::Element *E=top->member_functions.find(p_method);
  1365. if (E) {
  1366. if (!E->get().is_static()) {
  1367. WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data());
  1368. }
  1369. return E->get().call(NULL,p_args,p_argcount,r_error);
  1370. }
  1371. top=top->_base;
  1372. }
  1373. //none found, regular
  1374. return Script::call(p_method,p_args,p_argcount,r_error);
  1375. }
  1376. bool GDScript::_get(const StringName& p_name,Variant &r_ret) const {
  1377. {
  1378. const GDScript *top=this;
  1379. while(top) {
  1380. {
  1381. const Map<StringName,Variant>::Element *E=top->constants.find(p_name);
  1382. if (E) {
  1383. r_ret= E->get();
  1384. return true;
  1385. }
  1386. }
  1387. {
  1388. const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name);
  1389. if (E) {
  1390. r_ret=E->get();
  1391. return true;
  1392. }
  1393. }
  1394. top=top->_base;
  1395. }
  1396. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1397. r_ret=get_source_code();
  1398. return true;
  1399. }
  1400. }
  1401. return false;
  1402. }
  1403. bool GDScript::_set(const StringName& p_name, const Variant& p_value) {
  1404. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1405. set_source_code(p_value);
  1406. reload();
  1407. } else
  1408. return false;
  1409. return true;
  1410. }
  1411. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1412. p_properties->push_back( PropertyInfo(Variant::STRING,"script/source",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
  1413. }
  1414. void GDScript::_bind_methods() {
  1415. ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo("new"));
  1416. }
  1417. Error GDScript::load_byte_code(const String& p_path) {
  1418. Vector<uint8_t> bytecode;
  1419. if (p_path.ends_with("gde")) {
  1420. FileAccess *fa = FileAccess::open(p_path,FileAccess::READ);
  1421. ERR_FAIL_COND_V(!fa,ERR_CANT_OPEN);
  1422. FileAccessEncrypted *fae = memnew( FileAccessEncrypted );
  1423. ERR_FAIL_COND_V(!fae,ERR_CANT_OPEN);
  1424. Vector<uint8_t> key;
  1425. key.resize(32);
  1426. for(int i=0;i<key.size();i++) {
  1427. key[i]=script_encryption_key[i];
  1428. }
  1429. Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_READ);
  1430. ERR_FAIL_COND_V(err,err);
  1431. bytecode.resize(fae->get_len());
  1432. fae->get_buffer(bytecode.ptr(),bytecode.size());
  1433. memdelete(fae);
  1434. } else {
  1435. bytecode = FileAccess::get_file_as_array(p_path);
  1436. }
  1437. ERR_FAIL_COND_V(bytecode.size()==0,ERR_PARSE_ERROR);
  1438. path=p_path;
  1439. String basedir=path;
  1440. if (basedir=="")
  1441. basedir=get_path();
  1442. if (basedir!="")
  1443. basedir=basedir.get_base_dir();
  1444. valid=false;
  1445. GDParser parser;
  1446. Error err = parser.parse_bytecode(bytecode,basedir,get_path());
  1447. if (err) {
  1448. _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());
  1449. ERR_FAIL_V(ERR_PARSE_ERROR);
  1450. }
  1451. GDCompiler compiler;
  1452. err = compiler.compile(&parser,this);
  1453. if (err) {
  1454. _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());
  1455. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  1456. }
  1457. valid=true;
  1458. for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
  1459. _set_subclass_path(E->get(),path);
  1460. }
  1461. return OK;
  1462. }
  1463. Error GDScript::load_source_code(const String& p_path) {
  1464. DVector<uint8_t> sourcef;
  1465. Error err;
  1466. FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err);
  1467. if (err) {
  1468. ERR_FAIL_COND_V(err,err);
  1469. }
  1470. int len = f->get_len();
  1471. sourcef.resize(len+1);
  1472. DVector<uint8_t>::Write w = sourcef.write();
  1473. int r = f->get_buffer(w.ptr(),len);
  1474. f->close();
  1475. memdelete(f);
  1476. ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN);
  1477. w[len]=0;
  1478. String s;
  1479. if (s.parse_utf8((const char*)w.ptr())) {
  1480. 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.");
  1481. ERR_FAIL_V(ERR_INVALID_DATA);
  1482. }
  1483. source=s;
  1484. #ifdef TOOLS_ENABLED
  1485. source_changed_cache=true;
  1486. #endif
  1487. //print_line("LSC :"+get_path());
  1488. path=p_path;
  1489. return OK;
  1490. }
  1491. const Map<StringName,GDFunction>& GDScript::debug_get_member_functions() const {
  1492. return member_functions;
  1493. }
  1494. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  1495. for(const Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) {
  1496. if (E->get().index==p_idx)
  1497. return E->key();
  1498. }
  1499. return "<error>";
  1500. }
  1501. Ref<GDScript> GDScript::get_base() const {
  1502. return base;
  1503. }
  1504. GDScript::GDScript() {
  1505. _static_ref=this;
  1506. valid=false;
  1507. subclass_count=0;
  1508. initializer=NULL;
  1509. _base=NULL;
  1510. _owner=NULL;
  1511. tool=false;
  1512. #ifdef TOOLS_ENABLED
  1513. source_changed_cache=false;
  1514. #endif
  1515. }
  1516. //////////////////////////////
  1517. // INSTANCE //
  1518. //////////////////////////////
  1519. bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
  1520. //member
  1521. {
  1522. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  1523. if (E) {
  1524. members[E->get().index]=p_value;
  1525. if (E->get().setter) {
  1526. const Variant *val=&p_value;
  1527. Variant::CallError err;
  1528. call(E->get().setter,&val,1,err);
  1529. if (err.error==Variant::CallError::CALL_OK) {
  1530. return true; //function exists, call was successful
  1531. }
  1532. }
  1533. return true;
  1534. }
  1535. }
  1536. GDScript *sptr=script.ptr();
  1537. while(sptr) {
  1538. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  1539. if (E) {
  1540. Variant name=p_name;
  1541. const Variant *args[2]={&name,&p_value};
  1542. Variant::CallError err;
  1543. Variant ret = E->get().call(this,(const Variant**)args,2,err);
  1544. if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool())
  1545. return true;
  1546. }
  1547. sptr = sptr->_base;
  1548. }
  1549. return false;
  1550. }
  1551. bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
  1552. const GDScript *sptr=script.ptr();
  1553. while(sptr) {
  1554. {
  1555. const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  1556. if (E) {
  1557. if (E->get().getter) {
  1558. Variant::CallError err;
  1559. r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err);
  1560. if (err.error==Variant::CallError::CALL_OK) {
  1561. return true;
  1562. }
  1563. }
  1564. r_ret=members[E->get().index];
  1565. return true; //index found
  1566. }
  1567. }
  1568. {
  1569. const Map<StringName,Variant>::Element *E = script->constants.find(p_name);
  1570. if (E) {
  1571. r_ret=E->get();
  1572. return true; //index found
  1573. }
  1574. }
  1575. {
  1576. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  1577. if (E) {
  1578. Variant name=p_name;
  1579. const Variant *args[1]={&name};
  1580. Variant::CallError err;
  1581. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err);
  1582. if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
  1583. r_ret=ret;
  1584. return true;
  1585. }
  1586. }
  1587. }
  1588. sptr = sptr->_base;
  1589. }
  1590. return false;
  1591. }
  1592. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1593. // exported members, not doen yet!
  1594. const GDScript *sptr=script.ptr();
  1595. List<PropertyInfo> props;
  1596. while(sptr) {
  1597. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  1598. if (E) {
  1599. Variant::CallError err;
  1600. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),NULL,0,err);
  1601. if (err.error==Variant::CallError::CALL_OK) {
  1602. if (ret.get_type()!=Variant::ARRAY) {
  1603. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  1604. ERR_FAIL();
  1605. }
  1606. Array arr = ret;
  1607. for(int i=0;i<arr.size();i++) {
  1608. Dictionary d = arr[i];
  1609. ERR_CONTINUE(!d.has("name"));
  1610. ERR_CONTINUE(!d.has("type"));
  1611. PropertyInfo pinfo;
  1612. pinfo.type = Variant::Type( d["type"].operator int());
  1613. ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX );
  1614. pinfo.name = d["name"];
  1615. ERR_CONTINUE(pinfo.name=="");
  1616. if (d.has("hint"))
  1617. pinfo.hint=PropertyHint(d["hint"].operator int());
  1618. if (d.has("hint_string"))
  1619. pinfo.hint_string=d["hint_string"];
  1620. if (d.has("usage"))
  1621. pinfo.usage=d["usage"];
  1622. props.push_back(pinfo);
  1623. }
  1624. }
  1625. }
  1626. //instance a fake script for editing the values
  1627. Vector<_GDScriptMemberSort> msort;
  1628. for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
  1629. _GDScriptMemberSort ms;
  1630. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  1631. ms.index=sptr->member_indices[E->key()].index;
  1632. ms.name=E->key();
  1633. msort.push_back(ms);
  1634. }
  1635. msort.sort();
  1636. msort.invert();
  1637. for(int i=0;i<msort.size();i++) {
  1638. props.push_front(sptr->member_info[msort[i].name]);
  1639. }
  1640. #if 0
  1641. if (sptr->member_functions.has("_get_property_list")) {
  1642. Variant::CallError err;
  1643. GDFunction *f = const_cast<GDFunction*>(&sptr->member_functions["_get_property_list"]);
  1644. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  1645. if (plv.get_type()!=Variant::ARRAY) {
  1646. ERR_PRINT("_get_property_list: expected array returned");
  1647. } else {
  1648. Array pl=plv;
  1649. for(int i=0;i<pl.size();i++) {
  1650. Dictionary p = pl[i];
  1651. PropertyInfo pinfo;
  1652. if (!p.has("name")) {
  1653. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  1654. continue;
  1655. }
  1656. if (!p.has("type")) {
  1657. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  1658. continue;
  1659. }
  1660. pinfo.name=p["name"];
  1661. pinfo.type=Variant::Type(int(p["type"]));
  1662. if (p.has("hint"))
  1663. pinfo.hint=PropertyHint(int(p["hint"]));
  1664. if (p.has("hint_string"))
  1665. pinfo.hint_string=p["hint_string"];
  1666. if (p.has("usage"))
  1667. pinfo.usage=p["usage"];
  1668. props.push_back(pinfo);
  1669. }
  1670. }
  1671. }
  1672. #endif
  1673. sptr = sptr->_base;
  1674. }
  1675. //props.invert();
  1676. for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  1677. p_properties->push_back(E->get());
  1678. }
  1679. }
  1680. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  1681. const GDScript *sptr=script.ptr();
  1682. while(sptr) {
  1683. for (Map<StringName,GDFunction>::Element *E = sptr->member_functions.front();E;E=E->next()) {
  1684. MethodInfo mi;
  1685. mi.name=E->key();
  1686. for(int i=0;i<E->get().get_argument_count();i++)
  1687. mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
  1688. p_list->push_back(mi);
  1689. }
  1690. sptr = sptr->_base;
  1691. }
  1692. }
  1693. bool GDInstance::has_method(const StringName& p_method) const {
  1694. const GDScript *sptr=script.ptr();
  1695. while(sptr) {
  1696. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1697. if (E)
  1698. return true;
  1699. sptr = sptr->_base;
  1700. }
  1701. return false;
  1702. }
  1703. Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1704. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  1705. GDScript *sptr=script.ptr();
  1706. while(sptr) {
  1707. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1708. if (E) {
  1709. return E->get().call(this,p_args,p_argcount,r_error);
  1710. }
  1711. sptr = sptr->_base;
  1712. }
  1713. r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1714. return Variant();
  1715. }
  1716. void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1717. GDScript *sptr=script.ptr();
  1718. Variant::CallError ce;
  1719. while(sptr) {
  1720. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1721. if (E) {
  1722. E->get().call(this,p_args,p_argcount,ce);
  1723. }
  1724. sptr = sptr->_base;
  1725. }
  1726. }
  1727. void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) {
  1728. if (sptr->_base)
  1729. _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount);
  1730. Variant::CallError ce;
  1731. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1732. if (E) {
  1733. E->get().call(this,p_args,p_argcount,ce);
  1734. }
  1735. }
  1736. void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1737. if (script.ptr()) {
  1738. _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount);
  1739. }
  1740. }
  1741. void GDInstance::notification(int p_notification) {
  1742. //notification is not virutal, it gets called at ALL levels just like in C.
  1743. Variant value=p_notification;
  1744. const Variant *args[1]={&value };
  1745. GDScript *sptr=script.ptr();
  1746. while(sptr) {
  1747. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  1748. if (E) {
  1749. Variant::CallError err;
  1750. E->get().call(this,args,1,err);
  1751. if (err.error!=Variant::CallError::CALL_OK) {
  1752. //print error about notification call
  1753. }
  1754. }
  1755. sptr = sptr->_base;
  1756. }
  1757. }
  1758. Ref<Script> GDInstance::get_script() const {
  1759. return script;
  1760. }
  1761. ScriptLanguage *GDInstance::get_language() {
  1762. return GDScriptLanguage::get_singleton();
  1763. }
  1764. GDInstance::GDInstance() {
  1765. owner=NULL;
  1766. base_ref=false;
  1767. }
  1768. GDInstance::~GDInstance() {
  1769. if (script.is_valid() && owner) {
  1770. script->instances.erase(owner);
  1771. }
  1772. }
  1773. /************* SCRIPT LANGUAGE **************/
  1774. /************* SCRIPT LANGUAGE **************/
  1775. /************* SCRIPT LANGUAGE **************/
  1776. /************* SCRIPT LANGUAGE **************/
  1777. /************* SCRIPT LANGUAGE **************/
  1778. GDScriptLanguage *GDScriptLanguage::singleton=NULL;
  1779. String GDScriptLanguage::get_name() const {
  1780. return "GDScript";
  1781. }
  1782. /* LANGUAGE FUNCTIONS */
  1783. void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) {
  1784. if (globals.has(p_name)) {
  1785. //overwrite existing
  1786. global_array[globals[p_name]]=p_value;
  1787. return;
  1788. }
  1789. globals[p_name]=global_array.size();
  1790. global_array.push_back(p_value);
  1791. _global_array=global_array.ptr();
  1792. }
  1793. void GDScriptLanguage::init() {
  1794. //populate global constants
  1795. int gcc=GlobalConstants::get_global_constant_count();
  1796. for(int i=0;i<gcc;i++) {
  1797. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i));
  1798. }
  1799. _add_global(StaticCString::create("PI"),Math_PI);
  1800. //populate native classes
  1801. List<String> class_list;
  1802. ObjectTypeDB::get_type_list(&class_list);
  1803. for(List<String>::Element *E=class_list.front();E;E=E->next()) {
  1804. StringName n = E->get();
  1805. String s = String(n);
  1806. if (s.begins_with("_"))
  1807. n=s.substr(1,s.length());
  1808. if (globals.has(n))
  1809. continue;
  1810. Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) );
  1811. _add_global(n,nc);
  1812. }
  1813. //populate singletons
  1814. List<Globals::Singleton> singletons;
  1815. Globals::get_singleton()->get_singletons(&singletons);
  1816. for(List<Globals::Singleton>::Element *E=singletons.front();E;E=E->next()) {
  1817. _add_global(E->get().name,E->get().ptr);
  1818. }
  1819. }
  1820. String GDScriptLanguage::get_type() const {
  1821. return "GDScript";
  1822. }
  1823. String GDScriptLanguage::get_extension() const {
  1824. return "gd";
  1825. }
  1826. Error GDScriptLanguage::execute_file(const String& p_path) {
  1827. // ??
  1828. return OK;
  1829. }
  1830. void GDScriptLanguage::finish() {
  1831. }
  1832. void GDScriptLanguage::frame() {
  1833. // print_line("calls: "+itos(calls));
  1834. calls=0;
  1835. }
  1836. /* EDITOR FUNCTIONS */
  1837. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1838. static const char *_reserved_words[]={
  1839. "break",
  1840. "class",
  1841. "continue",
  1842. "const",
  1843. "else",
  1844. "elif",
  1845. "enum",
  1846. "extends" ,
  1847. "for" ,
  1848. "func" ,
  1849. "if" ,
  1850. "in" ,
  1851. "null" ,
  1852. "not" ,
  1853. "return" ,
  1854. "self" ,
  1855. "while" ,
  1856. "true" ,
  1857. "false" ,
  1858. "tool",
  1859. "var",
  1860. "setget",
  1861. "pass",
  1862. "and",
  1863. "or",
  1864. "export",
  1865. "assert",
  1866. "yield",
  1867. "static",
  1868. "float",
  1869. "int",
  1870. 0};
  1871. const char **w=_reserved_words;
  1872. while (*w) {
  1873. p_words->push_back(*w);
  1874. w++;
  1875. }
  1876. for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
  1877. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1878. }
  1879. }
  1880. GDScriptLanguage::GDScriptLanguage() {
  1881. calls=0;
  1882. ERR_FAIL_COND(singleton);
  1883. singleton=this;
  1884. strings._init = StaticCString::create("_init");
  1885. strings._notification = StaticCString::create("_notification");
  1886. strings._set= StaticCString::create("_set");
  1887. strings._get= StaticCString::create("_get");
  1888. strings._get_property_list= StaticCString::create("_get_property_list");
  1889. strings._script_source=StaticCString::create("script/source");
  1890. _debug_parse_err_line=-1;
  1891. _debug_parse_err_file="";
  1892. _debug_call_stack_pos=0;
  1893. int dmcs=GLOBAL_DEF("debug/script_max_call_stack",1024);
  1894. if (ScriptDebugger::get_singleton()) {
  1895. //debugging enabled!
  1896. _debug_max_call_stack = dmcs;
  1897. if (_debug_max_call_stack<1024)
  1898. _debug_max_call_stack=1024;
  1899. _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
  1900. } else {
  1901. _debug_max_call_stack=0;
  1902. _call_stack=NULL;
  1903. }
  1904. }
  1905. GDScriptLanguage::~GDScriptLanguage() {
  1906. if (_call_stack) {
  1907. memdelete_arr(_call_stack);
  1908. }
  1909. singleton=NULL;
  1910. }
  1911. /*************** RESOURCE ***************/
  1912. RES ResourceFormatLoaderGDScript::load(const String &p_path,const String& p_original_path) {
  1913. GDScript *script = memnew( GDScript );
  1914. Ref<GDScript> scriptres(script);
  1915. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1916. script->set_script_path(p_original_path); // script needs this.
  1917. script->set_path(p_original_path);
  1918. Error err = script->load_byte_code(p_path);
  1919. if (err!=OK) {
  1920. ERR_FAIL_COND_V(err!=OK, RES());
  1921. }
  1922. } else {
  1923. Error err = script->load_source_code(p_path);
  1924. if (err!=OK) {
  1925. ERR_FAIL_COND_V(err!=OK, RES());
  1926. }
  1927. script->set_script_path(p_original_path); // script needs this.
  1928. script->set_path(p_original_path);
  1929. //script->set_name(p_path.get_file());
  1930. script->reload();
  1931. }
  1932. return scriptres;
  1933. }
  1934. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1935. p_extensions->push_back("gd");
  1936. p_extensions->push_back("gdc");
  1937. p_extensions->push_back("gde");
  1938. }
  1939. bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const {
  1940. return (p_type=="Script" || p_type=="GDScript");
  1941. }
  1942. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1943. String el = p_path.extension().to_lower();
  1944. if (el=="gd" || el=="gdc" || el=="gde")
  1945. return "GDScript";
  1946. return "";
  1947. }
  1948. Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
  1949. Ref<GDScript> sqscr = p_resource;
  1950. ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER);
  1951. String source = sqscr->get_source_code();
  1952. Error err;
  1953. FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
  1954. if (err) {
  1955. ERR_FAIL_COND_V(err,err);
  1956. }
  1957. file->store_string(source);
  1958. if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) {
  1959. memdelete(file);
  1960. return ERR_CANT_CREATE;
  1961. }
  1962. file->close();
  1963. memdelete(file);
  1964. return OK;
  1965. }
  1966. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
  1967. if (p_resource->cast_to<GDScript>()) {
  1968. p_extensions->push_back("gd");
  1969. }
  1970. }
  1971. bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const {
  1972. return p_resource->cast_to<GDScript>()!=NULL;
  1973. }