gd_script.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  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. /* TODO:
  35. *populate globals
  36. *do checks as close to debugger as possible (but don't do debugger)
  37. *const check plz
  38. *check arguments and default arguments in GDFunction
  39. -get property list in instance?
  40. *missing opcodes
  41. -const checks
  42. -make thread safe
  43. */
  44. Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self, Variant *p_stack,String& r_error) const{
  45. int address = p_address&ADDR_MASK;
  46. //sequential table (jump table generated by compiler)
  47. switch((p_address&ADDR_TYPE_MASK)>>ADDR_BITS) {
  48. case ADDR_TYPE_SELF: {
  49. if (!p_instance) {
  50. r_error="Cannot access self without instance.";
  51. return NULL;
  52. }
  53. return &self;
  54. } break;
  55. case ADDR_TYPE_MEMBER: {
  56. //member indexing is O(1)
  57. if (!p_instance) {
  58. r_error="Cannot access member without instance.";
  59. return NULL;
  60. }
  61. return &p_instance->members[address];
  62. } break;
  63. case ADDR_TYPE_CLASS_CONSTANT: {
  64. //todo change to index!
  65. GDScript *s=p_script;
  66. ERR_FAIL_INDEX_V(address,_global_names_count,NULL);
  67. const StringName *sn = &_global_names_ptr[address];
  68. while(s) {
  69. Map<StringName,Variant>::Element *E=s->constants.find(*sn);
  70. if (E) {
  71. return &E->get();
  72. }
  73. s=s->_base;
  74. }
  75. ERR_EXPLAIN("GDCompiler bug..");
  76. ERR_FAIL_V(NULL);
  77. } break;
  78. case ADDR_TYPE_LOCAL_CONSTANT: {
  79. ERR_FAIL_INDEX_V(address,_constant_count,NULL);
  80. return &_constants_ptr[address];
  81. } break;
  82. case ADDR_TYPE_STACK:
  83. case ADDR_TYPE_STACK_VARIABLE: {
  84. ERR_FAIL_INDEX_V(address,_stack_size,NULL);
  85. return &p_stack[address];
  86. } break;
  87. case ADDR_TYPE_GLOBAL: {
  88. ERR_FAIL_INDEX_V(address,GDScriptLanguage::get_singleton()->get_global_array_size(),NULL);
  89. return &GDScriptLanguage::get_singleton()->get_global_array()[address];
  90. } break;
  91. case ADDR_TYPE_NIL: {
  92. return &nil;
  93. } break;
  94. }
  95. ERR_EXPLAIN("Bad Code! (Addressing Mode)");
  96. ERR_FAIL_V(NULL);
  97. return NULL;
  98. }
  99. String GDFunction::_get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const {
  100. String err_text;
  101. if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
  102. int errorarg=p_err.argument;
  103. 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)+".";
  104. } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
  105. err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
  106. } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
  107. err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
  108. } else if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
  109. err_text="Invalid call. Unexisting "+p_where+".";
  110. } else if (p_err.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
  111. err_text="Attempt to call "+p_where+" on a null instance.";
  112. } else {
  113. err_text="Bug, call error: #"+itos(p_err.error);
  114. }
  115. return err_text;
  116. }
  117. static String _get_var_type(const Variant* p_type) {
  118. String basestr;
  119. if (p_type->get_type()==Variant::OBJECT) {
  120. Object *bobj = *p_type;
  121. if (!bobj) {
  122. basestr = "null instance";
  123. } else {
  124. #ifdef DEBUG_ENABLED
  125. if (ObjectDB::instance_validate(bobj)) {
  126. if (bobj->get_script_instance())
  127. basestr= bobj->get_type()+" ("+bobj->get_script_instance()->get_script()->get_path().get_file()+")";
  128. else
  129. basestr = bobj->get_type();
  130. } else {
  131. basestr="previously freed instance";
  132. }
  133. #else
  134. basestr="Object";
  135. #endif
  136. }
  137. } else {
  138. basestr = Variant::get_type_name(p_type->get_type());
  139. }
  140. return basestr;
  141. }
  142. Variant GDFunction::call(GDInstance *p_instance,const Variant **p_args, int p_argcount,Variant::CallError& r_err) {
  143. if (!_code_ptr) {
  144. return Variant();
  145. }
  146. r_err.error=Variant::CallError::CALL_OK;
  147. Variant self;
  148. Variant retvalue;
  149. Variant *stack = NULL;
  150. Variant **call_args;
  151. int defarg=0;
  152. #ifdef DEBUG_ENABLED
  153. //GDScriptLanguage::get_singleton()->calls++;
  154. #endif
  155. if (p_argcount!=_argument_count) {
  156. if (p_argcount>_argument_count) {
  157. r_err.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  158. r_err.argument=_argument_count;
  159. return Variant();
  160. } else if (p_argcount < _argument_count - _default_arg_count) {
  161. r_err.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  162. r_err.argument=_argument_count - _default_arg_count;
  163. return Variant();
  164. } else {
  165. defarg=_argument_count-p_argcount;
  166. }
  167. }
  168. uint32_t alloca_size = sizeof(Variant*)*_call_size + sizeof(Variant)*_stack_size;
  169. if (alloca_size) {
  170. uint8_t *aptr = (uint8_t*)alloca(alloca_size);
  171. if (_stack_size) {
  172. stack=(Variant*)aptr;
  173. for(int i=0;i<p_argcount;i++)
  174. memnew_placement(&stack[i],Variant(*p_args[i]));
  175. for(int i=p_argcount;i<_stack_size;i++)
  176. memnew_placement(&stack[i],Variant);
  177. } else {
  178. stack=NULL;
  179. }
  180. if (_call_size) {
  181. call_args = (Variant**)&aptr[sizeof(Variant)*_stack_size];
  182. } else {
  183. call_args=NULL;
  184. }
  185. } else {
  186. stack=NULL;
  187. call_args=NULL;
  188. }
  189. GDScript *_class;
  190. if (p_instance) {
  191. if (p_instance->base_ref && static_cast<Reference*>(p_instance->owner)->is_referenced()) {
  192. self=REF(static_cast<Reference*>(p_instance->owner));
  193. } else {
  194. self=p_instance->owner;
  195. }
  196. _class=p_instance->script.ptr();
  197. } else {
  198. _class=_script;
  199. }
  200. int ip=0;
  201. int line=_initial_line;
  202. String err_text;
  203. #ifdef DEBUG_ENABLED
  204. if (ScriptDebugger::get_singleton())
  205. GDScriptLanguage::get_singleton()->enter_function(p_instance,this,stack,&ip,&line);
  206. #define CHECK_SPACE(m_space)\
  207. ERR_BREAK((ip+m_space)>_code_size)
  208. #define GET_VARIANT_PTR(m_v,m_code_ofs) \
  209. Variant *m_v; \
  210. m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);\
  211. if (!m_v)\
  212. break;
  213. #else
  214. #define CHECK_SPACE(m_space)
  215. #define GET_VARIANT_PTR(m_v,m_code_ofs) \
  216. Variant *m_v; \
  217. m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);
  218. #endif
  219. bool exit_ok=false;
  220. while(ip<_code_size) {
  221. int last_opcode=_code_ptr[ip];
  222. switch(_code_ptr[ip]) {
  223. case OPCODE_OPERATOR: {
  224. CHECK_SPACE(5);
  225. bool valid;
  226. Variant::Operator op = (Variant::Operator)_code_ptr[ip+1];
  227. ERR_BREAK(op>=Variant::OP_MAX);
  228. GET_VARIANT_PTR(a,2);
  229. GET_VARIANT_PTR(b,3);
  230. GET_VARIANT_PTR(dst,4);
  231. Variant::evaluate(op,*a,*b,*dst,valid);
  232. if (!valid) {
  233. if (false && dst->get_type()==Variant::STRING) {
  234. //return a string when invalid with the error
  235. err_text=*dst;
  236. } else {
  237. 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)+"'.";
  238. }
  239. break;
  240. }
  241. ip+=5;
  242. } continue;
  243. case OPCODE_EXTENDS_TEST: {
  244. CHECK_SPACE(4);
  245. GET_VARIANT_PTR(a,1);
  246. GET_VARIANT_PTR(b,2);
  247. GET_VARIANT_PTR(dst,3);
  248. #ifdef DEBUG_ENABLED
  249. if (a->get_type()!=Variant::OBJECT || a->operator Object*()==NULL) {
  250. err_text="Left operand of 'extends' is not an instance of anything.";
  251. break;
  252. }
  253. if (b->get_type()!=Variant::OBJECT || b->operator Object*()==NULL) {
  254. err_text="Right operand of 'extends' is not a class.";
  255. break;
  256. }
  257. #endif
  258. Object *obj_A = *a;
  259. Object *obj_B = *b;
  260. GDScript *scr_B = obj_B->cast_to<GDScript>();
  261. bool extends_ok=false;
  262. if (scr_B) {
  263. //if B is a script, the only valid condition is that A has an instance which inherits from the script
  264. //in other situation, this shoul return false.
  265. if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language()==GDScriptLanguage::get_singleton()) {
  266. GDInstance *ins = static_cast<GDInstance*>(obj_A->get_script_instance());
  267. GDScript *cmp = ins->script.ptr();
  268. //bool found=false;
  269. while(cmp) {
  270. if (cmp==scr_B) {
  271. //inherits from script, all ok
  272. extends_ok=true;
  273. break;
  274. }
  275. cmp=cmp->_base;
  276. }
  277. }
  278. } else {
  279. GDNativeClass *nc= obj_B->cast_to<GDNativeClass>();
  280. if (!nc) {
  281. err_text="Right operand of 'extends' is not a class (type: '"+obj_B->get_type()+"').";
  282. break;
  283. }
  284. extends_ok=ObjectTypeDB::is_type(obj_A->get_type_name(),nc->get_name());
  285. }
  286. *dst=extends_ok;
  287. ip+=4;
  288. } continue;
  289. case OPCODE_SET: {
  290. CHECK_SPACE(3);
  291. GET_VARIANT_PTR(dst,1);
  292. GET_VARIANT_PTR(index,2);
  293. GET_VARIANT_PTR(value,3);
  294. bool valid;
  295. dst->set(*index,*value,&valid);
  296. if (!valid) {
  297. String v = index->operator String();
  298. if (v!="") {
  299. v="'"+v+"'";
  300. } else {
  301. v="of type '"+_get_var_type(index)+"'";
  302. }
  303. err_text="Invalid set index "+v+" (on base: '"+_get_var_type(dst)+"').";
  304. break;
  305. }
  306. ip+=4;
  307. } continue;
  308. case OPCODE_GET: {
  309. CHECK_SPACE(3);
  310. GET_VARIANT_PTR(src,1);
  311. GET_VARIANT_PTR(index,2);
  312. GET_VARIANT_PTR(dst,3);
  313. bool valid;
  314. *dst = src->get(*index,&valid);
  315. if (!valid) {
  316. String v = index->operator String();
  317. if (v!="") {
  318. v="'"+v+"'";
  319. } else {
  320. v="of type '"+_get_var_type(index)+"'";
  321. }
  322. err_text="Invalid get index "+v+" (on base: '"+_get_var_type(src)+"').";
  323. break;
  324. }
  325. ip+=4;
  326. } continue;
  327. case OPCODE_SET_NAMED: {
  328. CHECK_SPACE(3);
  329. GET_VARIANT_PTR(dst,1);
  330. GET_VARIANT_PTR(value,3);
  331. int indexname = _code_ptr[ip+2];
  332. ERR_BREAK(indexname<0 || indexname>=_global_names_count);
  333. const StringName *index = &_global_names_ptr[indexname];
  334. bool valid;
  335. dst->set_named(*index,*value,&valid);
  336. if (!valid) {
  337. String err_type;
  338. err_text="Invalid set index '"+String(*index)+"' (on base: '"+_get_var_type(dst)+"').";
  339. break;
  340. }
  341. ip+=4;
  342. } continue;
  343. case OPCODE_GET_NAMED: {
  344. CHECK_SPACE(3);
  345. GET_VARIANT_PTR(src,1);
  346. GET_VARIANT_PTR(dst,3);
  347. int indexname = _code_ptr[ip+2];
  348. ERR_BREAK(indexname<0 || indexname>=_global_names_count);
  349. const StringName *index = &_global_names_ptr[indexname];
  350. bool valid;
  351. *dst = src->get_named(*index,&valid);
  352. if (!valid) {
  353. err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"').";
  354. break;
  355. }
  356. ip+=4;
  357. } continue;
  358. case OPCODE_ASSIGN: {
  359. CHECK_SPACE(3);
  360. GET_VARIANT_PTR(dst,1);
  361. GET_VARIANT_PTR(src,2);
  362. *dst = *src;
  363. ip+=3;
  364. } continue;
  365. case OPCODE_ASSIGN_TRUE: {
  366. CHECK_SPACE(2);
  367. GET_VARIANT_PTR(dst,1);
  368. *dst = true;
  369. ip+=2;
  370. } continue;
  371. case OPCODE_ASSIGN_FALSE: {
  372. CHECK_SPACE(2);
  373. GET_VARIANT_PTR(dst,1);
  374. *dst = false;
  375. ip+=2;
  376. } continue;
  377. case OPCODE_CONSTRUCT: {
  378. CHECK_SPACE(2);
  379. Variant::Type t=Variant::Type(_code_ptr[ip+1]);
  380. int argc=_code_ptr[ip+2];
  381. CHECK_SPACE(argc+2);
  382. Variant **argptrs = call_args;
  383. for(int i=0;i<argc;i++) {
  384. GET_VARIANT_PTR(v,3+i);
  385. argptrs[i]=v;
  386. }
  387. GET_VARIANT_PTR(dst,3+argc);
  388. Variant::CallError err;
  389. *dst = Variant::construct(t,(const Variant**)argptrs,argc,err);
  390. if (err.error!=Variant::CallError::CALL_OK) {
  391. err_text=_get_call_error(err,"'"+Variant::get_type_name(t)+"' constructor",(const Variant**)argptrs);
  392. break;
  393. }
  394. ip+=4+argc;
  395. //construct a basic type
  396. } continue;
  397. case OPCODE_CONSTRUCT_ARRAY: {
  398. CHECK_SPACE(1);
  399. int argc=_code_ptr[ip+1];
  400. Array array(true); //arrays are always shared
  401. array.resize(argc);
  402. CHECK_SPACE(argc+2);
  403. for(int i=0;i<argc;i++) {
  404. GET_VARIANT_PTR(v,2+i);
  405. array[i]=*v;
  406. }
  407. GET_VARIANT_PTR(dst,2+argc);
  408. *dst=array;
  409. ip+=3+argc;
  410. } continue;
  411. case OPCODE_CONSTRUCT_DICTIONARY: {
  412. CHECK_SPACE(1);
  413. int argc=_code_ptr[ip+1];
  414. Dictionary dict(true); //arrays are always shared
  415. CHECK_SPACE(argc*2+2);
  416. for(int i=0;i<argc;i++) {
  417. GET_VARIANT_PTR(k,2+i*2+0);
  418. GET_VARIANT_PTR(v,2+i*2+1);
  419. dict[*k]=*v;
  420. }
  421. GET_VARIANT_PTR(dst,2+argc*2);
  422. *dst=dict;
  423. ip+=3+argc*2;
  424. } continue;
  425. case OPCODE_CALL_RETURN:
  426. case OPCODE_CALL: {
  427. CHECK_SPACE(4);
  428. bool call_ret = _code_ptr[ip]==OPCODE_CALL_RETURN;
  429. int argc=_code_ptr[ip+1];
  430. GET_VARIANT_PTR(base,2);
  431. int nameg=_code_ptr[ip+3];
  432. ERR_BREAK(nameg<0 || nameg>=_global_names_count);
  433. const StringName *methodname = &_global_names_ptr[nameg];
  434. ERR_BREAK(argc<0);
  435. ip+=4;
  436. CHECK_SPACE(argc+1);
  437. Variant **argptrs = call_args;
  438. for(int i=0;i<argc;i++) {
  439. GET_VARIANT_PTR(v,i);
  440. argptrs[i]=v;
  441. }
  442. Variant::CallError err;
  443. if (call_ret) {
  444. GET_VARIANT_PTR(ret,argc);
  445. *ret = base->call(*methodname,(const Variant**)argptrs,argc,err);
  446. } else {
  447. base->call(*methodname,(const Variant**)argptrs,argc,err);
  448. }
  449. if (err.error!=Variant::CallError::CALL_OK) {
  450. String methodstr = *methodname;
  451. String basestr = _get_var_type(base);
  452. if (methodstr=="call") {
  453. if (argc>=1) {
  454. methodstr=String(*argptrs[0])+" (via call)";
  455. if (err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
  456. err.argument-=1;
  457. }
  458. }
  459. }
  460. err_text=_get_call_error(err,"function '"+methodstr+"' in base '"+basestr+"'",(const Variant**)argptrs);
  461. break;
  462. }
  463. //_call_func(NULL,base,*methodname,ip,argc,p_instance,stack);
  464. ip+=argc+1;
  465. } continue;
  466. case OPCODE_CALL_BUILT_IN: {
  467. CHECK_SPACE(4);
  468. GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip+1]);
  469. int argc=_code_ptr[ip+2];
  470. ERR_BREAK(argc<0);
  471. ip+=3;
  472. CHECK_SPACE(argc+1);
  473. Variant **argptrs = call_args;
  474. for(int i=0;i<argc;i++) {
  475. GET_VARIANT_PTR(v,i);
  476. argptrs[i]=v;
  477. }
  478. GET_VARIANT_PTR(dst,argc);
  479. Variant::CallError err;
  480. GDFunctions::call(func,(const Variant**)argptrs,argc,*dst,err);
  481. if (err.error!=Variant::CallError::CALL_OK) {
  482. String methodstr = GDFunctions::get_func_name(func);
  483. err_text=_get_call_error(err,"built-in function '"+methodstr+"'",(const Variant**)argptrs);
  484. break;
  485. }
  486. ip+=argc+1;
  487. } continue;
  488. case OPCODE_CALL_SELF: {
  489. } break;
  490. case OPCODE_CALL_SELF_BASE: {
  491. CHECK_SPACE(2);
  492. int self_fun = _code_ptr[ip+1];
  493. #ifdef DEBUG_ENABLED
  494. if (self_fun<0 || self_fun>=_global_names_count) {
  495. err_text="compiler bug, function name not found";
  496. break;
  497. }
  498. #endif
  499. const StringName *methodname = &_global_names_ptr[self_fun];
  500. int argc=_code_ptr[ip+2];
  501. CHECK_SPACE(2+argc+1);
  502. Variant **argptrs = call_args;
  503. for(int i=0;i<argc;i++) {
  504. GET_VARIANT_PTR(v,i+3);
  505. argptrs[i]=v;
  506. }
  507. GET_VARIANT_PTR(dst,argc+3);
  508. const GDScript *gds = _script;
  509. const Map<StringName,GDFunction>::Element *E=NULL;
  510. while (gds->base.ptr()) {
  511. gds=gds->base.ptr();
  512. E=gds->member_functions.find(*methodname);
  513. if (E)
  514. break;
  515. }
  516. Variant::CallError err;
  517. if (E) {
  518. *dst=((GDFunction*)&E->get())->call(p_instance,(const Variant**)argptrs,argc,err);
  519. } else if (gds->native.ptr()) {
  520. if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
  521. MethodBind *mb = ObjectTypeDB::get_method(gds->native->get_name(),*methodname);
  522. if (!mb) {
  523. err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  524. } else {
  525. *dst=mb->call(p_instance->owner,(const Variant**)argptrs,argc,err);
  526. }
  527. } else {
  528. err.error=Variant::CallError::CALL_OK;
  529. }
  530. } else {
  531. if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
  532. err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  533. } else {
  534. err.error=Variant::CallError::CALL_OK;
  535. }
  536. }
  537. if (err.error!=Variant::CallError::CALL_OK) {
  538. String methodstr = *methodname;
  539. err_text=_get_call_error(err,"function '"+methodstr+"'",(const Variant**)argptrs);
  540. break;
  541. }
  542. ip+=4+argc;
  543. } continue;
  544. case OPCODE_JUMP: {
  545. CHECK_SPACE(2);
  546. int to = _code_ptr[ip+1];
  547. ERR_BREAK(to<0 || to>_code_size);
  548. ip=to;
  549. } continue;
  550. case OPCODE_JUMP_IF: {
  551. CHECK_SPACE(3);
  552. GET_VARIANT_PTR(test,1);
  553. bool valid;
  554. bool result = test->booleanize(valid);
  555. #ifdef DEBUG_ENABLED
  556. if (!valid) {
  557. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  558. break;
  559. }
  560. #endif
  561. if (result) {
  562. int to = _code_ptr[ip+2];
  563. ERR_BREAK(to<0 || to>_code_size);
  564. ip=to;
  565. continue;
  566. }
  567. ip+=3;
  568. } continue;
  569. case OPCODE_JUMP_IF_NOT: {
  570. CHECK_SPACE(3);
  571. GET_VARIANT_PTR(test,1);
  572. bool valid;
  573. bool result = test->booleanize(valid);
  574. #ifdef DEBUG_ENABLED
  575. if (!valid) {
  576. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  577. break;
  578. }
  579. #endif
  580. if (!result) {
  581. int to = _code_ptr[ip+2];
  582. ERR_BREAK(to<0 || to>_code_size);
  583. ip=to;
  584. continue;
  585. }
  586. ip+=3;
  587. } continue;
  588. case OPCODE_JUMP_TO_DEF_ARGUMENT: {
  589. CHECK_SPACE(2);
  590. ip=_default_arg_ptr[defarg];
  591. } continue;
  592. case OPCODE_RETURN: {
  593. CHECK_SPACE(2);
  594. GET_VARIANT_PTR(r,1);
  595. retvalue=*r;
  596. exit_ok=true;
  597. } break;
  598. case OPCODE_ITERATE_BEGIN: {
  599. CHECK_SPACE(8); //space for this an regular iterate
  600. GET_VARIANT_PTR(counter,1);
  601. GET_VARIANT_PTR(container,2);
  602. bool valid;
  603. if (!container->iter_init(*counter,valid)) {
  604. if (!valid) {
  605. err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"'.";
  606. break;
  607. }
  608. int jumpto=_code_ptr[ip+3];
  609. ERR_BREAK(jumpto<0 || jumpto>_code_size);
  610. ip=jumpto;
  611. continue;
  612. }
  613. GET_VARIANT_PTR(iterator,4);
  614. *iterator=container->iter_get(*counter,valid);
  615. if (!valid) {
  616. err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"'.";
  617. break;
  618. }
  619. ip+=5; //skip regular iterate which is always next
  620. } continue;
  621. case OPCODE_ITERATE: {
  622. CHECK_SPACE(4);
  623. GET_VARIANT_PTR(counter,1);
  624. GET_VARIANT_PTR(container,2);
  625. bool valid;
  626. if (!container->iter_next(*counter,valid)) {
  627. if (!valid) {
  628. err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"' (type changed since first iteration?).";
  629. break;
  630. }
  631. int jumpto=_code_ptr[ip+3];
  632. ERR_BREAK(jumpto<0 || jumpto>_code_size);
  633. ip=jumpto;
  634. continue;
  635. }
  636. GET_VARIANT_PTR(iterator,4);
  637. *iterator=container->iter_get(*counter,valid);
  638. if (!valid) {
  639. err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"' (but was obtained on first iteration?).";
  640. break;
  641. }
  642. ip+=5; //loop again
  643. } continue;
  644. case OPCODE_ASSERT: {
  645. CHECK_SPACE(2);
  646. GET_VARIANT_PTR(test,1);
  647. #ifdef DEBUG_ENABLED
  648. bool valid;
  649. bool result = test->booleanize(valid);
  650. if (!valid) {
  651. err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
  652. break;
  653. }
  654. if (!result) {
  655. err_text="Assertion failed.";
  656. break;
  657. }
  658. #endif
  659. ip+=2;
  660. } continue;
  661. case OPCODE_LINE: {
  662. CHECK_SPACE(2);
  663. line=_code_ptr[ip+1];
  664. ip+=2;
  665. if (ScriptDebugger::get_singleton()) {
  666. // line
  667. bool do_break=false;
  668. if (ScriptDebugger::get_singleton()->get_lines_left()>0) {
  669. if (ScriptDebugger::get_singleton()->get_depth()<=0)
  670. ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 );
  671. if (ScriptDebugger::get_singleton()->get_lines_left()<=0)
  672. do_break=true;
  673. }
  674. if (ScriptDebugger::get_singleton()->is_breakpoint(line,source))
  675. do_break=true;
  676. if (do_break) {
  677. GDScriptLanguage::get_singleton()->debug_break("Breakpoint",true);
  678. }
  679. ScriptDebugger::get_singleton()->line_poll();
  680. }
  681. } continue;
  682. case OPCODE_END: {
  683. exit_ok=true;
  684. break;
  685. } break;
  686. default: {
  687. err_text="Illegal opcode "+itos(_code_ptr[ip])+" at address "+itos(ip);
  688. } break;
  689. }
  690. if (exit_ok)
  691. break;
  692. //error
  693. // function, file, line, error, explanation
  694. String err_file;
  695. if (p_instance)
  696. err_file=p_instance->script->path;
  697. else if (_class)
  698. err_file=_class->path;
  699. if (err_file=="")
  700. err_file="<built-in>";
  701. String err_func = name;
  702. if (p_instance && p_instance->script->name!="")
  703. err_func=p_instance->script->name+"."+err_func;
  704. int err_line=line;
  705. if (err_text=="") {
  706. err_text="Internal Script Error! - opcode #"+itos(last_opcode)+" (report please).";
  707. }
  708. if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) {
  709. // debugger break did not happen
  710. _err_print_error(err_func.utf8().get_data(),err_file.utf8().get_data(),err_line,err_text.utf8().get_data());
  711. }
  712. break;
  713. }
  714. if (ScriptDebugger::get_singleton())
  715. GDScriptLanguage::get_singleton()->exit_function();
  716. if (_stack_size) {
  717. //free stack
  718. for(int i=0;i<_stack_size;i++)
  719. stack[i].~Variant();
  720. }
  721. return retvalue;
  722. }
  723. const int* GDFunction::get_code() const {
  724. return _code_ptr;
  725. }
  726. int GDFunction::get_code_size() const{
  727. return _code_size;
  728. }
  729. Variant GDFunction::get_constant(int p_idx) const {
  730. ERR_FAIL_INDEX_V(p_idx,constants.size(),"<errconst>");
  731. return constants[p_idx];
  732. }
  733. StringName GDFunction::get_global_name(int p_idx) const {
  734. ERR_FAIL_INDEX_V(p_idx,global_names.size(),"<errgname>");
  735. return global_names[p_idx];
  736. }
  737. int GDFunction::get_default_argument_count() const {
  738. return default_arguments.size();
  739. }
  740. int GDFunction::get_default_argument_addr(int p_arg) const{
  741. ERR_FAIL_INDEX_V(p_arg,default_arguments.size(),-1);
  742. return default_arguments[p_arg];
  743. }
  744. StringName GDFunction::get_name() const {
  745. return name;
  746. }
  747. int GDFunction::get_max_stack_size() const {
  748. return _stack_size;
  749. }
  750. struct _GDFKC {
  751. int order;
  752. List<int> pos;
  753. };
  754. struct _GDFKCS {
  755. int order;
  756. StringName id;
  757. int pos;
  758. bool operator<(const _GDFKCS &p_r) const {
  759. return order<p_r.order;
  760. }
  761. };
  762. void GDFunction::debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const {
  763. int oc=0;
  764. Map<StringName,_GDFKC> sdmap;
  765. for( const List<StackDebug>::Element *E=stack_debug.front();E;E=E->next()) {
  766. const StackDebug &sd=E->get();
  767. if (sd.line>p_line)
  768. break;
  769. if (sd.added) {
  770. if (!sdmap.has(sd.identifier)) {
  771. _GDFKC d;
  772. d.order=oc++;
  773. d.pos.push_back(sd.pos);
  774. sdmap[sd.identifier]=d;
  775. } else {
  776. sdmap[sd.identifier].pos.push_back(sd.pos);
  777. }
  778. } else {
  779. ERR_CONTINUE(!sdmap.has(sd.identifier));
  780. sdmap[sd.identifier].pos.pop_back();
  781. if (sdmap[sd.identifier].pos.empty())
  782. sdmap.erase(sd.identifier);
  783. }
  784. }
  785. List<_GDFKCS> stackpositions;
  786. for(Map<StringName,_GDFKC>::Element *E=sdmap.front();E;E=E->next() ) {
  787. _GDFKCS spp;
  788. spp.id=E->key();
  789. spp.order=E->get().order;
  790. spp.pos=E->get().pos.back()->get();
  791. stackpositions.push_back(spp);
  792. }
  793. stackpositions.sort();
  794. for(List<_GDFKCS>::Element *E=stackpositions.front();E;E=E->next()) {
  795. Pair<StringName,int> p;
  796. p.first=E->get().id;
  797. p.second=E->get().pos;
  798. r_stackvars->push_back(p);
  799. }
  800. }
  801. #if 0
  802. void GDFunction::clear() {
  803. name=StringName();
  804. constants.clear();
  805. _stack_size=0;
  806. code.clear();
  807. _constants_ptr=NULL;
  808. _constant_count=0;
  809. _global_names_ptr=NULL;
  810. _global_names_count=0;
  811. _code_ptr=NULL;
  812. _code_size=0;
  813. }
  814. #endif
  815. GDFunction::GDFunction() {
  816. _stack_size=0;
  817. _call_size=0;
  818. name="<anonymous>";
  819. }
  820. GDNativeClass::GDNativeClass(const StringName& p_name) {
  821. name=p_name;
  822. }
  823. /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){
  824. }*/
  825. bool GDNativeClass::_get(const StringName& p_name,Variant &r_ret) const {
  826. bool ok;
  827. int v = ObjectTypeDB::get_integer_constant(name, p_name, &ok);
  828. if (ok) {
  829. r_ret=v;
  830. return true;
  831. } else {
  832. return false;
  833. }
  834. }
  835. void GDNativeClass::_bind_methods() {
  836. ObjectTypeDB::bind_method(_MD("new"),&GDNativeClass::_new);
  837. }
  838. Variant GDNativeClass::_new() {
  839. Object *o = instance();
  840. if (!o) {
  841. ERR_EXPLAIN("Class type: '"+String(name)+"' is not instantiable.");
  842. ERR_FAIL_COND_V(!o,Variant());
  843. }
  844. Reference *ref = o->cast_to<Reference>();
  845. if (ref) {
  846. return REF(ref);
  847. } else {
  848. return o;
  849. }
  850. }
  851. Object *GDNativeClass::instance() {
  852. return ObjectTypeDB::instance(name);
  853. }
  854. GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref) {
  855. /* STEP 1, CREATE */
  856. GDInstance* instance = memnew( GDInstance );
  857. instance->base_ref=p_isref;
  858. instance->members.resize(member_indices.size());
  859. instance->script=Ref<GDScript>(this);
  860. instance->owner=p_owner;
  861. instance->owner->set_script_instance(instance);
  862. /* STEP 2, INITIALIZE AND CONSRTUCT */
  863. instances.insert(instance->owner);
  864. Variant::CallError err;
  865. initializer->call(instance,p_args,p_argcount,err);
  866. if (err.error!=Variant::CallError::CALL_OK) {
  867. instance->script=Ref<GDScript>();
  868. instances.erase(p_owner);
  869. memdelete(instance);
  870. ERR_FAIL_COND_V(err.error!=Variant::CallError::CALL_OK, NULL); //error consrtucting
  871. }
  872. //@TODO make thread safe
  873. return instance;
  874. }
  875. Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) {
  876. /* STEP 1, CREATE */
  877. r_error.error=Variant::CallError::CALL_OK;
  878. REF ref;
  879. Object *owner=NULL;
  880. GDScript *_baseptr=this;
  881. while (_baseptr->_base) {
  882. _baseptr=_baseptr->_base;
  883. }
  884. if (_baseptr->native.ptr()) {
  885. owner=_baseptr->native->instance();
  886. } else {
  887. owner=memnew( Reference ); //by default, no base means use reference
  888. }
  889. Reference *r=owner->cast_to<Reference>();
  890. if (r) {
  891. ref=REF(r);
  892. }
  893. GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL);
  894. if (!instance) {
  895. if (ref.is_null()) {
  896. memdelete(owner); //no owner, sorry
  897. }
  898. return Variant();
  899. }
  900. if (ref.is_valid()) {
  901. return ref;
  902. } else {
  903. return owner;
  904. }
  905. }
  906. bool GDScript::can_instance() const {
  907. return valid; //any script in GDscript can instance
  908. }
  909. StringName GDScript::get_instance_base_type() const {
  910. if (native.is_valid())
  911. return native->get_name();
  912. if (base.is_valid())
  913. return base->get_instance_base_type();
  914. return StringName();
  915. }
  916. struct _GDScriptMemberSort {
  917. int index;
  918. StringName name;
  919. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; }
  920. };
  921. #ifdef TOOLS_ENABLED
  922. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  923. placeholders.erase(p_placeholder);
  924. }
  925. void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
  926. List<PropertyInfo> plist;
  927. GDScript *scr=this;
  928. Map<StringName,Variant> default_values;
  929. while(scr) {
  930. Vector<_GDScriptMemberSort> msort;
  931. for(Map<StringName,PropertyInfo>::Element *E=scr->member_info.front();E;E=E->next()) {
  932. _GDScriptMemberSort ms;
  933. ERR_CONTINUE(!scr->member_indices.has(E->key()));
  934. ms.index=scr->member_indices[E->key()];
  935. ms.name=E->key();
  936. msort.push_back(ms);
  937. }
  938. msort.sort();
  939. msort.invert();
  940. for(int i=0;i<msort.size();i++) {
  941. plist.push_front(scr->member_info[msort[i].name]);
  942. if (scr->member_default_values.has(msort[i].name))
  943. default_values[msort[i].name]=scr->member_default_values[msort[i].name];
  944. else {
  945. Variant::CallError err;
  946. default_values[msort[i].name]=Variant::construct(scr->member_info[msort[i].name].type,NULL,0,err);
  947. }
  948. }
  949. scr=scr->_base;
  950. }
  951. p_placeholder->update(plist,default_values);
  952. }
  953. #endif
  954. ScriptInstance* GDScript::instance_create(Object *p_this) {
  955. if (!tool && !ScriptServer::is_scripting_enabled()) {
  956. #ifdef TOOLS_ENABLED
  957. //instance a fake script for editing the values
  958. //plist.invert();
  959. /*print_line("CREATING PLACEHOLDER");
  960. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  961. print_line(E->get().name);
  962. }*/
  963. PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) );
  964. placeholders.insert(si);
  965. _update_placeholder(si);
  966. return si;
  967. #else
  968. return NULL;
  969. #endif
  970. }
  971. GDScript *top=this;
  972. while(top->_base)
  973. top=top->_base;
  974. if (top->native.is_valid()) {
  975. if (!ObjectTypeDB::is_type(p_this->get_type_name(),top->native->get_name())) {
  976. if (ScriptDebugger::get_singleton()) {
  977. 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()+"'");
  978. }
  979. 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()+"'");
  980. ERR_FAIL_V(NULL);
  981. }
  982. }
  983. return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>());
  984. }
  985. bool GDScript::instance_has(const Object *p_this) const {
  986. return instances.has((Object*)p_this);
  987. }
  988. bool GDScript::has_source_code() const {
  989. return source!="";
  990. }
  991. String GDScript::get_source_code() const {
  992. return source;
  993. }
  994. void GDScript::set_source_code(const String& p_code) {
  995. source=p_code;
  996. }
  997. void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) {
  998. p_sc->path=p_path;
  999. for(Map<StringName,Ref<GDScript> >::Element *E=p_sc->subclasses.front();E;E=E->next()) {
  1000. _set_subclass_path(E->get(),p_path);
  1001. }
  1002. }
  1003. Error GDScript::reload() {
  1004. ERR_FAIL_COND_V(instances.size(),ERR_ALREADY_IN_USE);
  1005. String basedir=path;
  1006. if (basedir=="")
  1007. basedir==get_path();
  1008. if (basedir!="")
  1009. basedir=basedir.get_base_dir();
  1010. valid=false;
  1011. GDParser parser;
  1012. Error err = parser.parse(source,basedir);
  1013. if (err) {
  1014. if (ScriptDebugger::get_singleton()) {
  1015. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),parser.get_error_line(),"Parser Error: "+parser.get_error());
  1016. }
  1017. _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());
  1018. ERR_FAIL_V(ERR_PARSE_ERROR);
  1019. }
  1020. GDCompiler compiler;
  1021. err = compiler.compile(&parser,this);
  1022. if (err) {
  1023. if (ScriptDebugger::get_singleton()) {
  1024. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error());
  1025. }
  1026. _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());
  1027. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  1028. }
  1029. valid=true;
  1030. for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
  1031. _set_subclass_path(E->get(),path);
  1032. }
  1033. #ifdef TOOLS_ENABLED
  1034. for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  1035. _update_placeholder(E->get());
  1036. }
  1037. #endif
  1038. return OK;
  1039. }
  1040. String GDScript::get_node_type() const {
  1041. return ""; // ?
  1042. }
  1043. ScriptLanguage *GDScript::get_language() const {
  1044. return GDScriptLanguage::get_singleton();
  1045. }
  1046. Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1047. GDScript *top=this;
  1048. while(top) {
  1049. Map<StringName,GDFunction>::Element *E=top->member_functions.find(p_method);
  1050. if (E) {
  1051. if (!E->get().is_static()) {
  1052. WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data());
  1053. }
  1054. return E->get().call(NULL,p_args,p_argcount,r_error);
  1055. }
  1056. top=top->_base;
  1057. }
  1058. //none found, regular
  1059. return Script::call(p_method,p_args,p_argcount,r_error);
  1060. }
  1061. bool GDScript::_get(const StringName& p_name,Variant &r_ret) const {
  1062. {
  1063. const GDScript *top=this;
  1064. while(top) {
  1065. {
  1066. const Map<StringName,Variant>::Element *E=top->constants.find(p_name);
  1067. if (E) {
  1068. r_ret= E->get();
  1069. return true;
  1070. }
  1071. }
  1072. {
  1073. const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name);
  1074. if (E) {
  1075. r_ret=E->get();
  1076. return true;
  1077. }
  1078. }
  1079. top=top->_base;
  1080. }
  1081. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1082. r_ret=get_source_code();
  1083. return true;
  1084. }
  1085. }
  1086. return false;
  1087. }
  1088. bool GDScript::_set(const StringName& p_name, const Variant& p_value) {
  1089. if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
  1090. set_source_code(p_value);
  1091. reload();
  1092. } else
  1093. return false;
  1094. return true;
  1095. }
  1096. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1097. p_properties->push_back( PropertyInfo(Variant::STRING,"script/source",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
  1098. }
  1099. void GDScript::_bind_methods() {
  1100. ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo("new"));
  1101. }
  1102. Error GDScript::load_source_code(const String& p_path) {
  1103. DVector<uint8_t> sourcef;
  1104. Error err;
  1105. FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err);
  1106. if (err) {
  1107. ERR_FAIL_COND_V(err,err);
  1108. }
  1109. int len = f->get_len();
  1110. sourcef.resize(len+1);
  1111. DVector<uint8_t>::Write w = sourcef.write();
  1112. int r = f->get_buffer(w.ptr(),len);
  1113. f->close();
  1114. memdelete(f);
  1115. ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN);
  1116. w[len]=0;
  1117. String s;
  1118. if (s.parse_utf8((const char*)w.ptr())) {
  1119. 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.");
  1120. ERR_FAIL_V(ERR_INVALID_DATA);
  1121. }
  1122. source=s;
  1123. path=p_path;
  1124. return OK;
  1125. }
  1126. const Map<StringName,GDFunction>& GDScript::debug_get_member_functions() const {
  1127. return member_functions;
  1128. }
  1129. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  1130. for(const Map<StringName,int>::Element *E=member_indices.front();E;E=E->next()) {
  1131. if (E->get()==p_idx)
  1132. return E->key();
  1133. }
  1134. return "<error>";
  1135. }
  1136. Ref<GDScript> GDScript::get_base() const {
  1137. return base;
  1138. }
  1139. GDScript::GDScript() {
  1140. valid=false;
  1141. subclass_count=0;
  1142. initializer=NULL;
  1143. _base=NULL;
  1144. _owner=NULL;
  1145. tool=false;
  1146. }
  1147. //////////////////////////////
  1148. // INSTANCE //
  1149. //////////////////////////////
  1150. bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
  1151. //member
  1152. {
  1153. const Map<StringName,int>::Element *E = script->member_indices.find(p_name);
  1154. if (E) {
  1155. members[E->get()]=p_value;
  1156. return true;
  1157. }
  1158. }
  1159. GDScript *sptr=script.ptr();
  1160. while(sptr) {
  1161. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  1162. if (E) {
  1163. Variant name=p_name;
  1164. const Variant *args[2]={&name,&p_value};
  1165. Variant::CallError err;
  1166. Variant ret = E->get().call(this,(const Variant**)args,2,err);
  1167. if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool())
  1168. return true;
  1169. }
  1170. sptr = sptr->_base;
  1171. }
  1172. return false;
  1173. }
  1174. bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
  1175. const GDScript *sptr=script.ptr();
  1176. while(sptr) {
  1177. {
  1178. const Map<StringName,int>::Element *E = script->member_indices.find(p_name);
  1179. if (E) {
  1180. r_ret=members[E->get()];
  1181. return true; //index found
  1182. }
  1183. }
  1184. {
  1185. const Map<StringName,Variant>::Element *E = script->constants.find(p_name);
  1186. if (E) {
  1187. r_ret=E->get();
  1188. return true; //index found
  1189. }
  1190. }
  1191. {
  1192. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  1193. if (E) {
  1194. Variant name=p_name;
  1195. const Variant *args[1]={&name};
  1196. Variant::CallError err;
  1197. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err);
  1198. if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
  1199. r_ret=ret;
  1200. return true;
  1201. }
  1202. }
  1203. }
  1204. sptr = sptr->_base;
  1205. }
  1206. return false;
  1207. }
  1208. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1209. // exported members, not doen yet!
  1210. const GDScript *sptr=script.ptr();
  1211. List<PropertyInfo> props;
  1212. while(sptr) {
  1213. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  1214. if (E) {
  1215. Variant::CallError err;
  1216. Variant ret = const_cast<GDFunction*>(&E->get())->call(const_cast<GDInstance*>(this),NULL,0,err);
  1217. if (err.error==Variant::CallError::CALL_OK) {
  1218. if (ret.get_type()!=Variant::ARRAY) {
  1219. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  1220. ERR_FAIL();
  1221. }
  1222. Array arr = ret;
  1223. for(int i=0;i<arr.size();i++) {
  1224. Dictionary d = arr[i];
  1225. ERR_CONTINUE(!d.has("name"));
  1226. ERR_CONTINUE(!d.has("type"));
  1227. PropertyInfo pinfo;
  1228. pinfo.type = Variant::Type( d["type"].operator int());
  1229. ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX );
  1230. pinfo.name = d["name"];
  1231. ERR_CONTINUE(pinfo.name=="");
  1232. if (d.has("hint"))
  1233. pinfo.hint=PropertyHint(d["hint"].operator int());
  1234. if (d.has("hint_string"))
  1235. pinfo.hint_string=d["hint_string"];
  1236. if (d.has("usage"))
  1237. pinfo.usage=d["usage"];
  1238. props.push_back(pinfo);
  1239. }
  1240. }
  1241. }
  1242. //instance a fake script for editing the values
  1243. Vector<_GDScriptMemberSort> msort;
  1244. for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
  1245. _GDScriptMemberSort ms;
  1246. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  1247. ms.index=sptr->member_indices[E->key()];
  1248. ms.name=E->key();
  1249. msort.push_back(ms);
  1250. }
  1251. msort.sort();
  1252. msort.invert();
  1253. for(int i=0;i<msort.size();i++) {
  1254. props.push_front(sptr->member_info[msort[i].name]);
  1255. }
  1256. #if 0
  1257. if (sptr->member_functions.has("_get_property_list")) {
  1258. Variant::CallError err;
  1259. GDFunction *f = const_cast<GDFunction*>(&sptr->member_functions["_get_property_list"]);
  1260. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  1261. if (plv.get_type()!=Variant::ARRAY) {
  1262. ERR_PRINT("_get_property_list: expected array returned");
  1263. } else {
  1264. Array pl=plv;
  1265. for(int i=0;i<pl.size();i++) {
  1266. Dictionary p = pl[i];
  1267. PropertyInfo pinfo;
  1268. if (!p.has("name")) {
  1269. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  1270. continue;
  1271. }
  1272. if (!p.has("type")) {
  1273. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  1274. continue;
  1275. }
  1276. pinfo.name=p["name"];
  1277. pinfo.type=Variant::Type(int(p["type"]));
  1278. if (p.has("hint"))
  1279. pinfo.hint=PropertyHint(int(p["hint"]));
  1280. if (p.has("hint_string"))
  1281. pinfo.hint_string=p["hint_string"];
  1282. if (p.has("usage"))
  1283. pinfo.usage=p["usage"];
  1284. props.push_back(pinfo);
  1285. }
  1286. }
  1287. }
  1288. #endif
  1289. sptr = sptr->_base;
  1290. }
  1291. //props.invert();
  1292. for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  1293. p_properties->push_back(E->get());
  1294. }
  1295. }
  1296. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  1297. const GDScript *sptr=script.ptr();
  1298. while(sptr) {
  1299. for (Map<StringName,GDFunction>::Element *E = sptr->member_functions.front();E;E=E->next()) {
  1300. MethodInfo mi;
  1301. mi.name=E->key();
  1302. for(int i=0;i<E->get().get_argument_count();i++)
  1303. mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
  1304. p_list->push_back(mi);
  1305. }
  1306. sptr = sptr->_base;
  1307. }
  1308. }
  1309. bool GDInstance::has_method(const StringName& p_method) const {
  1310. const GDScript *sptr=script.ptr();
  1311. while(sptr) {
  1312. const Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1313. if (E)
  1314. return true;
  1315. sptr = sptr->_base;
  1316. }
  1317. return false;
  1318. }
  1319. Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
  1320. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  1321. GDScript *sptr=script.ptr();
  1322. while(sptr) {
  1323. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1324. if (E) {
  1325. return E->get().call(this,p_args,p_argcount,r_error);
  1326. }
  1327. sptr = sptr->_base;
  1328. }
  1329. r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1330. return Variant();
  1331. }
  1332. void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1333. GDScript *sptr=script.ptr();
  1334. Variant::CallError ce;
  1335. while(sptr) {
  1336. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1337. if (E) {
  1338. E->get().call(this,p_args,p_argcount,ce);
  1339. }
  1340. sptr = sptr->_base;
  1341. }
  1342. }
  1343. void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) {
  1344. if (sptr->_base)
  1345. _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount);
  1346. Variant::CallError ce;
  1347. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(p_method);
  1348. if (E) {
  1349. E->get().call(this,p_args,p_argcount,ce);
  1350. }
  1351. }
  1352. void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
  1353. if (script.ptr()) {
  1354. _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount);
  1355. }
  1356. }
  1357. void GDInstance::notification(int p_notification) {
  1358. //notification is not virutal, it gets called at ALL levels just like in C.
  1359. Variant value=p_notification;
  1360. const Variant *args[1]={&value };
  1361. GDScript *sptr=script.ptr();
  1362. while(sptr) {
  1363. Map<StringName,GDFunction>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  1364. if (E) {
  1365. Variant::CallError err;
  1366. E->get().call(this,args,1,err);
  1367. if (err.error!=Variant::CallError::CALL_OK) {
  1368. //print error about notification call
  1369. }
  1370. }
  1371. sptr = sptr->_base;
  1372. }
  1373. }
  1374. Ref<Script> GDInstance::get_script() const {
  1375. return script;
  1376. }
  1377. ScriptLanguage *GDInstance::get_language() {
  1378. return GDScriptLanguage::get_singleton();
  1379. }
  1380. GDInstance::GDInstance() {
  1381. owner=NULL;
  1382. base_ref=false;
  1383. }
  1384. GDInstance::~GDInstance() {
  1385. if (script.is_valid() && owner) {
  1386. script->instances.erase(owner);
  1387. }
  1388. }
  1389. /************* SCRIPT LANGUAGE **************/
  1390. /************* SCRIPT LANGUAGE **************/
  1391. /************* SCRIPT LANGUAGE **************/
  1392. /************* SCRIPT LANGUAGE **************/
  1393. /************* SCRIPT LANGUAGE **************/
  1394. GDScriptLanguage *GDScriptLanguage::singleton=NULL;
  1395. String GDScriptLanguage::get_name() const {
  1396. return "GDScript";
  1397. }
  1398. /* LANGUAGE FUNCTIONS */
  1399. void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) {
  1400. if (globals.has(p_name)) {
  1401. //overwrite existing
  1402. global_array[globals[p_name]]=p_value;
  1403. return;
  1404. }
  1405. globals[p_name]=global_array.size();
  1406. global_array.push_back(p_value);
  1407. _global_array=global_array.ptr();
  1408. }
  1409. void GDScriptLanguage::init() {
  1410. //populate global constants
  1411. int gcc=GlobalConstants::get_global_constant_count();
  1412. for(int i=0;i<gcc;i++) {
  1413. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i));
  1414. }
  1415. _add_global(StaticCString::create("PI"),Math_PI);
  1416. //populate native classes
  1417. List<String> class_list;
  1418. ObjectTypeDB::get_type_list(&class_list);
  1419. for(List<String>::Element *E=class_list.front();E;E=E->next()) {
  1420. StringName n = E->get();
  1421. String s = String(n);
  1422. if (s.begins_with("_"))
  1423. n=s.substr(1,s.length());
  1424. if (globals.has(n))
  1425. continue;
  1426. Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) );
  1427. _add_global(n,nc);
  1428. }
  1429. //populate singletons
  1430. List<Globals::Singleton> singletons;
  1431. Globals::get_singleton()->get_singletons(&singletons);
  1432. for(List<Globals::Singleton>::Element *E=singletons.front();E;E=E->next()) {
  1433. _add_global(E->get().name,E->get().ptr);
  1434. }
  1435. }
  1436. String GDScriptLanguage::get_type() const {
  1437. return "GDScript";
  1438. }
  1439. String GDScriptLanguage::get_extension() const {
  1440. return "gd";
  1441. }
  1442. Error GDScriptLanguage::execute_file(const String& p_path) {
  1443. // ??
  1444. return OK;
  1445. }
  1446. void GDScriptLanguage::finish() {
  1447. }
  1448. void GDScriptLanguage::frame() {
  1449. // print_line("calls: "+itos(calls));
  1450. calls=0;
  1451. }
  1452. /* EDITOR FUNCTIONS */
  1453. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1454. static const char *_reserved_words[]={
  1455. "break",
  1456. "class",
  1457. "continue",
  1458. "const",
  1459. "else",
  1460. "elif",
  1461. "enum",
  1462. "extends" ,
  1463. "for" ,
  1464. "func" ,
  1465. "if" ,
  1466. "in" ,
  1467. "varl",
  1468. "null" ,
  1469. "return" ,
  1470. "self" ,
  1471. "while" ,
  1472. "true" ,
  1473. "false" ,
  1474. "tool",
  1475. "var",
  1476. "pass",
  1477. "and",
  1478. "or",
  1479. "export",
  1480. 0};
  1481. const char **w=_reserved_words;
  1482. while (*w) {
  1483. p_words->push_back(*w);
  1484. w++;
  1485. }
  1486. for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
  1487. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1488. }
  1489. }
  1490. GDScriptLanguage::GDScriptLanguage() {
  1491. calls=0;
  1492. ERR_FAIL_COND(singleton);
  1493. singleton=this;
  1494. strings._init = StaticCString::create("_init");
  1495. strings._notification = StaticCString::create("_notification");
  1496. strings._set= StaticCString::create("_set");
  1497. strings._get= StaticCString::create("_get");
  1498. strings._get_property_list= StaticCString::create("_get_property_list");
  1499. strings._script_source=StaticCString::create("script/source");
  1500. _debug_parse_err_line=-1;
  1501. _debug_parse_err_file="";
  1502. _debug_call_stack_pos=0;
  1503. int dmcs=GLOBAL_DEF("debug/script_max_call_stack",1024);
  1504. if (ScriptDebugger::get_singleton()) {
  1505. //debugging enabled!
  1506. _debug_max_call_stack = dmcs;
  1507. if (_debug_max_call_stack<1024)
  1508. _debug_max_call_stack=1024;
  1509. _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
  1510. } else {
  1511. _debug_max_call_stack=0;
  1512. _call_stack=NULL;
  1513. }
  1514. }
  1515. GDScriptLanguage::~GDScriptLanguage() {
  1516. if (_call_stack) {
  1517. memdelete_arr(_call_stack);
  1518. }
  1519. singleton=NULL;
  1520. }
  1521. /*************** RESOURCE ***************/
  1522. RES ResourceFormatLoaderGDScript::load(const String &p_path,const String& p_original_path) {
  1523. GDScript *script = memnew( GDScript );
  1524. Ref<GDScript> scriptres(script);
  1525. Error err = script->load_source_code(p_path);
  1526. if (err!=OK) {
  1527. ERR_FAIL_COND_V(err!=OK, RES());
  1528. }
  1529. script->set_script_path(p_original_path); // script needs this.
  1530. script->set_path(p_original_path);
  1531. //script->set_name(p_path.get_file());
  1532. script->reload();
  1533. return scriptres;
  1534. }
  1535. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1536. p_extensions->push_back("gd");
  1537. }
  1538. bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const {
  1539. return (p_type=="Script" || p_type=="GDScript");
  1540. }
  1541. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1542. if (p_path.extension().to_lower()=="gd")
  1543. return "GDScript";
  1544. return "";
  1545. }
  1546. Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
  1547. Ref<GDScript> sqscr = p_resource;
  1548. ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER);
  1549. String source = sqscr->get_source_code();
  1550. Error err;
  1551. FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
  1552. if (err) {
  1553. ERR_FAIL_COND_V(err,err);
  1554. }
  1555. file->store_string(source);
  1556. file->close();
  1557. memdelete(file);
  1558. return OK;
  1559. }
  1560. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
  1561. if (p_resource->cast_to<GDScript>()) {
  1562. p_extensions->push_back("gd");
  1563. }
  1564. }
  1565. bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const {
  1566. return p_resource->cast_to<GDScript>()!=NULL;
  1567. }