fixed warnings in squirrel
[supertux.git] / src / squirrel / squirrel / sqvm.cpp
1 /*
2         see copyright notice in squirrel.h
3 */
4 #include "sqpcheader.h"
5 #include <math.h>
6 #include <stdlib.h>
7 #include "sqopcodes.h"
8 #include "sqfuncproto.h"
9 #include "sqvm.h"
10 #include "sqclosure.h"
11 #include "sqstring.h"
12 #include "sqtable.h"
13 #include "squserdata.h"
14 #include "sqarray.h"
15 #include "sqclass.h"
16
17 #define TOP() (_stack[_top-1])
18
19 bool SQVM::BW_OP(unsigned int op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
20 {
21         SQInteger res;
22         SQInteger i1 = _integer(o1), i2 = _integer(o2);
23         if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER))
24         {
25                 switch(op) {
26                         case BW_AND:    res = i1 & i2; break;
27                         case BW_OR:             res = i1 | i2; break;
28                         case BW_XOR:    res = i1 ^ i2; break;
29                         case BW_SHIFTL: res = i1 << i2; break;
30                         case BW_SHIFTR: res = i1 >> i2; break;
31                         case BW_USHIFTR:res = (SQInteger)(*((unsigned int*)&i1) >> i2); break;
32                         default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; }
33                 }
34         } 
35         else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),GetTypeName(o1),GetTypeName(o2)); return false;}
36         trg = res;
37         return true;
38 }
39
40 bool SQVM::ARITH_OP(unsigned int op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
41 {
42         if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
43                         if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER)) {
44                                 switch(op) {
45                                 case '+': trg = _integer(o1) + _integer(o2); break;
46                                 case '-': trg = _integer(o1) - _integer(o2); break;
47                                 case '/': if(_integer(o2) == 0) { Raise_Error(_SC("division by zero")); return false; }
48                                         trg = _integer(o1) / _integer(o2); 
49                                         break;
50                                 case '*': trg = _integer(o1) * _integer(o2); break;
51                                 case '%': trg = _integer(o1) % _integer(o2); break;
52                                 }
53                         }else{
54                                 switch(op) {
55                                 case '+': trg = tofloat(o1) + tofloat(o2); break;
56                                 case '-': trg = tofloat(o1) - tofloat(o2); break;
57                                 case '/': trg = tofloat(o1) / tofloat(o2); break;
58                                 case '*': trg = tofloat(o1) * tofloat(o2); break;
59                                 case '%': trg = SQFloat(fmod((double)tofloat(o1),(double)tofloat(o2))); break;
60                                 }
61                         }       
62                 } else {
63                         if(op == '+' && (type(o1) == OT_STRING || type(o2) == OT_STRING)){
64                                         if(!StringCat(o1, o2, trg)) return false;
65                         }
66                         else if(!ArithMetaMethod(op,o1,o2,trg)) { 
67                                 Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2)); return false; 
68                         }
69                 }
70                 return true;
71 }
72
73 SQObjectPtr &stack_get(HSQUIRRELVM v,int idx){return ((idx>=0)?(v->GetAt(idx+v->_stackbase-1)):(v->GetUp(idx)));}
74
75 SQVM::SQVM(SQSharedState *ss)
76 {
77         _sharedstate=ss;
78         _suspended=false;
79         _suspended_target=-1;
80         _suspended_root=false;
81         _suspended_traps=-1;
82         _foreignptr=NULL;
83         _nnativecalls=0;
84         _uiRef=0;
85         _lasterror = _null_;
86         _errorhandler = _null_;
87         _debughook = _null_;
88         INIT_CHAIN();ADD_TO_CHAIN(&_ss(this)->_gc_chain,this);
89 }
90
91 void SQVM::Finalize()
92 {
93         _roottable = _null_;
94         _lasterror = _null_;
95         _errorhandler = _null_;
96         _debughook = _null_;
97         temp_reg = _null_;
98         int size=_stack.size();
99         for(int i=0;i<size;i++)
100                 _stack[i]=_null_;
101 }
102
103 SQVM::~SQVM()
104 {
105         Finalize();
106         REMOVE_FROM_CHAIN(&_ss(this)->_gc_chain,this);
107 }
108
109 bool SQVM::ArithMetaMethod(int op,const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &dest)
110 {
111         SQMetaMethod mm;
112         switch(op){
113                 case _SC('+'): mm=MT_ADD; break;
114                 case _SC('-'): mm=MT_SUB; break;
115                 case _SC('/'): mm=MT_DIV; break;
116                 case _SC('*'): mm=MT_MUL; break;
117                 case _SC('%'): mm=MT_MODULO; break;
118         }
119         if(is_delegable(o1) && _delegable(o1)->_delegate) {
120                 Push(o1);Push(o2);
121                 return CallMetaMethod(_delegable(o1),mm,2,dest);
122         }
123         return false;
124 }
125
126 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
127 {
128         
129         switch(type(o)) {
130         case OT_INTEGER:
131                 trg = -_integer(o);
132                 return true;
133         case OT_FLOAT:
134                 trg = -_float(o);
135                 return true;
136         case OT_TABLE:
137         case OT_USERDATA:
138         case OT_INSTANCE:
139                 if(_delegable(o)->_delegate) {
140                         Push(o);
141                         if(CallMetaMethod(_delegable(o), MT_UNM, 1, temp_reg)) {
142                                 trg = temp_reg;
143                                 return true;
144                         }
145                 }
146                 return true;
147         default:
148                 break;
149         }
150         Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
151         return false;
152 }
153
154 #define _RET_SUCCEED(exp) { result = (exp); return true; } 
155 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,int &result)
156 {
157         if(type(o1)==type(o2)){
158                 if(_userpointer(o1)==_userpointer(o2))_RET_SUCCEED(0);
159                 SQObjectPtr res;
160                 switch(type(o1)){
161                 case OT_STRING:
162                         _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
163                 case OT_INTEGER:
164                         _RET_SUCCEED(_integer(o1)-_integer(o2));
165                 case OT_FLOAT:
166                         _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
167                 case OT_TABLE:
168                 case OT_USERDATA:
169                 case OT_INSTANCE:
170                         Push(o1);Push(o2);
171                         if(_delegable(o1)->_delegate)CallMetaMethod(_delegable(o1),MT_CMP,2,res);
172                         break;
173                 default:
174                         break;
175                 }
176                 if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
177                 _RET_SUCCEED(_integer(res));
178         }
179         else{
180                 if(sq_isnumeric(o1) && sq_isnumeric(o2)){
181                         if((type(o1)==OT_INTEGER) && (type(o2)==OT_FLOAT)) { 
182                                 if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
183                                 else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
184                                 _RET_SUCCEED(1);
185                         }
186                         else{
187                                 if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
188                                 else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
189                                 _RET_SUCCEED(1);
190                         }
191                 }
192                 else if(type(o1)==OT_NULL) {_RET_SUCCEED(-1);}
193                 else if(type(o2)==OT_NULL) {_RET_SUCCEED(1);}
194                 else { Raise_CompareError(o1,o2); return false; }
195                 
196         }
197         assert(0);
198         _RET_SUCCEED(0); //cannot happen
199 }
200
201 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
202 {
203         int r;
204         if(ObjCmp(o1,o2,r)) {
205                 switch(op) {
206                         case CMP_G: res = (r > 0)?_true_:_false_; return true;
207                         case CMP_GE: res = (r >= 0)?_true_:_false_; return true;
208                         case CMP_L: res = (r < 0)?_true_:_false_; return true;
209                         case CMP_LE: res = (r <= 0)?_true_:_false_; return true;
210                         
211                 }
212                 assert(0);
213         }
214         return false;
215 }
216
217 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
218 {
219         switch(type(obj))
220         {
221         case OT_STRING:
222                 switch(type(str)){
223                 case OT_STRING: {
224                         int l=_string(str)->_len,ol=_string(obj)->_len;
225                         SQChar *s=_sp(rsl(l+ol+1));
226                         memcpy(s,_stringval(str),rsl(l));memcpy(s+l,_stringval(obj),rsl(ol));s[l+ol]=_SC('\0');
227                         break;
228                 }
229                 case OT_FLOAT:
230                         scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%g%s"),_float(str),_stringval(obj));
231                         break;
232                 case OT_INTEGER:
233                         scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%d%s"),_integer(str),_stringval(obj));
234                         break;
235                 default:
236                         Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
237                         return false;
238                 }
239                 dest=SQString::Create(_ss(this),_spval);
240                 break;
241         case OT_FLOAT:
242                 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%g"),_stringval(str),_float(obj));
243                 dest=SQString::Create(_ss(this),_spval);
244                 break;
245         case OT_INTEGER:
246                 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%d"),_stringval(str),_integer(obj));
247                 dest=SQString::Create(_ss(this),_spval);
248                 break;
249         default:
250                 Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
251                 return false;
252         }
253         return true;
254 }
255
256 const SQChar *IdType2Name(SQObjectType type)
257 {
258         switch(_RAW_TYPE(type))
259         {
260         case _RT_NULL:return _SC("null");
261         case _RT_INTEGER:return _SC("integer");
262         case _RT_FLOAT:return _SC("float");
263         case _RT_BOOL:return _SC("bool");
264         case _RT_STRING:return _SC("string");
265         case _RT_TABLE:return _SC("table");
266         case _RT_ARRAY:return _SC("array");
267         case _RT_GENERATOR:return _SC("generator");
268         case _RT_CLOSURE:
269         case _RT_NATIVECLOSURE:
270                 return _SC("function");
271         case _RT_USERDATA:
272         case _RT_USERPOINTER:
273                 return _SC("userdata");
274         case _RT_THREAD: return _SC("thread");
275         case _RT_FUNCPROTO: return _SC("function");
276         case _RT_CLASS: return _SC("class");
277         case _RT_INSTANCE: return _SC("instance");
278         default:
279                 return NULL;
280         }
281 }
282
283 const SQChar *GetTypeName(const SQObjectPtr &obj1)
284 {
285         return IdType2Name(type(obj1)); 
286 }
287
288 void SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
289 {
290         if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
291                 Push(obj1);
292                 if(CallMetaMethod(_delegable(obj1),MT_TYPEOF,1,dest))
293                         return;
294         }
295         dest = SQString::Create(_ss(this),GetTypeName(obj1));
296 }
297
298 bool SQVM::Init(SQVM *friendvm, int stacksize)
299 {
300         _stack.resize(stacksize);
301         _callsstack.reserve(4);
302         _stackbase = 0;
303         _top = 0;
304         if(!friendvm) 
305                 _roottable = SQTable::Create(_ss(this), 0);
306         else {
307                 _roottable = friendvm->_roottable;
308                 _errorhandler = friendvm->_errorhandler;
309                 _debughook = friendvm->_debughook;
310         }
311         
312         sq_base_register(this);
313         return true;
314 }
315
316 extern SQInstructionDesc g_InstrDesc[];
317
318 bool SQVM::StartCall(SQClosure *closure,int target,int nargs,int stackbase,bool tailcall)
319 {
320         SQFunctionProto *func = _funcproto(closure->_function);
321         //const int outerssize = func->_outervalues.size();
322
323         const int paramssize = func->_parameters.size();
324         // const int oldtop = _top;
325         const int newtop = stackbase + func->_stacksize;
326         
327         
328         if(func->_varparams)
329         {
330                 if (nargs < paramssize) {
331                         Raise_Error(_SC("wrong number of parameters"));
332                         return false;
333                 }
334                 for(int n = 0; n < nargs - paramssize; n++) {
335                         _vargsstack.push_back(_stack[stackbase+paramssize+n]);
336                         _stack[stackbase+paramssize+n] = _null_;
337                 }
338         }
339         else {
340                 if (paramssize != nargs) {
341                         Raise_Error(_SC("wrong number of parameters"));
342                         return false;
343                 }
344                 
345         }
346         
347         if (!tailcall) {
348                 PUSH_CALLINFO(this, CallInfo());
349                 ci->_etraps = 0;
350                 ci->_prevstkbase = stackbase - _stackbase;
351                 ci->_target = target;
352                 ci->_prevtop = _top - _stackbase;
353                 ci->_ncalls = 1;
354                 ci->_root = false;
355         }
356         else {
357                 ci->_ncalls++;
358         }
359         ci->_vargs.size = (nargs - paramssize);
360         ci->_vargs.base = _vargsstack.size()-(nargs - paramssize);
361         ci->_closure._unVal.pClosure = closure;
362         ci->_closure._type = OT_CLOSURE;
363         ci->_iv = &func->_instructions;
364         ci->_literals = &func->_literals;
365         //grows the stack if needed
366         if (((unsigned int)newtop + (func->_stacksize<<1)) > _stack.size()) {
367                 _stack.resize(_stack.size() + (func->_stacksize<<1));
368         }
369                 
370         _top = newtop;
371         _stackbase = stackbase;
372         ci->_ip = ci->_iv->_vals;
373         return true;
374 }
375
376 bool SQVM::Return(int _arg0, int _arg1, SQObjectPtr &retval)
377 {
378         if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
379                 for(int i=0;i<ci->_ncalls;i++)
380                         CallDebugHook(_SC('r'));
381                                                 
382         bool broot = ci->_root;
383         int last_top = _top;
384         int target = ci->_target;
385         int oldstackbase = _stackbase;
386         _stackbase -= ci->_prevstkbase;
387         _top = _stackbase + ci->_prevtop;
388         PopVarArgs(ci->_vargs);
389         POP_CALLINFO(this);
390         if (broot) {
391                 if (_arg0 != MAX_FUNC_STACKSIZE) retval = _stack[oldstackbase+_arg1];
392                 else retval = _null_;
393         }
394         else {
395                 if (_arg0 != MAX_FUNC_STACKSIZE)
396                         STK(target) = _stack[oldstackbase+_arg1];
397                 else
398                         STK(target) = _null_;
399         }
400
401         while (last_top >= _top) _stack[last_top--].Null();
402         assert(oldstackbase >= _stackbase); 
403         return broot;
404 }
405
406 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
407
408 bool SQVM::LOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
409 {
410         _RET_ON_FAIL(ARITH_OP( op , target, a, incr));
411         a = target;
412         return true;
413 }
414
415 bool SQVM::PLOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
416 {
417         SQObjectPtr trg;
418         _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
419         target = a;
420         a = trg;
421         return true;
422 }
423
424 bool SQVM::DerefInc(int op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix)
425 {
426         SQObjectPtr tmp, tself = self, tkey = key;
427         if (!Get(tself, tkey, tmp, false, true)) { Raise_IdxError(tkey); return false; }
428         _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
429         Set(tself, tkey, target,true);
430         if (postfix) target = tmp;
431         return true;
432 }
433
434 #define arg0 (_i_._arg0)
435 #define arg1 (_i_._arg1)
436 #define sarg1 (*((int *)&_i_._arg1))
437 #define arg2 (_i_._arg2)
438 #define arg3 (_i_._arg3)
439 #define sarg3 (*((char *)&_i_._arg3))
440
441 SQRESULT SQVM::Suspend()
442 {
443         if (_suspended)
444                 return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
445         if (_nnativecalls!=2)
446                 return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
447         return SQ_SUSPEND_FLAG;
448 }
449
450 void SQVM::PopVarArgs(VarArgs &vargs)
451 {
452         for(int n = 0; n< vargs.size; n++)
453                 _vargsstack.pop_back();
454 }
455
456 #define _FINISH(stoploop) {finished = stoploop; return true; }
457 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr 
458 &o3,SQObjectPtr &o4,int arg_2,bool &finished)
459 {
460         int nrefidx;
461         switch(type(o1)) {
462         case OT_TABLE:
463                 if((nrefidx = _table(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
464                 o4 = (SQInteger)nrefidx; _FINISH(false);
465         case OT_ARRAY:
466                 if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
467                 o4 = (SQInteger) nrefidx; _FINISH(false);
468         case OT_STRING:
469                 if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
470                 o4 = (SQInteger)nrefidx; _FINISH(false);
471         case OT_CLASS:
472                 if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
473                 o4 = (SQInteger)nrefidx; _FINISH(false);
474         case OT_USERDATA:
475         case OT_INSTANCE:
476                 if(_delegable(o1)->_delegate) {
477                         SQObjectPtr itr;
478                         Push(o1);
479                         Push(o4);
480                         if(CallMetaMethod(_delegable(o1), MT_NEXTI, 2, itr)){
481                                 o4 = o2 = itr;
482                                 if(type(itr) == OT_NULL) _FINISH(true);
483                                 if(!Get(o1, itr, o3, false,false)) {
484                                         Raise_Error(_SC("_nexti returned an invalid idx"));
485                                         return false;
486                                 }
487                                 _FINISH(false);
488                         }
489                         Raise_Error(_SC("_nexti failed"));
490                         return false;
491                 }
492                 break;
493         case OT_GENERATOR:
494                 if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(true);
495                 if(_generator(o1)->_state == SQGenerator::eSuspended) {
496                         SQInteger idx = 0;
497                         if(type(o4) == OT_INTEGER) {
498                                 idx = _integer(o4) + 1;
499                         }
500                         o2 = idx;
501                         o4 = idx;
502                         _generator(o1)->Resume(this, arg_2+1);
503                         _FINISH(false);
504                 }
505         default:
506                 break;
507         }
508         Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
509         return false; //cannot be hit(just to avoid warnings)
510 }
511
512 bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2)
513 {
514         if(type(o1) != OT_TABLE) { Raise_Error(_SC("delegating a '%s'"), GetTypeName(o1)); return false; }
515         switch(type(o2)) {
516         case OT_TABLE:
517                 if(!_table(o1)->SetDelegate(_table(o2))){
518                         Raise_Error(_SC("delegate cycle detected"));
519                         return false;
520                 }
521                 break;
522         case OT_NULL:
523                 _table(o1)->SetDelegate(NULL);
524                 break;
525         default:
526                 Raise_Error(_SC("using '%s' as delegate"), GetTypeName(o2));
527                 return false;
528                 break;
529         }
530         trg = o1;
531         return true;
532 }
533 #define COND_LITERAL (arg3!=0?(*ci->_literals)[arg1]:STK(arg1))
534
535 #define _GUARD(exp) { if(!exp) { Raise_Error(_lasterror); SQ_THROW();} }
536
537 #define SQ_THROW() { goto exception_trap; }
538
539 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
540 {
541         int nouters;
542         SQClosure *closure = SQClosure::Create(_ss(this), func);
543         if( (nouters = func->_outervalues.size()) ) {
544                 closure->_outervalues.reserve(nouters);
545                 for(int i = 0; i<nouters; i++) {
546                         SQOuterVar &v = func->_outervalues[i];
547                         switch(v._type){
548                         case otSYMBOL:
549                                 closure->_outervalues.push_back(_null_);
550                                 if(!Get(_stack._vals[_stackbase]/*STK(0)*/, v._src, closure->_outervalues.top(), false,true))
551                                 {Raise_IdxError(v._src); return false; }
552                                 break;
553                         case otLOCAL:
554                                 closure->_outervalues.push_back(_stack._vals[_stackbase+_integer(v._src)]);
555                                 break;
556                         case otOUTER:
557                                 closure->_outervalues.push_back(_closure(ci->_closure)->_outervalues[_integer(v._src)]);
558                                 break;
559                         }
560                 }
561         }
562         target = closure;
563         return true;
564
565 }
566
567 bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci)
568 {
569         if(ci->_vargs.size == 0) {
570                 Raise_Error(_SC("the function doesn't have var args"));
571                 return false;
572         }
573         if(!sq_isnumeric(index)){
574                 Raise_Error(_SC("indexing 'vargv' with %s"),GetTypeName(index));
575                 return false;
576         }
577         int idx = tointeger(index);
578         if(idx < 0 || idx >= ci->_vargs.size){ Raise_Error(_SC("vargv index out of range")); return false; }
579         target = _vargsstack[ci->_vargs.base+idx];
580         return true;
581 }
582
583 bool SQVM::CLASS_OP(SQObjectPtr &target,int baseclass,int attributes)
584 {
585         SQClass *base = NULL;
586         SQObjectPtr attrs;
587         if(baseclass != MAX_LITERALS) {
588                 if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
589                 base = _class(_stack._vals[_stackbase + baseclass]);
590         }
591         if(attributes != MAX_FUNC_STACKSIZE) {
592                 attrs = _stack._vals[_stackbase+attributes];
593         }
594         target = SQClass::Create(_ss(this),base);
595         _class(target)->_attributes = attrs;
596         return true;
597 }
598
599 bool SQVM::IsFalse(SQObjectPtr &o)
600 {
601         SQObjectType t = type(o);
602         if((t & SQOBJECT_CANBEFALSE)
603                 && ((t == OT_NULL) || ((t == OT_INTEGER || t == OT_BOOL) && _integer(o) == 0)
604                 || (t == OT_FLOAT && _float(o) == SQFloat(0.0)))) {
605                         return true;
606                 }
607         return false;
608 }
609
610 bool SQVM::IsEqual(SQObjectPtr &o1,SQObjectPtr &o2,bool &res)
611 {
612         if(type(o1) == type(o2)) {
613                 res = ((_userpointer(o1) == _userpointer(o2)?true:false));
614         }
615         else {
616                 if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
617                         int cmpres;
618                         if(!ObjCmp(o1, o2,cmpres)) return false;
619                         res = (cmpres == 0);
620                 }
621                 else {
622                         res = false;
623                 }
624         }
625         return true;
626 }
627
628 bool SQVM::Execute(SQObjectPtr &closure, int target, int nargs, int stackbase,SQObjectPtr &outres, ExecutionType et)
629 {
630         if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
631         _nnativecalls++;
632         AutoDec ad(&_nnativecalls);
633         int traps = 0;
634         //temp_reg vars for OP_CALL
635         int ct_target;
636         bool ct_tailcall; 
637
638         switch(et) {
639                 case ET_CALL: 
640                         if(!StartCall(_closure(closure), _top - nargs, nargs, stackbase, false)) { 
641                                 //call the handler if there are no calls in the stack, if not relies on the previous node
642                                 if(ci == NULL) CallErrorHandler(_lasterror);
643                                 return false;
644                         }
645                         ci->_root = true;
646                         break;
647                 case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, target); ci->_root = true; traps += ci->_etraps; break;
648                 case ET_RESUME_VM:
649                         traps = _suspended_traps;
650                         ci->_root = _suspended_root;
651                         _suspended = false;
652                         break;
653         }
654         
655 exception_restore:
656         //SQ_TRY 
657         {
658                 for(;;)
659                 {
660                         const SQInstruction &_i_ = *ci->_ip++;
661                         //dumpstack(_stackbase);
662                         //scprintf("\n[%d] %s %d %d %d %d\n",ci->_ip-ci->_iv->_vals,g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
663                         switch(_i_.op)
664                         {
665                         case _OP_LINE:
666                                 if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
667                                         CallDebugHook(_SC('l'),arg1);
668                                 continue;
669                         case _OP_LOAD: TARGET = (*ci->_literals)[arg1]; continue;
670                         case _OP_TAILCALL:
671                                 temp_reg = STK(arg1);
672                                 if (type(temp_reg) == OT_CLOSURE){ 
673                                         ct_tailcall = true;
674                                         PopVarArgs(ci->_vargs);
675                                         for (int i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
676                                         ct_target = ci->_target;
677                                         goto common_call;
678                                 }
679                         case _OP_CALL: {
680                                         ct_tailcall = false;
681                                         ct_target = arg0;
682                                         temp_reg = STK(arg1);
683 common_call:
684                                         int last_top = _top;
685                                         switch (type(temp_reg)) {
686                                         case OT_CLOSURE:{
687                                                 StartCall(_closure(temp_reg), ct_target, arg3, ct_tailcall?_stackbase:_stackbase+arg2, ct_tailcall);
688                                                 if (_funcproto(_closure(temp_reg)->_function)->_bgenerator) {
689                                                         SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(temp_reg));
690                                                         _GUARD(gen->Yield(this));
691                                                         Return(1, ct_target, temp_reg);
692                                                         STK(ct_target) = gen;
693                                                         while (last_top >= _top) _stack[last_top--].Null();
694                                                         continue;
695                                                 }
696                                                 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
697                                                         CallDebugHook(_SC('c'));
698                                                 }
699                                                 break;
700                                         case OT_NATIVECLOSURE: {
701                                                 bool suspend;
702                                                 _GUARD(CallNative(_nativeclosure(temp_reg), arg3, _stackbase+arg2, ct_tailcall, temp_reg,suspend));
703                                                 if(suspend){
704                                                         _suspended = true;
705                                                         _suspended_target = ct_target;
706                                                         _suspended_root = ci->_root;
707                                                         _suspended_traps = traps;
708                                                         outres = temp_reg;
709                                                         return true;
710                                                 }
711                                                 STK(ct_target) = temp_reg;
712                                                                                    }
713                                                 break;
714                                         case OT_CLASS:{
715                                                 _GUARD(CreateClassInstance(_class(temp_reg),arg3,_stackbase+arg2,STK(ct_target)));
716                                                 }
717                                                 break;
718                                         case OT_TABLE:
719                                         case OT_USERDATA:
720                                         case OT_INSTANCE:
721                                                 {
722                                                 Push(temp_reg);
723                                                 for (int i = 0; i < arg3; i++) Push(STK(arg2 + i));
724                                                 if (_delegable(temp_reg) && CallMetaMethod(_delegable(temp_reg), MT_CALL, arg3+1, temp_reg)){
725                                                         STK(ct_target) = temp_reg;
726                                                         break;
727                                                 }
728                                                 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
729                                                 SQ_THROW();
730                                           }
731                                         default:
732                                                 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
733                                                 SQ_THROW();
734                                         }
735                                 }
736                                   continue;
737                         case _OP_PREPCALL:
738                                         if (!Get(STK(arg2), STK(arg1), temp_reg, false,true))
739                                         { Raise_IdxError(STK(arg1)); SQ_THROW(); }
740                                         goto common_prepcall;
741                         case _OP_PREPCALLK:
742                                         if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg,false,true)) {
743                                                 if(type(STK(arg2)) == OT_CLASS) { //hack?
744                                                         if(_class_ddel->Get((*ci->_literals)[arg1],temp_reg)) {
745                                                                 STK(arg3) = STK(arg2);
746                                                                 TARGET = temp_reg;
747                                                                 continue;
748                                                         }
749                                                 }
750                                                 { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
751                                         }
752 common_prepcall:
753                                         if(type(STK(arg2)) == OT_CLASS) {
754                                                 STK(arg3) = STK(0); // this
755                                         }
756                                         else {
757                                                 STK(arg3) = STK(arg2);
758                                         }
759                                         TARGET = temp_reg;
760                                 continue;
761                         case _OP_GETK:
762                                 if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg, false,true)) { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
763                                 TARGET = temp_reg;
764                                 continue;
765                         case _OP_MOVE: TARGET = STK(arg1); continue;
766                         case _OP_NEWSLOT:
767                                 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
768                                 if(arg0 != arg3) TARGET = STK(arg3);
769                                 continue;
770                         case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
771                         case _OP_SET:
772                                 if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
773                                 if (arg0 != arg3) TARGET = STK(arg3);
774                                 continue;
775                         case _OP_GET:
776                                 if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
777                                 TARGET = temp_reg;
778                                 continue;
779                         case _OP_EQ:{
780                                 bool res;
781                                 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
782                                 TARGET = res?_true_:_false_;
783                                 }continue;
784                         case _OP_NE:{ 
785                                 bool res;
786                                 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
787                                 TARGET = (!res)?_true_:_false_;
788                                 } continue;
789                         case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
790                         case _OP_BITW:  _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
791                         case _OP_RETURN:
792                                 if(type((ci)->_generator) == OT_GENERATOR) {
793                                         _generator((ci)->_generator)->Kill();
794                                 }
795                                 if(Return(arg0, arg1, temp_reg)){
796                                         assert(traps==0);
797                                         outres = temp_reg;
798                                         return true;
799                                 }
800                                 continue;
801                         case _OP_LOADNULLS:{ for(unsigned int n=0;n<arg1;n++) STK(arg0+n) = _null_; }continue;
802                         case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
803                         case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
804                         case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
805                         case _OP_JMP: ci->_ip += (sarg1); continue;
806                         case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
807                         case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
808                         case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
809                         case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
810                         case _OP_GETVARGV: 
811                                 if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); } 
812                                 continue;
813                         case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
814                         case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
815                         case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL);  continue;
816                         case _OP_GETPARENT:
817                                 switch(type(STK(arg1))) {
818                                 case OT_TABLE: 
819                         TARGET = _table(STK(arg1))->_delegate?SQObjectPtr(_table(STK(arg1))->_delegate):_null_;
820                                         continue;
821                                 case OT_CLASS: TARGET = _class(STK(arg1))->_base?_class(STK(arg1))->_base:_null_;
822                                         continue;
823                                 default:
824                                         break;
825                                 }
826                                 Raise_Error(_SC("the %s type doesn't have a parent slot"), GetTypeName(STK(arg1)));
827                                 SQ_THROW();
828                                 continue;
829                         case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((unsigned int)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
830                         case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
831                         case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
832                         case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
833                         case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
834                         case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
835                         case _OP_CMP:   _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET))  continue;
836                         case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
837                         case _OP_INSTANCEOF: 
838                                 if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
839                                 {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
840                                 TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
841                                 continue;
842                         case _OP_AND: 
843                                 if(IsFalse(STK(arg2))) {
844                                         TARGET = STK(arg2);
845                                         ci->_ip += (sarg1);
846                                 }
847                                 continue;
848                         case _OP_OR:
849                                 if(!IsFalse(STK(arg2))) {
850                                         TARGET = STK(arg2);
851                                         ci->_ip += (sarg1);
852                                 }
853                                 continue;
854                         case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
855                         case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
856                         case _OP_BWNOT:
857                                 if(type(STK(arg1)) == OT_INTEGER) {
858                                         TARGET = SQInteger(~_integer(STK(arg1)));
859                                         continue;
860                                 }
861                                 Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
862                                 SQ_THROW();
863                         case _OP_CLOSURE: {
864                                 SQClosure *c = ci->_closure._unVal.pClosure;
865                                 SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
866                                 if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
867                                 continue;
868                         }
869                         case _OP_YIELD:{
870                                 if(type(ci->_generator) == OT_GENERATOR) {
871                                         if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
872                                         _GUARD(_generator(ci->_generator)->Yield(this));
873                                         traps -= ci->_etraps;
874                                         if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
875                                 }
876                                 else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
877                                 if(Return(arg0, arg1, temp_reg)){
878                                         assert(traps==0);
879                                         outres = temp_reg;
880                                         return true;
881                                 }
882                                         
883                                 }
884                                 continue;
885                         case _OP_RESUME:
886                                 if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
887                                 _GUARD(_generator(STK(arg1))->Resume(this, arg0));
888                                 traps += ci->_etraps;
889                 continue;
890                         case _OP_FOREACH:{ bool finished;
891                                 _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,finished));
892                                 if(finished) ci->_ip += sarg1; }
893                                 continue;
894                         case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
895                         case _OP_CLONE:
896                                 if(!Clone(STK(arg1), TARGET))
897                                 { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
898                                 continue;
899                         case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
900                         case _OP_PUSHTRAP:
901                                 _etraps.push_back(SQExceptionTrap(_top,_stackbase, &ci->_iv->_vals[(ci->_ip-ci->_iv->_vals)+arg1], arg0)); traps++;
902                                 ci->_etraps++;
903                                 continue;
904                         case _OP_POPTRAP:{
905                                 for(int i=0; i<arg0; i++) {
906                                         _etraps.pop_back(); traps--;
907                                         ci->_etraps--;
908                                 }}
909                                 continue;
910                         case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
911                         case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
912                         case _OP_NEWSLOTA:
913                                 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
914                                 _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
915                                 if(arg0 != arg3) TARGET = STK(arg3);
916                                 continue;
917                         }
918                         
919                 }
920         }
921 exception_trap:
922         {
923                 SQObjectPtr currerror = _lasterror;
924 //              dumpstack(_stackbase);
925                 int n = 0;
926                 int last_top = _top;
927                 if(ci) {
928                         if(traps) {
929                                 do {
930                                         if(ci->_etraps > 0) {
931                                                 SQExceptionTrap &et = _etraps.top();
932                                                 ci->_ip = et._ip;
933                                                 _top = et._stacksize;
934                                                 _stackbase = et._stackbase;
935                                                 _stack[_stackbase+et._extarget] = currerror;
936                                                 _etraps.pop_back(); traps--; ci->_etraps--;
937                                                 while(last_top >= _top) _stack[last_top--].Null();
938                                                 goto exception_restore;
939                                         }
940                                         //if is a native closure
941                                         if(type(ci->_closure) != OT_CLOSURE && n)
942                                                 break;
943                                         if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
944                                         PopVarArgs(ci->_vargs);
945                                         POP_CALLINFO(this);
946                                         n++;
947                                 }while(_callsstack.size());
948                         }
949                         //call the hook
950                         CallErrorHandler(currerror);
951                         //remove call stack until a C function is found or the cstack is empty
952                         if(ci) do{
953                                 bool exitafterthisone = ci->_root;
954                                 if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
955                                 _stackbase -= ci->_prevstkbase;
956                                 _top = _stackbase + ci->_prevtop;
957                                 PopVarArgs(ci->_vargs);
958                                 POP_CALLINFO(this);
959                                 if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
960                         }while(_callsstack.size());
961
962                         while(last_top >= _top) _stack[last_top--].Null();
963                 }
964                 _lasterror = currerror;
965                 return false;
966         }
967         assert(0);
968 }
969
970 bool SQVM::CreateClassInstance(SQClass *theclass, int nargs, int stackbase, SQObjectPtr &retval)
971 {
972         SQObjectPtr constr;
973         SQObjectPtr inst = theclass->CreateInstance();
974         _stack[stackbase] = inst;
975         if(theclass->Get(_ss(this)->_constructoridx,constr)) {
976                 if(!Call(constr,nargs,stackbase,constr))
977                         return false;
978         }
979         retval = inst;
980         return true;
981 }
982
983 void SQVM::CallErrorHandler(SQObjectPtr &error)
984 {
985         if(type(_errorhandler) != OT_NULL) {
986                 SQObjectPtr out;
987                 Push(_roottable); Push(error);
988                 Call(_errorhandler, 2, _top-2, out);
989                 Pop(2);
990         }
991 }
992
993 void SQVM::CallDebugHook(int type,int forcedline)
994 {
995         SQObjectPtr temp_reg;
996         int nparams=5;
997         SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
998         Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
999         Call(_debughook,nparams,_top-nparams,temp_reg);
1000         Pop(nparams);
1001 }
1002
1003 bool SQVM::CallNative(SQNativeClosure *nclosure,int nargs,int stackbase,bool tailcall,SQObjectPtr &retval,bool &suspend)
1004 {
1005         (void) tailcall;
1006         if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
1007         int nparamscheck = nclosure->_nparamscheck;
1008         if(((nparamscheck > 0) && (nparamscheck != nargs))
1009                 || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
1010                 Raise_Error(_SC("wrong number of parameters"));
1011                 return false;
1012                 }
1013
1014         int tcs;
1015         if( (tcs = nclosure->_typecheck.size()) ) {
1016                 for(int i = 0; i < nargs && i < tcs; i++)
1017                         if((nclosure->_typecheck[i] != -1) && !(type(_stack[stackbase+i]) & nclosure->_typecheck[i])) {
1018                 Raise_ParamTypeError(i,nclosure->_typecheck[i],type(_stack[stackbase+i]));
1019                                 return false;
1020                         }
1021         }
1022         _nnativecalls++;
1023         if ((_top + MIN_STACK_OVERHEAD) > (int)_stack.size()) {
1024                 _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
1025         }
1026         int oldtop = _top;
1027         int oldstackbase = _stackbase;
1028         _top = stackbase + nargs;
1029         PUSH_CALLINFO(this, CallInfo());
1030         ci->_etraps = 0;
1031         ci->_closure._unVal.pNativeClosure = nclosure;
1032         ci->_closure._type = OT_NATIVECLOSURE;
1033         ci->_prevstkbase = stackbase - _stackbase;
1034         ci->_ncalls = 1;
1035         _stackbase = stackbase;
1036         //push free variables
1037         int outers = nclosure->_outervalues.size();
1038         for (int i = 0; i < outers; i++) {
1039                 Push(nclosure->_outervalues[i]);
1040         }
1041         ci->_prevtop = (oldtop - oldstackbase);
1042         int ret = (nclosure->_function)(this);
1043         _nnativecalls--;
1044         suspend = false;
1045         if( ret == SQ_SUSPEND_FLAG) suspend = true;
1046         else if (ret < 0) { 
1047                 _stackbase = oldstackbase;
1048                 _top = oldtop;
1049                 POP_CALLINFO(this);
1050                 Raise_Error(_lasterror);
1051                 return false;
1052         }
1053         
1054         if (ret != 0){ retval = TOP(); }
1055         else { retval = _null_; }
1056         _stackbase = oldstackbase;
1057         _top = oldtop;
1058         POP_CALLINFO(this);
1059         return true;
1060 }
1061
1062 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
1063 {
1064         switch(type(self)){
1065         case OT_TABLE:
1066                 if(_table(self)->Get(key,dest))return true;
1067                 break;
1068         case OT_ARRAY:
1069                 if(sq_isnumeric(key)){
1070                         return _array(self)->Get(tointeger(key),dest);
1071                 }
1072                 break;
1073         case OT_INSTANCE:
1074                 if(_instance(self)->Get(key,dest)) return true;
1075                 break;
1076         default:
1077                 break;
1078         }
1079         if(FallBackGet(self,key,dest,raw)) return true;
1080
1081         if(fetchroot) {
1082                 if(_rawval(STK(0)) == _rawval(self) &&
1083                         type(STK(0)) == type(self)) {
1084                                 return _table(_roottable)->Get(key,dest);
1085                 }
1086         }
1087         return false;
1088 }
1089
1090 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
1091 {
1092         switch(type(self)){
1093         case OT_CLASS: 
1094                 return _class(self)->Get(key,dest);
1095                 break;
1096         case OT_TABLE:
1097         case OT_USERDATA:
1098         //delegation
1099                 if(_delegable(self)->_delegate) {
1100                         if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
1101                                 return true;    
1102                         if(raw)return false;
1103                         Push(self);Push(key);
1104                         if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
1105                                 return true;
1106                 }
1107                 if(type(self) == OT_TABLE) {
1108                         if(raw) return false;
1109                         return _table_ddel->Get(key,dest);
1110                 }
1111                 return false;
1112                 break;
1113         case OT_ARRAY:
1114                 if(raw)return false;
1115                 return _array_ddel->Get(key,dest);
1116         case OT_STRING:
1117                 if(sq_isnumeric(key)){
1118                         SQInteger n=tointeger(key);
1119                         if(abs(n)<_string(self)->_len){
1120                                 if(n<0)n=_string(self)->_len-n;
1121                                 dest=SQInteger(_stringval(self)[n]);
1122                                 return true;
1123                         }
1124                         return false;
1125                 }
1126                 else {
1127                         if(raw)return false;
1128                         return _string_ddel->Get(key,dest);
1129                 }
1130                 break;
1131         case OT_INSTANCE:
1132                 if(raw)return false;
1133                 Push(self);Push(key);
1134                 if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
1135                         return _instance_ddel->Get(key,dest);
1136                 }
1137                 return true;
1138         case OT_INTEGER:case OT_FLOAT:case OT_BOOL: 
1139                 if(raw)return false;
1140                 return _number_ddel->Get(key,dest);
1141         case OT_GENERATOR: 
1142                 if(raw)return false;
1143                 return _generator_ddel->Get(key,dest);
1144         case OT_CLOSURE: case OT_NATIVECLOSURE: 
1145                 if(raw)return false;
1146                 return _closure_ddel->Get(key,dest);
1147         case OT_THREAD:
1148                 if(raw)return false;
1149                 return  _thread_ddel->Get(key,dest);
1150         default:return false;
1151         }
1152         return false;
1153 }
1154
1155 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
1156 {
1157         switch(type(self)){
1158         case OT_TABLE:
1159                 if(_table(self)->Set(key,val))
1160                         return true;
1161                 if(_table(self)->_delegate) {
1162                         if(Set(_table(self)->_delegate,key,val,false)) {
1163                                 return true;
1164                         }
1165                 }
1166                 //keeps going
1167         case OT_USERDATA:
1168                 if(_delegable(self)->_delegate) {
1169                         SQObjectPtr t;
1170                         Push(self);Push(key);Push(val);
1171                         if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1172                 }
1173                 break;
1174         case OT_INSTANCE:{
1175                 if(_instance(self)->Set(key,val))
1176                         return true;
1177                 SQObjectPtr t;
1178                 Push(self);Push(key);Push(val);
1179                 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1180                 }
1181                 break;
1182         case OT_ARRAY:
1183                 if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
1184                 return _array(self)->Set(tointeger(key),val);
1185         default:
1186                 Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
1187                 return false;
1188         }
1189         if(fetchroot) {
1190                 if(_rawval(STK(0)) == _rawval(self) &&
1191                         type(STK(0)) == type(self)) {
1192                                 return _table(_roottable)->Set(key,val);
1193                         }
1194         }
1195         return false;
1196 }
1197
1198 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
1199 {
1200         SQObjectPtr temp_reg;
1201         switch(type(self)){
1202         case OT_TABLE:
1203                 target = _table(self)->Clone();
1204                 goto cloned_mt;
1205         case OT_INSTANCE:
1206                 target = _instance(self)->Clone(_ss(this));
1207 cloned_mt:
1208                 if(_delegable(target)->_delegate){
1209                         Push(target);
1210                         Push(self);
1211                         CallMetaMethod(_delegable(target),MT_CLONED,2,temp_reg);
1212                 }
1213                 return true;
1214         case OT_ARRAY: 
1215                 target=_array(self)->Clone();
1216                 return true;
1217         default: return false;
1218         }
1219 }
1220
1221 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val)
1222 {
1223         if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
1224         switch(type(self)) {
1225         case OT_TABLE: {
1226                 bool rawcall = true;
1227                 if(_table(self)->_delegate) {
1228                         SQObjectPtr res;
1229                         if(!_table(self)->Get(key,res)) {
1230                                 Push(self);Push(key);Push(val);
1231                                 rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
1232                         }
1233                 }
1234                 if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
1235                 
1236                 break;}
1237         case OT_CLASS: 
1238                 if(!_class(self)->NewSlot(key,val)) {
1239                         if(_class(self)->_locked) {
1240                                 Raise_Error(_SC("trying to modify a class that has already been instantiated"));
1241                                 return false;
1242                         }
1243                         else {
1244                                 SQObjectPtr oval = PrintObjVal(key);
1245                                 Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
1246                                 return false;
1247                         }
1248                 }
1249                 break;
1250         default:
1251                 Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
1252                 return false;
1253                 break;
1254         }
1255         return true;
1256 }
1257
1258 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
1259 {
1260         switch(type(self)) {
1261         case OT_TABLE:
1262         case OT_INSTANCE:
1263         case OT_USERDATA: {
1264                 SQObjectPtr t;
1265                 bool handled = false;
1266                 if(_delegable(self)->_delegate) {
1267                         Push(self);Push(key);
1268                         handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
1269                 }
1270
1271                 if(!handled) {
1272                         if(type(self) == OT_TABLE) {
1273                                 if(_table(self)->Get(key,t)) {
1274                                         _table(self)->Remove(key);
1275                                 }
1276                                 else {
1277                                         Raise_IdxError((SQObject &)key);
1278                                         return false;
1279                                 }
1280                         }
1281                         else {
1282                                 Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
1283                                 return false;
1284                         }
1285                 }
1286                 res = t;
1287                                 }
1288                 break;
1289         default:
1290                 Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
1291                 return false;
1292         }
1293         return true;
1294 }
1295
1296 bool SQVM::Call(SQObjectPtr &closure,int nparams,int stackbase,SQObjectPtr &outres)
1297 {
1298 #ifdef _DEBUG
1299 int prevstackbase = _stackbase;
1300 #endif
1301         switch(type(closure)) {
1302         case OT_CLOSURE:
1303                 return Execute(closure, _top - nparams, nparams, stackbase,outres);
1304                 break;
1305         case OT_NATIVECLOSURE:{
1306                 bool suspend;
1307                 return CallNative(_nativeclosure(closure), nparams, stackbase, false, outres,suspend);
1308                 
1309                                                   }
1310                 break;
1311         case OT_CLASS:
1312                 return CreateClassInstance(_class(closure),nparams,stackbase,outres);
1313                 break;
1314         default:
1315                 return false;
1316         }
1317 #ifdef _DEBUG
1318         if(!_suspended) {
1319                 assert(_stackbase == prevstackbase);
1320         }
1321 #endif
1322         return true;
1323 }
1324
1325 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,int nparams,SQObjectPtr &outres)
1326 {
1327         SQObjectPtr closure;
1328         if(del->GetMetaMethod(mm, closure)) {
1329                 if(Call(closure, nparams, _top - nparams, outres)) {
1330                         Pop(nparams);
1331                         return true;
1332                 }
1333         }
1334         Pop(nparams);
1335         return false;
1336 }
1337
1338 void SQVM::Pop() {
1339         _stack[--_top] = _null_;
1340 }
1341 void SQVM::Pop(int n) {
1342         for(int i = 0; i < n; i++){
1343                 _stack[--_top] = _null_;
1344         }
1345 }
1346
1347 void SQVM::Remove(int n) {
1348         n = (n >= 0)?n + _stackbase - 1:_top + n;
1349         for(int i = n; i < _top; i++){
1350                 _stack[i] = _stack[i+1];
1351         }
1352         _stack[_top] = _null_;
1353         _top--;
1354 }
1355
1356 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
1357 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
1358 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
1359 SQObjectPtr &SQVM::GetUp(int n) { return _stack[_top+n]; }
1360 SQObjectPtr &SQVM::GetAt(int n) { return _stack[n]; }
1361
1362 #ifdef _DEBUG_DUMP
1363 void SQVM::dumpstack(int stackbase,bool dumpall)
1364 {
1365         int size=dumpall?_stack.size():_top;
1366         int n=0;
1367         scprintf(_SC("\n>>>>stack dump<<<<\n"));
1368         CallInfo &ci=_callsstack.back();
1369         scprintf(_SC("IP: %d\n"),ci._ip);
1370         scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
1371         scprintf(_SC("prev top: %d\n"),ci._prevtop);
1372         for(int i=0;i<size;i++){
1373                 SQObjectPtr &obj=_stack[i];     
1374                 if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
1375                 scprintf(_SC("[%d]:"),n);
1376                 switch(type(obj)){
1377                 case OT_FLOAT:                  scprintf(_SC("FLOAT %.3f"),_float(obj));break;
1378                 case OT_INTEGER:                scprintf(_SC("INTEGER %d"),_integer(obj));break;
1379                 case OT_BOOL:                   scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
1380                 case OT_STRING:                 scprintf(_SC("STRING %s"),_stringval(obj));break;
1381                 case OT_NULL:                   scprintf(_SC("NULL"));  break;
1382                 case OT_TABLE:                  scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
1383                 case OT_ARRAY:                  scprintf(_SC("ARRAY %p"),_array(obj));break;
1384                 case OT_CLOSURE:                scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
1385                 case OT_NATIVECLOSURE:  scprintf(_SC("NATIVECLOSURE"));break;
1386                 case OT_USERDATA:               scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
1387                 case OT_GENERATOR:              scprintf(_SC("GENERATOR"));break;
1388                 case OT_THREAD:                 scprintf(_SC("THREAD [%p]"),_thread(obj));break;
1389                 case OT_USERPOINTER:    scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
1390                 case OT_CLASS:                  scprintf(_SC("CLASS %p"),_class(obj));break;
1391                 case OT_INSTANCE:               scprintf(_SC("INSTANCE %p"),_instance(obj));break;
1392                 default:
1393                         assert(0);
1394                         break;
1395                 };
1396                 scprintf(_SC("\n"));
1397                 ++n;
1398         }
1399 }
1400
1401 #endif