# sqvm.cpp

    00001 /*
    00002   see copyright notice in squirrel.h
    00003 */
    00004 #include <squirrel.h>
    00005 #include "sqpcheader.h"
    00006 #include <math.h>
    00007 #include <stdlib.h>
    00008 #include "sqopcodes.h"
    00009 #include "sqfuncproto.h"
    00010 #include "sqvm.h"
    00011 #include "sqclosure.h"
    00012 #include "sqstring.h"
    00013 #include "sqtable.h"
    00014 #include "squserdata.h"
    00015 #include "sqarray.h"
    00016 #include "sqclass.h"
    00017
    00018 #define TOP() (_stack._vals[_top-1])
    00019
    00020 bool SQVM::BW_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
    00021 {
    00022   SQInteger res;
    00023   SQInteger i1 = _integer(o1), i2 = _integer(o2);
    00024   if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER))
    00025   {
    00026     switch(op) {
    00027       case BW_AND:  res = i1 & i2; break;
    00028       case BW_OR:   res = i1 | i2; break;
    00029       case BW_XOR:  res = i1 ^ i2; break;
    00030       case BW_SHIFTL: res = i1 << i2; break;
    00031       case BW_SHIFTR: res = i1 >> i2; break;
    00032       case BW_USHIFTR:res = (SQInteger)(*((SQUnsignedInteger*)&i1) >> i2); break;
    00033       default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; }
    00034     }
    00035   }
    00036   else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),GetTypeName(o1),GetTypeName(o2)); return false;}
    00037   trg = res;
    00038   return true;
    00039 }
    00040
    00041 bool SQVM::ARITH_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
    00042 {
    00043   if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
    00044       if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER)) {
    00045         SQInteger res, i1 = _integer(o1), i2 = _integer(o2);
    00046         switch(op) {
    00047         case '+': res = i1 + i2; break;
    00048         case '-': res = i1 - i2; break;
    00049         case '/': if(i2 == 0) { Raise_Error(_SC("division by zero")); return false; }
    00050           res = i1 / i2;
    00051           break;
    00052         case '*': res = i1 * i2; break;
    00053         case '%': res = i1 % i2; break;
    00054         default: res = 0xDEADBEEF;
    00055         }
    00056         trg = res;
    00057       }else{
    00058         SQFloat res, f1 = tofloat(o1), f2 = tofloat(o2);
    00059         switch(op) {
    00060         case '+': res = f1 + f2; break;
    00061         case '-': res = f1 - f2; break;
    00062         case '/': res = f1 / f2; break;
    00063         case '*': res = f1 * f2; break;
    00064         case '%': res = SQFloat(fmod((double)f1,(double)f2)); break;
    00065         default: res = 0x0f;
    00066         }
    00067         trg = res;
    00068       }
    00069     } else {
    00070       if(op == '+' && (type(o1) == OT_STRING || type(o2) == OT_STRING)){
    00071           if(!StringCat(o1, o2, trg)) return false;
    00072       }
    00073       else if(!ArithMetaMethod(op,o1,o2,trg)) {
    00074         Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2)); return false;
    00075       }
    00076     }
    00077     return true;
    00078 }
    00079
    00080 SQVM::SQVM(SQSharedState *ss)
    00081 {
    00082   _sharedstate=ss;
    00083   _suspended = SQFalse;
    00084   _suspended_target=-1;
    00085   _suspended_root = SQFalse;
    00086   _suspended_traps=-1;
    00087   _foreignptr=NULL;
    00088   _nnativecalls=0;
    00089   _lasterror = _null_;
    00090   _errorhandler = _null_;
    00091   _debughook = _null_;
    00092   _can_suspend = false;
    00093   _ops_till_suspend = 0;
    00094   ci = NULL;
    00095   INIT_CHAIN();ADD_TO_CHAIN(&_ss(this)->_gc_chain,this);
    00096 }
    00097
    00098 void SQVM::Finalize()
    00099 {
    00100   _roottable = _null_;
    00101   _lasterror = _null_;
    00102   _errorhandler = _null_;
    00103   _debughook = _null_;
    00104   temp_reg = _null_;
    00105   _callstackdata.resize(0);
    00106   SQInteger size=_stack.size();
    00107   for(SQInteger i=size - 1;i>=0;i--)
    00108     _stack[i]=_null_;
    00109 }
    00110
    00111 SQVM::~SQVM()
    00112 {
    00113   Finalize();
    00114   //sq_free(_callsstack,_alloccallsstacksize*sizeof(CallInfo));
    00115   REMOVE_FROM_CHAIN(&_ss(this)->_gc_chain,this);
    00116 }
    00117
    00118 bool SQVM::ArithMetaMethod(SQInteger op,const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &dest)
    00119 {
    00120   SQMetaMethod mm;
    00121   switch(op){
    00122     case _SC('+'): mm=MT_ADD; break;
    00123     case _SC('-'): mm=MT_SUB; break;
    00124     case _SC('/'): mm=MT_DIV; break;
    00125     case _SC('*'): mm=MT_MUL; break;
    00126     case _SC('%'): mm=MT_MODULO; break;
    00127     default: mm = MT_ADD; assert(0); break; //shutup compiler
    00128   }
    00129   if(is_delegable(o1) && _delegable(o1)->_delegate) {
    00130     Push(o1);Push(o2);
    00131     return CallMetaMethod(_delegable(o1),mm,2,dest);
    00132   }
    00133   return false;
    00134 }
    00135
    00136 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
    00137 {
    00138
    00139   switch(type(o)) {
    00140   case OT_INTEGER:
    00141     trg = -_integer(o);
    00142     return true;
    00143   case OT_FLOAT:
    00144     trg = -_float(o);
    00145     return true;
    00146   case OT_TABLE:
    00147   case OT_USERDATA:
    00148   case OT_INSTANCE:
    00149     if(_delegable(o)->_delegate) {
    00150       Push(o);
    00151       if(CallMetaMethod(_delegable(o), MT_UNM, 1, temp_reg)) {
    00152         trg = temp_reg;
    00153         return true;
    00154       }
    00155     }
    00156   default:break; //shutup compiler
    00157   }
    00158   Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
    00159   return false;
    00160 }
    00161
    00162 #define _RET_SUCCEED(exp) { result = (exp); return true; }
    00163 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,SQInteger &result)
    00164 {
    00165   if(type(o1)==type(o2)){
    00166     if(_userpointer(o1)==_userpointer(o2))_RET_SUCCEED(0);
    00167     SQObjectPtr res;
    00168     switch(type(o1)){
    00169     case OT_STRING:
    00170       _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
    00171     case OT_INTEGER:
    00172       _RET_SUCCEED(_integer(o1)-_integer(o2));
    00173     case OT_FLOAT:
    00174       _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
    00175     case OT_TABLE:
    00176     case OT_USERDATA:
    00177     case OT_INSTANCE:
    00178       if(_delegable(o1)->_delegate) {
    00179         Push(o1);Push(o2);
    00180         if(CallMetaMethod(_delegable(o1),MT_CMP,2,res)) break;
    00181       }
    00182       //continues through (no break needed)
    00183     default:
    00184       _RET_SUCCEED( _userpointer(o1) < _userpointer(o2)?-1:1 );
    00185     }
    00186     if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
    00187       _RET_SUCCEED(_integer(res));
    00188
    00189   }
    00190   else{
    00191     if(sq_isnumeric(o1) && sq_isnumeric(o2)){
    00192       if((type(o1)==OT_INTEGER) && (type(o2)==OT_FLOAT)) {
    00193         if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
    00194         else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
    00195         _RET_SUCCEED(1);
    00196       }
    00197       else{
    00198         if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
    00199         else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
    00200         _RET_SUCCEED(1);
    00201       }
    00202     }
    00203     else if(type(o1)==OT_NULL) {_RET_SUCCEED(-1);}
    00204     else if(type(o2)==OT_NULL) {_RET_SUCCEED(1);}
    00205     else { Raise_CompareError(o1,o2); return false; }
    00206
    00207   }
    00208   assert(0);
    00209   _RET_SUCCEED(0); //cannot happen
    00210 }
    00211
    00212 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
    00213 {
    00214   SQInteger r;
    00215   if(ObjCmp(o1,o2,r)) {
    00216     switch(op) {
    00217       case CMP_G: res = (r > 0)?_true_:_false_; return true;
    00218       case CMP_GE: res = (r >= 0)?_true_:_false_; return true;
    00219       case CMP_L: res = (r < 0)?_true_:_false_; return true;
    00220       case CMP_LE: res = (r <= 0)?_true_:_false_; return true;
    00221
    00222     }
    00223     assert(0);
    00224   }
    00225   return false;
    00226 }
    00227
    00228 void SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res)
    00229 {
    00230   switch(type(o)) {
    00231   case OT_STRING:
    00232     res = o;
    00233     return;
    00234   case OT_FLOAT:
    00235     scsprintf(_sp(rsl(NUMBER_MAX_CHAR+1)),_SC("%g"),_float(o));
    00236     break;
    00237   case OT_INTEGER:
    00238 #if defined(_SQ64)
    00239     scsprintf(_sp(rsl(NUMBER_MAX_CHAR+1)),_SC("%ld"),_integer(o));
    00240 #else
    00241     scsprintf(_sp(rsl(NUMBER_MAX_CHAR+1)),_SC("%d"),_integer(o));
    00242 #endif
    00243     break;
    00244   case OT_BOOL:
    00245     scsprintf(_sp(rsl(6)),_integer(o)?_SC("true"):_SC("false"));
    00246     break;
    00247   case OT_TABLE:
    00248   case OT_USERDATA:
    00249   case OT_INSTANCE:
    00250     if(_delegable(o)->_delegate) {
    00251       Push(o);
    00252       if(CallMetaMethod(_delegable(o),MT_TOSTRING,1,res)) {
    00253         if(type(res) == OT_STRING)
    00254           return;
    00255         //else keeps going to the default
    00256       }
    00257     }
    00258   default:
    00259     scsprintf(_sp(rsl(sizeof(void*)+20)),_SC("(%s : 0x%p)"),GetTypeName(o),(void*)_rawval(o));
    00260   }
    00261   res = SQString::Create(_ss(this),_spval);
    00262 }
    00263
    00264
    00265 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
    00266 {
    00267   SQObjectPtr a, b;
    00268   ToString(str, a);
    00269   ToString(obj, b);
    00270   SQInteger l = _string(a)->_len , ol = _string(b)->_len;
    00271   SQChar *s = _sp(rsl(l + ol + 1));
    00272   memcpy(s, _stringval(a), rsl(l));
    00273   memcpy(s + l, _stringval(b), rsl(ol));
    00274   dest = SQString::Create(_ss(this), _spval, l + ol);
    00275   return true;
    00276 }
    00277
    00278 void SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
    00279 {
    00280   if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
    00281     Push(obj1);
    00282     if(CallMetaMethod(_delegable(obj1),MT_TYPEOF,1,dest))
    00283       return;
    00284   }
    00285   dest = SQString::Create(_ss(this),GetTypeName(obj1));
    00286 }
    00287
    00288 bool SQVM::Init(SQVM *friendvm, SQInteger stacksize)
    00289 {
    00290   _stack.resize(stacksize);
    00291   //_callsstack.reserve(4);
    00292   _alloccallsstacksize = 4;
    00293   _callstackdata.resize(_alloccallsstacksize);
    00294   _callsstacksize = 0;
    00295   _callsstack = &_callstackdata[0];
    00296   //_callsstack = (CallInfo*)sq_malloc(_alloccallsstacksize*sizeof(CallInfo));
    00297   _stackbase = 0;
    00298   _top = 0;
    00299   if(!friendvm)
    00300     _roottable = SQTable::Create(_ss(this), 0);
    00301   else {
    00302     _roottable = friendvm->_roottable;
    00303     _errorhandler = friendvm->_errorhandler;
    00304     _debughook = friendvm->_debughook;
    00305   }
    00306
    00307   sq_base_register(this);
    00308   return true;
    00309 }
    00310
    00311 extern SQInstructionDesc g_InstrDesc[];
    00312
    00313 bool SQVM::StartCall(SQClosure *closure,SQInteger target,SQInteger args,SQInteger stackbase,bool tailcall)
    00314 {
    00315   SQFunctionProto *func = _funcproto(closure->_function);
    00316
    00317   const SQInteger paramssize = func->_nparameters;
    00318   const SQInteger newtop = stackbase + func->_stacksize;
    00319   SQInteger nargs = args;
    00320   if (paramssize != nargs) {
    00321     SQInteger ndef = func->_ndefaultparams;
    00322     if(ndef && nargs < paramssize) {
    00323       SQInteger diff = paramssize - nargs;
    00324       for(SQInteger n = ndef - diff; n < ndef; n++) {
    00325         _stack._vals[stackbase + (nargs++)] = closure->_defaultparams[n];
    00326       }
    00327     }
    00328     else if(func->_varparams)
    00329     {
    00330       if (nargs < paramssize) {
    00331         Raise_Error(_SC("wrong number of parameters"));
    00332         return false;
    00333       }
    00334       for(SQInteger n = 0; n < nargs - paramssize; n++) {
    00335         _vargsstack.push_back(_stack._vals[stackbase+paramssize+n]);
    00336         _stack._vals[stackbase+paramssize+n] = _null_;
    00337       }
    00338     }
    00339     else {
    00340       Raise_Error(_SC("wrong number of parameters"));
    00341       return false;
    00342     }
    00343   }
    00344
    00345   if(type(closure->_env) == OT_WEAKREF) {
    00346     _stack._vals[stackbase] = _weakref(closure->_env)->_obj;
    00347   }
    00348
    00349   if (!tailcall) {
    00350     CallInfo lc;
    00351     memset(&lc, 0, sizeof(lc));
    00352     lc._generator = NULL;
    00353     lc._etraps = 0;
    00354     lc._prevstkbase = (SQInt32) ( stackbase - _stackbase );
    00355     lc._target = (SQInt32) target;
    00356     lc._prevtop = (SQInt32) (_top - _stackbase);
    00357     lc._ncalls = 1;
    00358     lc._root = SQFalse;
    00359     PUSH_CALLINFO(this, lc);
    00360   }
    00361   else {
    00362     ci->_ncalls++;
    00363   }
    00364   ci->_vargs.size = (SQInt32)(nargs - paramssize);
    00365   ci->_vargs.base = (SQInt32)(_vargsstack.size()-(ci->_vargs.size));
    00366   ci->_closure = closure;
    00367   ci->_literals = func->_literals;
    00368   ci->_ip = func->_instructions;
    00369   //grows the stack if needed
    00370   if (((SQUnsignedInteger)newtop + (func->_stacksize<<1)) > _stack.size()) {
    00371     _stack.resize(_stack.size() + (func->_stacksize<<1));
    00372   }
    00373
    00374   _top = newtop;
    00375   _stackbase = stackbase;
    00376   if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
    00377     CallDebugHook(_SC('c'));
    00378   return true;
    00379 }
    00380
    00381 bool SQVM::Return(SQInteger _arg0, SQInteger _arg1, SQObjectPtr &retval)
    00382 {
    00383   if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
    00384     for(SQInteger i=0;i<ci->_ncalls;i++)
    00385       CallDebugHook(_SC('r'));
    00386
    00387   SQBool broot = ci->_root;
    00388   SQInteger last_top = _top;
    00389   SQInteger target = ci->_target;
    00390   SQInteger oldstackbase = _stackbase;
    00391   _stackbase -= ci->_prevstkbase;
    00392   _top = _stackbase + ci->_prevtop;
    00393   if(ci->_vargs.size) PopVarArgs(ci->_vargs);
    00394   POP_CALLINFO(this);
    00395   if (broot) {
    00396     if (_arg0 != MAX_FUNC_STACKSIZE) retval = _stack._vals[oldstackbase+_arg1];
    00397     else retval = _null_;
    00398   }
    00399   else {
    00400     if(target != -1) { //-1 is when a class contructor ret value has to be ignored
    00401       if (_arg0 != MAX_FUNC_STACKSIZE)
    00402         STK(target) = _stack._vals[oldstackbase+_arg1];
    00403       else
    00404         STK(target) = _null_;
    00405     }
    00406   }
    00407
    00408   while (last_top > oldstackbase) _stack._vals[last_top--].Null();
    00409   assert(oldstackbase >= _stackbase);
    00410   return broot?true:false;
    00411 }
    00412
    00413 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
    00414
    00415 bool SQVM::LOCAL_INC(SQInteger op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
    00416 {
    00417   _RET_ON_FAIL(ARITH_OP( op , target, a, incr));
    00418   a = target;
    00419   return true;
    00420 }
    00421
    00422 bool SQVM::PLOCAL_INC(SQInteger op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
    00423 {
    00424   SQObjectPtr trg;
    00425   _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
    00426   target = a;
    00427   a = trg;
    00428   return true;
    00429 }
    00430
    00431 bool SQVM::DerefInc(SQInteger op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix)
    00432 {
    00433   SQObjectPtr tmp, tself = self, tkey = key;
    00434   if (!Get(tself, tkey, tmp, false, true)) { Raise_IdxError(tkey); return false; }
    00435   _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
    00436   Set(tself, tkey, target,true);
    00437   if (postfix) target = tmp;
    00438   return true;
    00439 }
    00440
    00441 #define arg0 (_i_._arg0)
    00442 #define arg1 (_i_._arg1)
    00443 #define sarg1 (*((SQInt32 *)&_i_._arg1))
    00444 #define arg2 (_i_._arg2)
    00445 #define arg3 (_i_._arg3)
    00446 #define sarg3 ((SQInteger)*((signed char *)&_i_._arg3))
    00447
    00448 SQRESULT SQVM::Suspend()
    00449 {
    00450   if (_suspended)
    00451     return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
    00452   if (_nnativecalls!=2)
    00453     return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
    00454   return SQ_SUSPEND_FLAG;
    00455 }
    00456
    00457 void SQVM::PopVarArgs(VarArgs &vargs)
    00458 {
    00459   for(SQInteger n = 0; n< vargs.size; n++)
    00460     _vargsstack.pop_back();
    00461 }
    00462
    00463 #define _FINISH(howmuchtojump) {jump = howmuchtojump; return true; }
    00464 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
    00465 &o3,SQObjectPtr &o4,SQInteger arg_2,int exitpos,int &jump)
    00466 {
    00467   SQInteger nrefidx;
    00468   switch(type(o1)) {
    00469   case OT_TABLE:
    00470     if((nrefidx = _table(o1)->Next(false,o4, o2, o3)) == -1) _FINISH(exitpos);
    00471     o4 = (SQInteger)nrefidx; _FINISH(1);
    00472   case OT_ARRAY:
    00473     if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(exitpos);
    00474     o4 = (SQInteger) nrefidx; _FINISH(1);
    00475   case OT_STRING:
    00476     if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
    00477     o4 = (SQInteger)nrefidx; _FINISH(1);
    00478   case OT_CLASS:
    00479     if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
    00480     o4 = (SQInteger)nrefidx; _FINISH(1);
    00481   case OT_USERDATA:
    00482   case OT_INSTANCE:
    00483     if(_delegable(o1)->_delegate) {
    00484       SQObjectPtr itr;
    00485       Push(o1);
    00486       Push(o4);
    00487       if(CallMetaMethod(_delegable(o1), MT_NEXTI, 2, itr)){
    00488         o4 = o2 = itr;
    00489         if(type(itr) == OT_NULL) _FINISH(exitpos);
    00490         if(!Get(o1, itr, o3, false,false)) {
    00491           Raise_Error(_SC("_nexti returned an invalid idx"));
    00492           return false;
    00493         }
    00494         _FINISH(1);
    00495       }
    00496       Raise_Error(_SC("_nexti failed"));
    00497       return false;
    00498     }
    00499     break;
    00500   case OT_GENERATOR:
    00501     if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(exitpos);
    00502     if(_generator(o1)->_state == SQGenerator::eSuspended) {
    00503       SQInteger idx = 0;
    00504       if(type(o4) == OT_INTEGER) {
    00505         idx = _integer(o4) + 1;
    00506       }
    00507       o2 = idx;
    00508       o4 = idx;
    00509       _generator(o1)->Resume(this, arg_2+1);
    00510       _FINISH(0);
    00511     }
    00512   default:
    00513     Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
    00514   }
    00515   return false; //cannot be hit(just to avoid warnings)
    00516 }
    00517
    00518 bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2)
    00519 {
    00520   if(type(o1) != OT_TABLE) { Raise_Error(_SC("delegating a '%s'"), GetTypeName(o1)); return false; }
    00521   switch(type(o2)) {
    00522   case OT_TABLE:
    00523     if(!_table(o1)->SetDelegate(_table(o2))){
    00524       Raise_Error(_SC("delegate cycle detected"));
    00525       return false;
    00526     }
    00527     break;
    00528   case OT_NULL:
    00529     _table(o1)->SetDelegate(NULL);
    00530     break;
    00531   default:
    00532     Raise_Error(_SC("using '%s' as delegate"), GetTypeName(o2));
    00533     return false;
    00534     break;
    00535   }
    00536   trg = o1;
    00537   return true;
    00538 }
    00539 #define COND_LITERAL (arg3!=0?ci->_literals[arg1]:STK(arg1))
    00540
    00541 #define _GUARD(exp) { if(!exp) { Raise_Error(_lasterror); SQ_THROW();} }
    00542
    00543 #define SQ_THROW() { goto exception_trap; }
    00544
    00545 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
    00546 {
    00547   SQInteger nouters;
    00548   SQClosure *closure = SQClosure::Create(_ss(this), func);
    00549   if((nouters = func->_noutervalues)) {
    00550     closure->_outervalues.reserve(nouters);
    00551     for(SQInteger i = 0; i<nouters; i++) {
    00552       SQOuterVar &v = func->_outervalues[i];
    00553       switch(v._type){
    00554       case otSYMBOL:
    00555         closure->_outervalues.push_back(_null_);
    00556         if(!Get(_stack._vals[_stackbase]/*STK(0)*/, v._src, closure->_outervalues.top(), false,true))
    00557         {Raise_IdxError(v._src); return false; }
    00558         break;
    00559       case otLOCAL:
    00560         closure->_outervalues.push_back(_stack._vals[_stackbase+_integer(v._src)]);
    00561         break;
    00562       case otOUTER:
    00563         closure->_outervalues.push_back(_closure(ci->_closure)->_outervalues[_integer(v._src)]);
    00564         break;
    00565       }
    00566     }
    00567   }
    00568   SQInteger ndefparams;
    00569   if((ndefparams = func->_ndefaultparams)) {
    00570     closure->_defaultparams.reserve(ndefparams);
    00571     for(SQInteger i = 0; i < ndefparams; i++) {
    00572       SQInteger spos = func->_defaultparams[i];
    00573       closure->_defaultparams.push_back(_stack._vals[_stackbase + spos]);
    00574     }
    00575   }
    00576   target = closure;
    00577   return true;
    00578
    00579 }
    00580
    00581 bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci)
    00582 {
    00583   if(ci->_vargs.size == 0) {
    00584     Raise_Error(_SC("the function doesn't have var args"));
    00585     return false;
    00586   }
    00587   if(!sq_isnumeric(index)){
    00588     Raise_Error(_SC("indexing 'vargv' with %s"),GetTypeName(index));
    00589     return false;
    00590   }
    00591   SQInteger idx = tointeger(index);
    00592   if(idx < 0 || idx >= ci->_vargs.size){ Raise_Error(_SC("vargv index out of range")); return false; }
    00593   target = _vargsstack[ci->_vargs.base+idx];
    00594   return true;
    00595 }
    00596
    00597 bool SQVM::CLASS_OP(SQObjectPtr &target,SQInteger baseclass,SQInteger attributes)
    00598 {
    00599   SQClass *base = NULL;
    00600   SQObjectPtr attrs;
    00601   if(baseclass != -1) {
    00602     if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
    00603     base = _class(_stack._vals[_stackbase + baseclass]);
    00604   }
    00605   if(attributes != MAX_FUNC_STACKSIZE) {
    00606     attrs = _stack._vals[_stackbase+attributes];
    00607   }
    00608   target = SQClass::Create(_ss(this),base);
    00609   if(type(_class(target)->_metamethods[MT_INHERITED]) != OT_NULL) {
    00610     int nparams = 2;
    00611     SQObjectPtr ret;
    00612     Push(target); Push(attrs);
    00613     Call(_class(target)->_metamethods[MT_INHERITED],nparams,_top - nparams, ret, false, false);
    00614     Pop(nparams);
    00615   }
    00616   _class(target)->_attributes = attrs;
    00617   return true;
    00618 }
    00619
    00620
    00621
    00622 bool SQVM::IsEqual(SQObjectPtr &o1,SQObjectPtr &o2,bool &res)
    00623 {
    00624   if(type(o1) == type(o2)) {
    00625     res = ((_userpointer(o1) == _userpointer(o2)?true:false));
    00626   }
    00627   else {
    00628     if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
    00629       SQInteger cmpres;
    00630       if(!ObjCmp(o1, o2,cmpres)) return false;
    00631       res = (cmpres == 0);
    00632     }
    00633     else {
    00634       res = false;
    00635     }
    00636   }
    00637   return true;
    00638 }
    00639
    00640 bool SQVM::IsFalse(SQObjectPtr &o)
    00641 {
    00642   if(((type(o) & SQOBJECT_CANBEFALSE) && ( (type(o) == OT_FLOAT) && (_float(o) == SQFloat(0.0)) ))
    00643     || (_integer(o) == 0) ) { //OT_NULL|OT_INTEGER|OT_BOOL
    00644     return true;
    00645   }
    00646   return false;
    00647 }
    00648
    00649 bool SQVM::GETPARENT_OP(SQObjectPtr &o,SQObjectPtr &target)
    00650 {
    00651   switch(type(o)) {
    00652     case OT_TABLE: target = _table(o)->_delegate?SQObjectPtr(_table(o)->_delegate):_null_;
    00653       break;
    00654     case OT_CLASS: target = _class(o)->_base?_class(o)->_base:_null_;
    00655       break;
    00656     default:
    00657       Raise_Error(_SC("the %s type doesn't have a parent slot"), GetTypeName(o));
    00658       return false;
    00659   }
    00660   return true;
    00661 }
    00662
    00663 bool SQVM::Execute(SQObjectPtr &closure, SQInteger target, SQInteger nargs, SQInteger stackbase,SQObjectPtr &outres, SQBool raiseerror,ExecutionType et)
    00664 {
    00665   if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
    00666   _nnativecalls++;
    00667   AutoDec ad(&_nnativecalls);
    00668   SQInteger traps = 0;
    00669   //temp_reg vars for OP_CALL
    00670   SQInteger ct_target;
    00671   SQInteger ct_stackbase;
    00672   bool ct_tailcall;
    00673
    00674   switch(et) {
    00675     case ET_CALL:
    00676       if(!StartCall(_closure(closure), _top - nargs, nargs, stackbase, false)) {
    00677         //call the handler if there are no calls in the stack, if not relies on the previous node
    00678         if(ci == NULL) CallErrorHandler(_lasterror);
    00679         return false;
    00680       }
    00681       ci->_root = SQTrue;
    00682       break;
    00683     case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, target); ci->_root = SQTrue; traps += ci->_etraps; break;
    00684     case ET_RESUME_VM:
    00685       traps = _suspended_traps;
    00686       ci->_root = _suspended_root;
    00687       ci->_vargs = _suspend_varargs;
    00688       _suspended = SQFalse;
    00689       break;
    00690     case ET_RESUME_OPENTTD:
    00691       _suspended = SQFalse;
    00692       break;
    00693   }
    00694
    00695 exception_restore:
    00696   //
    00697   {
    00698     for(;;)
    00699     {
    00700       DecreaseOps(1);
    00701       if (ShouldSuspend()) { _suspended = SQTrue; return true; }
    00702
    00703       const SQInstruction &_i_ = *ci->_ip++;
    00704       //dumpstack(_stackbase);
    00705       //scprintf("%s %d %d %d %d\n",g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
    00706       switch(_i_.op)
    00707       {
    00708       case _OP_LINE:
    00709         if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
    00710           CallDebugHook(_SC('l'),arg1);
    00711         continue;
    00712       case _OP_LOAD: TARGET = ci->_literals[arg1]; continue;
    00713       case _OP_LOADINT: TARGET = (SQInteger)arg1; continue;
    00714       case _OP_LOADFLOAT: TARGET = *((SQFloat *)&arg1); continue;
    00715       case _OP_DLOAD: TARGET = ci->_literals[arg1]; STK(arg2) = ci->_literals[arg3];continue;
    00716       case _OP_TAILCALL:
    00717         temp_reg = STK(arg1);
    00718         if (type(temp_reg) == OT_CLOSURE){
    00719           ct_tailcall = true;
    00720           if(ci->_vargs.size) PopVarArgs(ci->_vargs);
    00721           for (SQInteger i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
    00722           ct_target = ci->_target;
    00723           ct_stackbase = _stackbase;
    00724           goto common_call;
    00725         }
    00726       case _OP_CALL: {
    00727           ct_tailcall = false;
    00728           ct_target = arg0;
    00729           temp_reg = STK(arg1);
    00730           ct_stackbase = _stackbase+arg2;
    00731
    00732 common_call:
    00733           SQObjectPtr clo = temp_reg;
    00734           SQInteger last_top = _top;
    00735           switch (type(clo)) {
    00736           case OT_CLOSURE:{
    00737             _GUARD(StartCall(_closure(clo), ct_target, arg3, ct_stackbase, ct_tailcall));
    00738             if (_funcproto(_closure(clo)->_function)->_bgenerator) {
    00739               SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(clo));
    00740               _GUARD(gen->Yield(this));
    00741               Return(1, ct_target, clo);
    00742               STK(ct_target) = gen;
    00743               while (last_top >= _top) _stack._vals[last_top--].Null();
    00744               continue;
    00745             }
    00746             }
    00747             continue;
    00748           case OT_NATIVECLOSURE: {
    00749             bool suspend;
    00750             _suspended_target = ct_target;
    00751             _GUARD(CallNative(_nativeclosure(clo), arg3, ct_stackbase, clo,suspend));
    00752             if(suspend){
    00753               _suspended = SQTrue;
    00754               _suspended_target = ct_target;
    00755               _suspended_root = ci->_root;
    00756               _suspended_traps = traps;
    00757               _suspend_varargs = ci->_vargs;
    00758               outres = clo;
    00759               return true;
    00760             }
    00761             if(ct_target != -1) { //skip return value for constructors
    00762               STK(ct_target) = clo;
    00763             }
    00764                        }
    00765             continue;
    00766           case OT_CLASS:{
    00767             SQObjectPtr inst;
    00768             _GUARD(CreateClassInstance(_class(clo),inst,temp_reg));
    00769             STK(ct_target) = inst;
    00770             ct_target = -1; //fakes return value target so that is not overwritten by the constructor
    00771             if(type(temp_reg) != OT_NULL) {
    00772               _stack._vals[ct_stackbase] = inst;
    00773               goto common_call; //hard core spaghetti code(reissues the OP_CALL to invoke the constructor)
    00774             }
    00775             }
    00776             break;
    00777           case OT_TABLE:
    00778           case OT_USERDATA:
    00779           case OT_INSTANCE:
    00780             {
    00781             Push(clo);
    00782             for (SQInteger i = 0; i < arg3; i++) Push(STK(arg2 + i));
    00783             if (_delegable(clo) && CallMetaMethod(_delegable(clo), MT_CALL, arg3+1, clo)){
    00784               STK(ct_target) = clo;
    00785               break;
    00786             }
    00787             Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
    00788             SQ_THROW();
    00789             }
    00790           default:
    00791             Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
    00792             SQ_THROW();
    00793           }
    00794         }
    00795           continue;
    00796       case _OP_PREPCALL:
    00797       case _OP_PREPCALLK:
    00798         {
    00799           SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1);
    00800           SQObjectPtr &o = STK(arg2);
    00801           if (!Get(o, key, temp_reg,false,true)) {
    00802             if(type(o) == OT_CLASS) { //hack?
    00803               if(_class_ddel->Get(key,temp_reg)) {
    00804                 STK(arg3) = o;
    00805                 TARGET = temp_reg;
    00806                 continue;
    00807               }
    00808             }
    00809             { Raise_IdxError(key); SQ_THROW();}
    00810           }
    00811
    00812           STK(arg3) = type(o) == OT_CLASS?STK(0):o;
    00813           TARGET = temp_reg;
    00814         }
    00815         continue;
    00816       case _OP_SCOPE_END:
    00817       {
    00818         SQInteger from = arg0;
    00819         SQInteger count = arg1 - arg0 + 2;
    00820         /* When 'return' is executed, it happens that the stack is already cleaned
    00821          *  (by Return()), but this OP-code is still executed. So check for this
    00822          *  situation, and ignore the cleanup */
    00823         if (_stackbase + count + from <= _top) {
    00824           while (--count >= 0) _stack._vals[_stackbase + count + from].Null();
    00825         }
    00826       } continue;
    00827       case _OP_GETK:
    00828         if (!Get(STK(arg2), ci->_literals[arg1], temp_reg, false,true)) { Raise_IdxError(ci->_literals[arg1]); SQ_THROW();}
    00829         TARGET = temp_reg;
    00830         continue;
    00831       case _OP_MOVE: TARGET = STK(arg1); continue;
    00832       case _OP_NEWSLOT:
    00833         _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),false));
    00834         if(arg0 != arg3) TARGET = STK(arg3);
    00835         continue;
    00836       case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
    00837       case _OP_SET:
    00838         if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
    00839         if (arg0 != arg3) TARGET = STK(arg3);
    00840         continue;
    00841       case _OP_GET:
    00842         if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
    00843         TARGET = temp_reg;
    00844         continue;
    00845       case _OP_EQ:{
    00846         bool res;
    00847         if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
    00848         TARGET = res?_true_:_false_;
    00849         }continue;
    00850       case _OP_NE:{
    00851         bool res;
    00852         if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
    00853         TARGET = (!res)?_true_:_false_;
    00854         } continue;
    00855       case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
    00856       case _OP_BITW:  _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
    00857       case _OP_RETURN:
    00858         if(ci->_generator) {
    00859           ci->_generator->Kill();
    00860         }
    00861         if(Return(arg0, arg1, temp_reg)){
    00862           assert(traps==0);
    00863           outres = temp_reg;
    00864           return true;
    00865         }
    00866         continue;
    00867       case _OP_LOADNULLS:{ for(SQInt32 n=0; n < arg1; n++) STK(arg0+n) = _null_; }continue;
    00868       case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
    00869       case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
    00870       case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
    00871       case _OP_JMP: ci->_ip += (sarg1); continue;
    00872       case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
    00873       case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
    00874       case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
    00875       case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
    00876       case _OP_GETVARGV:
    00877         if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); }
    00878         continue;
    00879       case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
    00880       case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
    00881       case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL);  continue;
    00882       case _OP_GETPARENT: _GUARD(GETPARENT_OP(STK(arg1),TARGET)); continue;
    00883       case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((SQUnsignedInteger)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
    00884       case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
    00885       case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
    00886       case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
    00887       case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
    00888       case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
    00889       case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET))  continue;
    00890       case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
    00891       case _OP_INSTANCEOF:
    00892         if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
    00893         {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
    00894         TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
    00895         continue;
    00896       case _OP_AND:
    00897         if(IsFalse(STK(arg2))) {
    00898           TARGET = STK(arg2);
    00899           ci->_ip += (sarg1);
    00900         }
    00901         continue;
    00902       case _OP_OR:
    00903         if(!IsFalse(STK(arg2))) {
    00904           TARGET = STK(arg2);
    00905           ci->_ip += (sarg1);
    00906         }
    00907         continue;
    00908       case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
    00909       case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
    00910       case _OP_BWNOT:
    00911         if(type(STK(arg1)) == OT_INTEGER) {
    00912           SQInteger t = _integer(STK(arg1));
    00913           TARGET = SQInteger(~t);
    00914           continue;
    00915         }
    00916         Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
    00917         SQ_THROW();
    00918       case _OP_CLOSURE: {
    00919         SQClosure *c = ci->_closure._unVal.pClosure;
    00920         SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
    00921         if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
    00922         continue;
    00923       }
    00924       case _OP_YIELD:{
    00925         if(ci->_generator) {
    00926           if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
    00927           _GUARD(ci->_generator->Yield(this));
    00928           traps -= ci->_etraps;
    00929           if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
    00930         }
    00931         else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
    00932         if(Return(arg0, arg1, temp_reg)){
    00933           assert(traps == 0);
    00934           outres = temp_reg;
    00935           return true;
    00936         }
    00937
    00938         }
    00939         continue;
    00940       case _OP_RESUME:
    00941         if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
    00942         _GUARD(_generator(STK(arg1))->Resume(this, arg0));
    00943         traps += ci->_etraps;
    00944                 continue;
    00945       case _OP_FOREACH:{ int tojump;
    00946         _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,sarg1,tojump));
    00947         ci->_ip += tojump; }
    00948         continue;
    00949       case _OP_POSTFOREACH:
    00950         assert(type(STK(arg0)) == OT_GENERATOR);
    00951         if(_generator(STK(arg0))->_state == SQGenerator::eDead)
    00952           ci->_ip += (sarg1 - 1);
    00953         continue;
    00954       case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
    00955       case _OP_CLONE:
    00956         if(!Clone(STK(arg1), TARGET))
    00957         { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
    00958         continue;
    00959       case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
    00960       case _OP_PUSHTRAP:{
    00961         SQInstruction *_iv = _funcproto(_closure(ci->_closure)->_function)->_instructions;
    00962         _etraps.push_back(SQExceptionTrap(_top,_stackbase, &_iv[(ci->_ip-_iv)+arg1], arg0)); traps++;
    00963         ci->_etraps++;
    00964                 }
    00965         continue;
    00966       case _OP_POPTRAP: {
    00967         for(SQInteger i = 0; i < arg0; i++) {
    00968           _etraps.pop_back(); traps--;
    00969           ci->_etraps--;
    00970         }
    00971                 }
    00972         continue;
    00973       case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
    00974       case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
    00975       case _OP_NEWSLOTA:
    00976         bool bstatic = (arg0&NEW_SLOT_STATIC_FLAG)?true:false;
    00977         if(type(STK(arg1)) == OT_CLASS) {
    00978           if(type(_class(STK(arg1))->_metamethods[MT_NEWMEMBER]) != OT_NULL ) {
    00979             Push(STK(arg1)); Push(STK(arg2)); Push(STK(arg3));
    00980             Push((arg0&NEW_SLOT_ATTRIBUTES_FLAG) ? STK(arg2-1) : _null_);
    00981             int nparams = 4;
    00982             if(Call(_class(STK(arg1))->_metamethods[MT_NEWMEMBER], nparams, _top - nparams, temp_reg,SQFalse,SQFalse)) {
    00983               Pop(nparams);
    00984               continue;
    00985             }
    00986           }
    00987         }
    00988         _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),bstatic));
    00989         if((arg0&NEW_SLOT_ATTRIBUTES_FLAG)) {
    00990           _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
    00991         }
    00992         continue;
    00993       }
    00994
    00995     }
    00996   }
    00997 exception_trap:
    00998   {
    00999     SQObjectPtr currerror = _lasterror;
    01000 //    dumpstack(_stackbase);
    01001     SQInteger n = 0;
    01002     SQInteger last_top = _top;
    01003     if(ci) {
    01004       if(_ss(this)->_notifyallexceptions) CallErrorHandler(currerror);
    01005
    01006       if(traps) {
    01007         do {
    01008           if(ci->_etraps > 0) {
    01009             SQExceptionTrap &et = _etraps.top();
    01010             ci->_ip = et._ip;
    01011             _top = et._stacksize;
    01012             _stackbase = et._stackbase;
    01013             _stack._vals[_stackbase+et._extarget] = currerror;
    01014             _etraps.pop_back(); traps--; ci->_etraps--;
    01015             while(last_top >= _top) _stack._vals[last_top--].Null();
    01016             goto exception_restore;
    01017           }
    01018           //if is a native closure
    01019           if(type(ci->_closure) != OT_CLOSURE && n)
    01020             break;
    01021           if(ci->_generator) ci->_generator->Kill();
    01022           PopVarArgs(ci->_vargs);
    01023           POP_CALLINFO(this);
    01024           n++;
    01025         } while(_callsstacksize);
    01026       }
    01027       else {
    01028         //call the hook
    01029         if(raiseerror && !_ss(this)->_notifyallexceptions)
    01030           CallErrorHandler(currerror);
    01031       }
    01032       //remove call stack until a C function is found or the cstack is empty
    01033       if(ci) do {
    01034         SQBool exitafterthisone = ci->_root;
    01035         if(ci->_generator) ci->_generator->Kill();
    01036         _stackbase -= ci->_prevstkbase;
    01037         _top = _stackbase + ci->_prevtop;
    01038         PopVarArgs(ci->_vargs);
    01039         POP_CALLINFO(this);
    01040         if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
    01041       } while(_callsstacksize);
    01042
    01043       while(last_top >= _top) _stack._vals[last_top--].Null();
    01044     }
    01045     _lasterror = currerror;
    01046     return false;
    01047   }
    01048   assert(0);
    01049 }
    01050
    01051 bool SQVM::CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor)
    01052 {
    01053   inst = theclass->CreateInstance();
    01054   if(!theclass->Get(_ss(this)->_constructoridx,constructor)) {
    01055     //if(!Call(constr,nargs,stackbase,constr,false))
    01056     //  return false;
    01057     constructor = _null_;
    01058   }
    01059   return true;
    01060 }
    01061
    01062 void SQVM::CallErrorHandler(SQObjectPtr &error)
    01063 {
    01064   if(type(_errorhandler) != OT_NULL) {
    01065     SQObjectPtr out;
    01066     Push(_roottable); Push(error);
    01067     Call(_errorhandler, 2, _top-2, out,SQFalse,SQFalse);
    01068     Pop(2);
    01069   }
    01070 }
    01071
    01072 void SQVM::CallDebugHook(SQInteger type,SQInteger forcedline)
    01073 {
    01074   SQObjectPtr temp_reg;
    01075   SQInteger nparams=5;
    01076   SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
    01077   Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
    01078   Call(_debughook,nparams,_top-nparams,temp_reg,SQFalse,SQFalse);
    01079   Pop(nparams);
    01080 }
    01081
    01082 bool SQVM::CallNative(SQNativeClosure *nclosure,SQInteger nargs,SQInteger stackbase,SQObjectPtr &retval,bool &suspend)
    01083 {
    01084   if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
    01085   SQInteger nparamscheck = nclosure->_nparamscheck;
    01086   if(((nparamscheck > 0) && (nparamscheck != nargs))
    01087     || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
    01088     Raise_Error(_SC("wrong number of parameters"));
    01089     return false;
    01090     }
    01091
    01092   SQInteger tcs;
    01093   if((tcs = nclosure->_typecheck.size())) {
    01094     for(SQInteger i = 0; i < nargs && i < tcs; i++)
    01095       if((nclosure->_typecheck._vals[i] != -1) && !(type(_stack._vals[stackbase+i]) & nclosure->_typecheck[i])) {
    01096                 Raise_ParamTypeError(i,nclosure->_typecheck._vals[i],type(_stack._vals[stackbase+i]));
    01097         return false;
    01098       }
    01099   }
    01100   _nnativecalls++;
    01101   if ((_top + MIN_STACK_OVERHEAD) > (SQInteger)_stack.size()) {
    01102     _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
    01103   }
    01104   SQInteger oldtop = _top;
    01105   SQInteger oldstackbase = _stackbase;
    01106   _top = stackbase + nargs;
    01107   CallInfo lci;
    01108   memset(&lci, 0, sizeof(lci));
    01109   lci._closure = nclosure;
    01110   lci._generator = NULL;
    01111   lci._etraps = 0;
    01112   lci._prevstkbase = (SQInt32) (stackbase - _stackbase);
    01113   lci._ncalls = 1;
    01114   lci._prevtop = (SQInt32) (oldtop - oldstackbase);
    01115   PUSH_CALLINFO(this, lci);
    01116   _stackbase = stackbase;
    01117   //push free variables
    01118   SQInteger outers = nclosure->_outervalues.size();
    01119   for (SQInteger i = 0; i < outers; i++) {
    01120     Push(nclosure->_outervalues[i]);
    01121   }
    01122
    01123   if(type(nclosure->_env) == OT_WEAKREF) {
    01124     _stack[stackbase] = _weakref(nclosure->_env)->_obj;
    01125   }
    01126
    01127
    01128   SQInteger ret;
    01129   try {
    01130     SQBool can_suspend = this->_can_suspend;
    01131     this->_can_suspend = false;
    01132     ret = (nclosure->_function)(this);
    01133     this->_can_suspend = can_suspend;
    01134   } catch (...) {
    01135     _nnativecalls--;
    01136     suspend = false;
    01137
    01138     _stackbase = oldstackbase;
    01139     _top = oldtop;
    01140
    01141     POP_CALLINFO(this);
    01142
    01143     while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01144     throw;
    01145   }
    01146
    01147   _nnativecalls--;
    01148   suspend = false;
    01149   if( ret == SQ_SUSPEND_FLAG) suspend = true;
    01150   else if (ret < 0) {
    01151     _stackbase = oldstackbase;
    01152     _top = oldtop;
    01153     POP_CALLINFO(this);
    01154     while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01155     Raise_Error(_lasterror);
    01156     return false;
    01157   }
    01158
    01159   if (ret != 0){ retval = TOP(); TOP().Null(); }
    01160   else { retval = _null_; }
    01161   _stackbase = oldstackbase;
    01162   _top = oldtop;
    01163   POP_CALLINFO(this);
    01164   while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01165   return true;
    01166 }
    01167
    01168 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
    01169 {
    01170   switch(type(self)){
    01171   case OT_TABLE:
    01172     if(_table(self)->Get(key,dest))return true;
    01173     break;
    01174   case OT_ARRAY:
    01175     if(sq_isnumeric(key)){
    01176       return _array(self)->Get(tointeger(key),dest);
    01177     }
    01178     break;
    01179   case OT_INSTANCE:
    01180     if(_instance(self)->Get(key,dest)) return true;
    01181     break;
    01182   default:break; //shut up compiler
    01183   }
    01184   if(FallBackGet(self,key,dest,raw)) return true;
    01185
    01186   if(fetchroot) {
    01187     if(_rawval(STK(0)) == _rawval(self) &&
    01188       type(STK(0)) == type(self)) {
    01189         return _table(_roottable)->Get(key,dest);
    01190     }
    01191   }
    01192   return false;
    01193 }
    01194
    01195 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
    01196 {
    01197   switch(type(self)){
    01198   case OT_CLASS:
    01199     return _class(self)->Get(key,dest);
    01200     break;
    01201   case OT_TABLE:
    01202   case OT_USERDATA:
    01203         //delegation
    01204     if(_delegable(self)->_delegate) {
    01205       if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
    01206         return true;
    01207       if(raw)return false;
    01208       Push(self);Push(key);
    01209       if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
    01210         return true;
    01211     }
    01212     if(type(self) == OT_TABLE) {
    01213       if(raw) return false;
    01214       return _table_ddel->Get(key,dest);
    01215     }
    01216     return false;
    01217     break;
    01218   case OT_ARRAY:
    01219     if(raw)return false;
    01220     return _array_ddel->Get(key,dest);
    01221   case OT_STRING:
    01222     if(sq_isnumeric(key)){
    01223       SQInteger n=tointeger(key);
    01224       if(abs((int)n)<_string(self)->_len){
    01225         if(n<0)n=_string(self)->_len-n;
    01226         dest=SQInteger(_stringval(self)[n]);
    01227         return true;
    01228       }
    01229       return false;
    01230     }
    01231     else {
    01232       if(raw)return false;
    01233       return _string_ddel->Get(key,dest);
    01234     }
    01235     break;
    01236   case OT_INSTANCE:
    01237     if(raw)return false;
    01238     Push(self);Push(key);
    01239     if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
    01240       return _instance_ddel->Get(key,dest);
    01241     }
    01242     return true;
    01243   case OT_INTEGER:case OT_FLOAT:case OT_BOOL:
    01244     if(raw)return false;
    01245     return _number_ddel->Get(key,dest);
    01246   case OT_GENERATOR:
    01247     if(raw)return false;
    01248     return _generator_ddel->Get(key,dest);
    01249   case OT_CLOSURE: case OT_NATIVECLOSURE:
    01250     if(raw)return false;
    01251     return _closure_ddel->Get(key,dest);
    01252   case OT_THREAD:
    01253     if(raw)return false;
    01254     return  _thread_ddel->Get(key,dest);
    01255   case OT_WEAKREF:
    01256     if(raw)return false;
    01257     return  _weakref_ddel->Get(key,dest);
    01258   default:return false;
    01259   }
    01260   return false;
    01261 }
    01262
    01263 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
    01264 {
    01265   switch(type(self)){
    01266   case OT_TABLE:
    01267     if(_table(self)->Set(key,val))
    01268       return true;
    01269     if(_table(self)->_delegate) {
    01270       if(Set(_table(self)->_delegate,key,val,false)) {
    01271         return true;
    01272       }
    01273     }
    01274     //keeps going
    01275   case OT_USERDATA:
    01276     if(_delegable(self)->_delegate) {
    01277       SQObjectPtr t;
    01278       Push(self);Push(key);Push(val);
    01279       if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
    01280     }
    01281     break;
    01282   case OT_INSTANCE:{
    01283     if(_instance(self)->Set(key,val))
    01284       return true;
    01285     SQObjectPtr t;
    01286     Push(self);Push(key);Push(val);
    01287     if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
    01288     }
    01289     break;
    01290   case OT_ARRAY:
    01291     if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
    01292     return _array(self)->Set(tointeger(key),val);
    01293   default:
    01294     Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
    01295     return false;
    01296   }
    01297   if(fetchroot) {
    01298     if(_rawval(STK(0)) == _rawval(self) &&
    01299       type(STK(0)) == type(self)) {
    01300         return _table(_roottable)->Set(key,val);
    01301       }
    01302   }
    01303   return false;
    01304 }
    01305
    01306 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
    01307 {
    01308   SQObjectPtr temp_reg;
    01309   SQObjectPtr newobj;
    01310   switch(type(self)){
    01311   case OT_TABLE:
    01312     newobj = _table(self)->Clone();
    01313     goto cloned_mt;
    01314   case OT_INSTANCE:
    01315     newobj = _instance(self)->Clone(_ss(this));
    01316 cloned_mt:
    01317     if(_delegable(newobj)->_delegate){
    01318       Push(newobj);
    01319       Push(self);
    01320       CallMetaMethod(_delegable(newobj),MT_CLONED,2,temp_reg);
    01321     }
    01322     target = newobj;
    01323     return true;
    01324   case OT_ARRAY:
    01325     target = _array(self)->Clone();
    01326     return true;
    01327   default: return false;
    01328   }
    01329 }
    01330
    01331 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
    01332 {
    01333   if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
    01334   switch(type(self)) {
    01335   case OT_TABLE: {
    01336     bool rawcall = true;
    01337     if(_table(self)->_delegate) {
    01338       SQObjectPtr res;
    01339       if(!_table(self)->Get(key,res)) {
    01340         Push(self);Push(key);Push(val);
    01341         rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
    01342       }
    01343     }
    01344     if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
    01345
    01346     break;}
    01347   case OT_INSTANCE: {
    01348     SQObjectPtr res;
    01349     Push(self);Push(key);Push(val);
    01350     if(!CallMetaMethod(_instance(self),MT_NEWSLOT,3,res)) {
    01351       Raise_Error(_SC("class instances do not support the new slot operator"));
    01352       return false;
    01353     }
    01354     break;}
    01355   case OT_CLASS:
    01356     if(!_class(self)->NewSlot(_ss(this),key,val,bstatic)) {
    01357       if(_class(self)->_locked) {
    01358         Raise_Error(_SC("trying to modify a class that has already been instantiated"));
    01359         return false;
    01360       }
    01361       else {
    01362         SQObjectPtr oval = PrintObjVal(key);
    01363         Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
    01364         return false;
    01365       }
    01366     }
    01367     break;
    01368   default:
    01369     Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
    01370     return false;
    01371     break;
    01372   }
    01373   return true;
    01374 }
    01375
    01376 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
    01377 {
    01378   switch(type(self)) {
    01379   case OT_TABLE:
    01380   case OT_INSTANCE:
    01381   case OT_USERDATA: {
    01382     SQObjectPtr t;
    01383     bool handled = false;
    01384     if(_delegable(self)->_delegate) {
    01385       Push(self);Push(key);
    01386       handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
    01387     }
    01388
    01389     if(!handled) {
    01390       if(type(self) == OT_TABLE) {
    01391         if(_table(self)->Get(key,t)) {
    01392           _table(self)->Remove(key);
    01393         }
    01394         else {
    01395           Raise_IdxError((SQObject &)key);
    01396           return false;
    01397         }
    01398       }
    01399       else {
    01400         Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
    01401         return false;
    01402       }
    01403     }
    01404     res = t;
    01405         }
    01406     break;
    01407   default:
    01408     Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
    01409     return false;
    01410   }
    01411   return true;
    01412 }
    01413
    01414 bool SQVM::Call(SQObjectPtr &closure,SQInteger nparams,SQInteger stackbase,SQObjectPtr &outres,SQBool raiseerror,SQBool can_suspend)
    01415 {
    01416 #ifdef _DEBUG
    01417 SQInteger prevstackbase = _stackbase;
    01418 #endif
    01419   switch(type(closure)) {
    01420   case OT_CLOSURE: {
    01421     assert(!can_suspend || this->_can_suspend);
    01422     SQBool backup_suspend = this->_can_suspend;
    01423     this->_can_suspend = can_suspend;
    01424     bool ret = Execute(closure, _top - nparams, nparams, stackbase,outres,raiseerror);
    01425     this->_can_suspend = backup_suspend;
    01426     return ret;
    01427            }
    01428     break;
    01429   case OT_NATIVECLOSURE:{
    01430     bool suspend;
    01431     return CallNative(_nativeclosure(closure), nparams, stackbase, outres,suspend);
    01432
    01433               }
    01434     break;
    01435   case OT_CLASS: {
    01436     SQObjectPtr constr;
    01437     SQObjectPtr temp;
    01438     CreateClassInstance(_class(closure),outres,constr);
    01439     if(type(constr) != OT_NULL) {
    01440       _stack[stackbase] = outres;
    01441       return Call(constr,nparams,stackbase,temp,raiseerror,false);
    01442     }
    01443     return true;
    01444            }
    01445     break;
    01446   default:
    01447     return false;
    01448   }
    01449 #ifdef _DEBUG
    01450   if(!_suspended) {
    01451     assert(_stackbase == prevstackbase);
    01452   }
    01453 #endif
    01454   return true;
    01455 }
    01456
    01457 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,SQInteger nparams,SQObjectPtr &outres)
    01458 {
    01459   SQObjectPtr closure;
    01460   if(del->GetMetaMethod(this, mm, closure)) {
    01461     if(Call(closure, nparams, _top - nparams, outres, SQFalse, SQFalse)) {
    01462       Pop(nparams);
    01463       return true;
    01464     }
    01465   }
    01466   Pop(nparams);
    01467   return false;
    01468 }
    01469
    01470 void SQVM::Remove(SQInteger n) {
    01471   n = (n >= 0)?n + _stackbase - 1:_top + n;
    01472   for(SQInteger i = n; i < _top; i++){
    01473     _stack[i] = _stack[i+1];
    01474   }
    01475   _stack[_top] = _null_;
    01476   _top--;
    01477 }
    01478
    01479 void SQVM::Pop() {
    01480   _stack[--_top] = _null_;
    01481 }
    01482
    01483 void SQVM::Pop(SQInteger n) {
    01484   for(SQInteger i = 0; i < n; i++){
    01485     _stack[--_top] = _null_;
    01486   }
    01487 }
    01488
    01489 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
    01490 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
    01491 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
    01492 SQObjectPtr &SQVM::GetUp(SQInteger n) { return _stack[_top+n]; }
    01493 SQObjectPtr &SQVM::GetAt(SQInteger n) { return _stack[n]; }
    01494
    01495 #ifdef _DEBUG_DUMP
    01496 void SQVM::dumpstack(SQInteger stackbase,bool dumpall)
    01497 {
    01498   SQInteger size=dumpall?_stack.size():_top;
    01499   SQInteger n=0;
    01500   scprintf(_SC("\n>>>>stack dump<<<<\n"));
    01501   CallInfo &ci=_callsstack[_callsstacksize-1];
    01502   scprintf(_SC("IP: %p\n"),ci._ip);
    01503   scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
    01504   scprintf(_SC("prev top: %d\n"),ci._prevtop);
    01505   for(SQInteger i=0;i<size;i++){
    01506     SQObjectPtr &obj=_stack[i];
    01507     if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
    01508     scprintf(_SC("[%d]:"),n);
    01509     switch(type(obj)){
    01510     case OT_FLOAT:      scprintf(_SC("FLOAT %.3f"),_float(obj));break;
    01511     case OT_INTEGER:    scprintf(_SC("INTEGER %d"),_integer(obj));break;
    01512     case OT_BOOL:     scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
    01513     case OT_STRING:     scprintf(_SC("STRING %s"),_stringval(obj));break;
    01514     case OT_NULL:     scprintf(_SC("NULL"));  break;
    01515     case OT_TABLE:      scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
    01516     case OT_ARRAY:      scprintf(_SC("ARRAY %p"),_array(obj));break;
    01517     case OT_CLOSURE:    scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
    01518     case OT_NATIVECLOSURE:  scprintf(_SC("NATIVECLOSURE"));break;
    01519     case OT_USERDATA:   scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
    01520     case OT_GENERATOR:    scprintf(_SC("GENERATOR %p"),_generator(obj));break;
    01521     case OT_THREAD:     scprintf(_SC("THREAD [%p]"),_thread(obj));break;
    01522     case OT_USERPOINTER:  scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
    01523     case OT_CLASS:      scprintf(_SC("CLASS %p"),_class(obj));break;
    01524     case OT_INSTANCE:   scprintf(_SC("INSTANCE %p"),_instance(obj));break;
    01525     case OT_WEAKREF:    scprintf(_SC("WEAKERF %p"),_weakref(obj));break;
    01526     default:
    01527       assert(0);
    01528       break;
    01529     };
    01530     scprintf(_SC("\n"));
    01531     ++n;
    01532   }
    01533 }
    01534
    01535
    01536
    01537 #endif