gd_script.cpp 60 KB

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