gd_script.cpp 63 KB

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