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