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