# 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=0;
    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       traps = _suspended_traps;
    00692       _suspended = SQFalse;
    00693       break;
    00694   }
    00695
    00696 exception_restore:
    00697   //
    00698   {
    00699     for(;;)
    00700     {
    00701       DecreaseOps(1);
    00702       if (ShouldSuspend()) { _suspended = SQTrue; _suspended_traps = traps; return true; }
    00703
    00704       const SQInstruction &_i_ = *ci->_ip++;
    00705       //dumpstack(_stackbase);
    00706       //scprintf("%s %d %d %d %d\n",g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
    00707       switch(_i_.op)
    00708       {
    00709       case _OP_LINE:
    00710         if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
    00711           CallDebugHook(_SC('l'),arg1);
    00712         continue;
    00713       case _OP_LOAD: TARGET = ci->_literals[arg1]; continue;
    00714       case _OP_LOADINT: TARGET = (SQInteger)arg1; continue;
    00715       case _OP_LOADFLOAT: TARGET = *((SQFloat *)&arg1); continue;
    00716       case _OP_DLOAD: TARGET = ci->_literals[arg1]; STK(arg2) = ci->_literals[arg3];continue;
    00717       case _OP_TAILCALL:
    00718         temp_reg = STK(arg1);
    00719         if (type(temp_reg) == OT_CLOSURE){
    00720           ct_tailcall = true;
    00721           if(ci->_vargs.size) PopVarArgs(ci->_vargs);
    00722           for (SQInteger i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
    00723           ct_target = ci->_target;
    00724           ct_stackbase = _stackbase;
    00725           goto common_call;
    00726         }
    00727       case _OP_CALL: {
    00728           ct_tailcall = false;
    00729           ct_target = arg0;
    00730           temp_reg = STK(arg1);
    00731           ct_stackbase = _stackbase+arg2;
    00732
    00733 common_call:
    00734           SQObjectPtr clo = temp_reg;
    00735           SQInteger last_top = _top;
    00736           switch (type(clo)) {
    00737           case OT_CLOSURE:{
    00738             _GUARD(StartCall(_closure(clo), ct_target, arg3, ct_stackbase, ct_tailcall));
    00739             if (_funcproto(_closure(clo)->_function)->_bgenerator) {
    00740               SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(clo));
    00741               _GUARD(gen->Yield(this));
    00742               Return(1, ct_target, clo);
    00743               STK(ct_target) = gen;
    00744               while (last_top >= _top) _stack._vals[last_top--].Null();
    00745               continue;
    00746             }
    00747             }
    00748             continue;
    00749           case OT_NATIVECLOSURE: {
    00750             bool suspend;
    00751             _suspended_target = ct_target;
    00752             _GUARD(CallNative(_nativeclosure(clo), arg3, ct_stackbase, clo,suspend));
    00753             if(suspend){
    00754               _suspended = SQTrue;
    00755               _suspended_target = ct_target;
    00756               _suspended_root = ci->_root;
    00757               _suspended_traps = traps;
    00758               _suspend_varargs = ci->_vargs;
    00759               outres = clo;
    00760               return true;
    00761             }
    00762             if(ct_target != -1) { //skip return value for constructors
    00763               STK(ct_target) = clo;
    00764             }
    00765                        }
    00766             continue;
    00767           case OT_CLASS:{
    00768             SQObjectPtr inst;
    00769             _GUARD(CreateClassInstance(_class(clo),inst,temp_reg));
    00770             STK(ct_target) = inst;
    00771             ct_target = -1; //fakes return value target so that is not overwritten by the constructor
    00772             if(type(temp_reg) != OT_NULL) {
    00773               _stack._vals[ct_stackbase] = inst;
    00774               goto common_call; //hard core spaghetti code(reissues the OP_CALL to invoke the constructor)
    00775             }
    00776             }
    00777             break;
    00778           case OT_TABLE:
    00779           case OT_USERDATA:
    00780           case OT_INSTANCE:
    00781             {
    00782             Push(clo);
    00783             for (SQInteger i = 0; i < arg3; i++) Push(STK(arg2 + i));
    00784             if (_delegable(clo) && CallMetaMethod(_delegable(clo), MT_CALL, arg3+1, clo)){
    00785               STK(ct_target) = clo;
    00786               break;
    00787             }
    00788             Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
    00789             SQ_THROW();
    00790             }
    00791           default:
    00792             Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
    00793             SQ_THROW();
    00794           }
    00795         }
    00796           continue;
    00797       case _OP_PREPCALL:
    00798       case _OP_PREPCALLK:
    00799         {
    00800           SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1);
    00801           SQObjectPtr &o = STK(arg2);
    00802           if (!Get(o, key, temp_reg,false,true)) {
    00803             if(type(o) == OT_CLASS) { //hack?
    00804               if(_class_ddel->Get(key,temp_reg)) {
    00805                 STK(arg3) = o;
    00806                 TARGET = temp_reg;
    00807                 continue;
    00808               }
    00809             }
    00810             { Raise_IdxError(key); SQ_THROW();}
    00811           }
    00812
    00813           STK(arg3) = type(o) == OT_CLASS?STK(0):o;
    00814           TARGET = temp_reg;
    00815         }
    00816         continue;
    00817       case _OP_SCOPE_END:
    00818       {
    00819         SQInteger from = arg0;
    00820         SQInteger count = arg1 - arg0 + 2;
    00821         /* When 'return' is executed, it happens that the stack is already cleaned
    00822          *  (by Return()), but this OP-code is still executed. So check for this
    00823          *  situation, and ignore the cleanup */
    00824         if (_stackbase + count + from <= _top) {
    00825           while (--count >= 0) _stack._vals[_stackbase + count + from].Null();
    00826         }
    00827       } continue;
    00828       case _OP_GETK:
    00829         if (!Get(STK(arg2), ci->_literals[arg1], temp_reg, false,true)) { Raise_IdxError(ci->_literals[arg1]); SQ_THROW();}
    00830         TARGET = temp_reg;
    00831         continue;
    00832       case _OP_MOVE: TARGET = STK(arg1); continue;
    00833       case _OP_NEWSLOT:
    00834         _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),false));
    00835         if(arg0 != arg3) TARGET = STK(arg3);
    00836         continue;
    00837       case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
    00838       case _OP_SET:
    00839         if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
    00840         if (arg0 != arg3) TARGET = STK(arg3);
    00841         continue;
    00842       case _OP_GET:
    00843         if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
    00844         TARGET = temp_reg;
    00845         continue;
    00846       case _OP_EQ:{
    00847         bool res;
    00848         if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
    00849         TARGET = res?_true_:_false_;
    00850         }continue;
    00851       case _OP_NE:{
    00852         bool res;
    00853         if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
    00854         TARGET = (!res)?_true_:_false_;
    00855         } continue;
    00856       case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
    00857       case _OP_BITW:  _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
    00858       case _OP_RETURN:
    00859         if(ci->_generator) {
    00860           ci->_generator->Kill();
    00861         }
    00862         if(Return(arg0, arg1, temp_reg)){
    00863           assert(traps==0);
    00864           outres = temp_reg;
    00865           return true;
    00866         }
    00867         continue;
    00868       case _OP_LOADNULLS:{ for(SQInt32 n=0; n < arg1; n++) STK(arg0+n) = _null_; }continue;
    00869       case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
    00870       case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
    00871       case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
    00872       case _OP_JMP: ci->_ip += (sarg1); continue;
    00873       case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
    00874       case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
    00875       case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
    00876       case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
    00877       case _OP_GETVARGV:
    00878         if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); }
    00879         continue;
    00880       case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
    00881       case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
    00882       case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL);  continue;
    00883       case _OP_GETPARENT: _GUARD(GETPARENT_OP(STK(arg1),TARGET)); continue;
    00884       case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((SQUnsignedInteger)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
    00885       case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
    00886       case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
    00887       case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
    00888       case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
    00889       case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
    00890       case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET))  continue;
    00891       case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
    00892       case _OP_INSTANCEOF:
    00893         if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
    00894         {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
    00895         TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
    00896         continue;
    00897       case _OP_AND:
    00898         if(IsFalse(STK(arg2))) {
    00899           TARGET = STK(arg2);
    00900           ci->_ip += (sarg1);
    00901         }
    00902         continue;
    00903       case _OP_OR:
    00904         if(!IsFalse(STK(arg2))) {
    00905           TARGET = STK(arg2);
    00906           ci->_ip += (sarg1);
    00907         }
    00908         continue;
    00909       case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
    00910       case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
    00911       case _OP_BWNOT:
    00912         if(type(STK(arg1)) == OT_INTEGER) {
    00913           SQInteger t = _integer(STK(arg1));
    00914           TARGET = SQInteger(~t);
    00915           continue;
    00916         }
    00917         Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
    00918         SQ_THROW();
    00919       case _OP_CLOSURE: {
    00920         SQClosure *c = ci->_closure._unVal.pClosure;
    00921         SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
    00922         if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
    00923         continue;
    00924       }
    00925       case _OP_YIELD:{
    00926         if(ci->_generator) {
    00927           if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
    00928           _GUARD(ci->_generator->Yield(this));
    00929           traps -= ci->_etraps;
    00930           if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
    00931         }
    00932         else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
    00933         if(Return(arg0, arg1, temp_reg)){
    00934           assert(traps == 0);
    00935           outres = temp_reg;
    00936           return true;
    00937         }
    00938
    00939         }
    00940         continue;
    00941       case _OP_RESUME:
    00942         if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
    00943         _GUARD(_generator(STK(arg1))->Resume(this, arg0));
    00944         traps += ci->_etraps;
    00945                 continue;
    00946       case _OP_FOREACH:{ int tojump;
    00947         _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,sarg1,tojump));
    00948         ci->_ip += tojump; }
    00949         continue;
    00950       case _OP_POSTFOREACH:
    00951         assert(type(STK(arg0)) == OT_GENERATOR);
    00952         if(_generator(STK(arg0))->_state == SQGenerator::eDead)
    00953           ci->_ip += (sarg1 - 1);
    00954         continue;
    00955       case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
    00956       case _OP_CLONE:
    00957         if(!Clone(STK(arg1), TARGET))
    00958         { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
    00959         continue;
    00960       case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
    00961       case _OP_PUSHTRAP:{
    00962         SQInstruction *_iv = _funcproto(_closure(ci->_closure)->_function)->_instructions;
    00963         _etraps.push_back(SQExceptionTrap(_top,_stackbase, &_iv[(ci->_ip-_iv)+arg1], arg0)); traps++;
    00964         ci->_etraps++;
    00965                 }
    00966         continue;
    00967       case _OP_POPTRAP: {
    00968         for(SQInteger i = 0; i < arg0; i++) {
    00969           _etraps.pop_back(); traps--;
    00970           ci->_etraps--;
    00971         }
    00972                 }
    00973         continue;
    00974       case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
    00975       case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
    00976       case _OP_NEWSLOTA:
    00977         bool bstatic = (arg0&NEW_SLOT_STATIC_FLAG)?true:false;
    00978         if(type(STK(arg1)) == OT_CLASS) {
    00979           if(type(_class(STK(arg1))->_metamethods[MT_NEWMEMBER]) != OT_NULL ) {
    00980             Push(STK(arg1)); Push(STK(arg2)); Push(STK(arg3));
    00981             Push((arg0&NEW_SLOT_ATTRIBUTES_FLAG) ? STK(arg2-1) : _null_);
    00982             int nparams = 4;
    00983             if(Call(_class(STK(arg1))->_metamethods[MT_NEWMEMBER], nparams, _top - nparams, temp_reg,SQFalse,SQFalse)) {
    00984               Pop(nparams);
    00985               continue;
    00986             }
    00987           }
    00988         }
    00989         _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),bstatic));
    00990         if((arg0&NEW_SLOT_ATTRIBUTES_FLAG)) {
    00991           _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
    00992         }
    00993         continue;
    00994       }
    00995
    00996     }
    00997   }
    00998 exception_trap:
    00999   {
    01000     SQObjectPtr currerror = _lasterror;
    01001 //    dumpstack(_stackbase);
    01002     SQInteger n = 0;
    01003     SQInteger last_top = _top;
    01004     if(ci) {
    01005       if(_ss(this)->_notifyallexceptions) CallErrorHandler(currerror);
    01006
    01007       if(traps) {
    01008         do {
    01009           if(ci->_etraps > 0) {
    01010             SQExceptionTrap &et = _etraps.top();
    01011             ci->_ip = et._ip;
    01012             _top = et._stacksize;
    01013             _stackbase = et._stackbase;
    01014             _stack._vals[_stackbase+et._extarget] = currerror;
    01015             _etraps.pop_back(); traps--; ci->_etraps--;
    01016             while(last_top >= _top) _stack._vals[last_top--].Null();
    01017             goto exception_restore;
    01018           }
    01019           //if is a native closure
    01020           if(type(ci->_closure) != OT_CLOSURE && n)
    01021             break;
    01022           if(ci->_generator) ci->_generator->Kill();
    01023           PopVarArgs(ci->_vargs);
    01024           POP_CALLINFO(this);
    01025           n++;
    01026         } while(_callsstacksize);
    01027       }
    01028       else {
    01029         //call the hook
    01030         if(raiseerror && !_ss(this)->_notifyallexceptions)
    01031           CallErrorHandler(currerror);
    01032       }
    01033       //remove call stack until a C function is found or the cstack is empty
    01034       if(ci) do {
    01035         SQBool exitafterthisone = ci->_root;
    01036         if(ci->_generator) ci->_generator->Kill();
    01037         _stackbase -= ci->_prevstkbase;
    01038         _top = _stackbase + ci->_prevtop;
    01039         PopVarArgs(ci->_vargs);
    01040         POP_CALLINFO(this);
    01041         if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
    01042       } while(_callsstacksize);
    01043
    01044       while(last_top >= _top) _stack._vals[last_top--].Null();
    01045     }
    01046     _lasterror = currerror;
    01047     return false;
    01048   }
    01049   assert(0);
    01050 }
    01051
    01052 bool SQVM::CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor)
    01053 {
    01054   inst = theclass->CreateInstance();
    01055   if(!theclass->Get(_ss(this)->_constructoridx,constructor)) {
    01056     //if(!Call(constr,nargs,stackbase,constr,false))
    01057     //  return false;
    01058     constructor = _null_;
    01059   }
    01060   return true;
    01061 }
    01062
    01063 void SQVM::CallErrorHandler(SQObjectPtr &error)
    01064 {
    01065   if(type(_errorhandler) != OT_NULL) {
    01066     SQObjectPtr out;
    01067     Push(_roottable); Push(error);
    01068     Call(_errorhandler, 2, _top-2, out,SQFalse,SQFalse);
    01069     Pop(2);
    01070   }
    01071 }
    01072
    01073 void SQVM::CallDebugHook(SQInteger type,SQInteger forcedline)
    01074 {
    01075   SQObjectPtr temp_reg;
    01076   SQInteger nparams=5;
    01077   SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
    01078   Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
    01079   Call(_debughook,nparams,_top-nparams,temp_reg,SQFalse,SQFalse);
    01080   Pop(nparams);
    01081 }
    01082
    01083 bool SQVM::CallNative(SQNativeClosure *nclosure,SQInteger nargs,SQInteger stackbase,SQObjectPtr &retval,bool &suspend)
    01084 {
    01085   if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
    01086   SQInteger nparamscheck = nclosure->_nparamscheck;
    01087   if(((nparamscheck > 0) && (nparamscheck != nargs))
    01088     || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
    01089     Raise_Error(_SC("wrong number of parameters"));
    01090     return false;
    01091     }
    01092
    01093   SQInteger tcs;
    01094   if((tcs = nclosure->_typecheck.size())) {
    01095     for(SQInteger i = 0; i < nargs && i < tcs; i++)
    01096       if((nclosure->_typecheck._vals[i] != -1) && !(type(_stack._vals[stackbase+i]) & nclosure->_typecheck[i])) {
    01097                 Raise_ParamTypeError(i,nclosure->_typecheck._vals[i],type(_stack._vals[stackbase+i]));
    01098         return false;
    01099       }
    01100   }
    01101   _nnativecalls++;
    01102   if ((_top + MIN_STACK_OVERHEAD) > (SQInteger)_stack.size()) {
    01103     _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
    01104   }
    01105   SQInteger oldtop = _top;
    01106   SQInteger oldstackbase = _stackbase;
    01107   _top = stackbase + nargs;
    01108   CallInfo lci;
    01109   memset(&lci, 0, sizeof(lci));
    01110   lci._closure = nclosure;
    01111   lci._generator = NULL;
    01112   lci._etraps = 0;
    01113   lci._prevstkbase = (SQInt32) (stackbase - _stackbase);
    01114   lci._ncalls = 1;
    01115   lci._prevtop = (SQInt32) (oldtop - oldstackbase);
    01116   PUSH_CALLINFO(this, lci);
    01117   _stackbase = stackbase;
    01118   //push free variables
    01119   SQInteger outers = nclosure->_outervalues.size();
    01120   for (SQInteger i = 0; i < outers; i++) {
    01121     Push(nclosure->_outervalues[i]);
    01122   }
    01123
    01124   if(type(nclosure->_env) == OT_WEAKREF) {
    01125     _stack[stackbase] = _weakref(nclosure->_env)->_obj;
    01126   }
    01127
    01128
    01129   SQInteger ret;
    01130   try {
    01131     SQBool can_suspend = this->_can_suspend;
    01132     this->_can_suspend = false;
    01133     ret = (nclosure->_function)(this);
    01134     this->_can_suspend = can_suspend;
    01135   } catch (...) {
    01136     _nnativecalls--;
    01137     suspend = false;
    01138
    01139     _stackbase = oldstackbase;
    01140     _top = oldtop;
    01141
    01142     POP_CALLINFO(this);
    01143
    01144     while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01145     throw;
    01146   }
    01147
    01148   _nnativecalls--;
    01149   suspend = false;
    01150   if( ret == SQ_SUSPEND_FLAG) suspend = true;
    01151   else if (ret < 0) {
    01152     _stackbase = oldstackbase;
    01153     _top = oldtop;
    01154     POP_CALLINFO(this);
    01155     while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01156     Raise_Error(_lasterror);
    01157     return false;
    01158   }
    01159
    01160   if (ret != 0){ retval = TOP(); TOP().Null(); }
    01161   else { retval = _null_; }
    01162   _stackbase = oldstackbase;
    01163   _top = oldtop;
    01164   POP_CALLINFO(this);
    01165   while(oldtop > _stackbase + stackbase) _stack._vals[oldtop--].Null();
    01166   return true;
    01167 }
    01168
    01169 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
    01170 {
    01171   switch(type(self)){
    01172   case OT_TABLE:
    01173     if(_table(self)->Get(key,dest))return true;
    01174     break;
    01175   case OT_ARRAY:
    01176     if(sq_isnumeric(key)){
    01177       return _array(self)->Get(tointeger(key),dest);
    01178     }
    01179     break;
    01180   case OT_INSTANCE:
    01181     if(_instance(self)->Get(key,dest)) return true;
    01182     break;
    01183   default:break; //shut up compiler
    01184   }
    01185   if(FallBackGet(self,key,dest,raw)) return true;
    01186
    01187   if(fetchroot) {
    01188     if(_rawval(STK(0)) == _rawval(self) &&
    01189       type(STK(0)) == type(self)) {
    01190         return _table(_roottable)->Get(key,dest);
    01191     }
    01192   }
    01193   return false;
    01194 }
    01195
    01196 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
    01197 {
    01198   switch(type(self)){
    01199   case OT_CLASS:
    01200     return _class(self)->Get(key,dest);
    01201     break;
    01202   case OT_TABLE:
    01203   case OT_USERDATA:
    01204         //delegation
    01205     if(_delegable(self)->_delegate) {
    01206       if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
    01207         return true;
    01208       if(raw)return false;
    01209       Push(self);Push(key);
    01210       if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
    01211         return true;
    01212     }
    01213     if(type(self) == OT_TABLE) {
    01214       if(raw) return false;
    01215       return _table_ddel->Get(key,dest);
    01216     }
    01217     return false;
    01218     break;
    01219   case OT_ARRAY:
    01220     if(raw)return false;
    01221     return _array_ddel->Get(key,dest);
    01222   case OT_STRING:
    01223     if(sq_isnumeric(key)){
    01224       SQInteger n=tointeger(key);
    01225       if(abs((int)n)<_string(self)->_len){
    01226         if(n<0)n=_string(self)->_len-n;
    01227         dest=SQInteger(_stringval(self)[n]);
    01228         return true;
    01229       }
    01230       return false;
    01231     }
    01232     else {
    01233       if(raw)return false;
    01234       return _string_ddel->Get(key,dest);
    01235     }
    01236     break;
    01237   case OT_INSTANCE:
    01238     if(raw)return false;
    01239     Push(self);Push(key);
    01240     if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
    01241       return _instance_ddel->Get(key,dest);
    01242     }
    01243     return true;
    01244   case OT_INTEGER:case OT_FLOAT:case OT_BOOL:
    01245     if(raw)return false;
    01246     return _number_ddel->Get(key,dest);
    01247   case OT_GENERATOR:
    01248     if(raw)return false;
    01249     return _generator_ddel->Get(key,dest);
    01250   case OT_CLOSURE: case OT_NATIVECLOSURE:
    01251     if(raw)return false;
    01252     return _closure_ddel->Get(key,dest);
    01253   case OT_THREAD:
    01254     if(raw)return false;
    01255     return  _thread_ddel->Get(key,dest);
    01256   case OT_WEAKREF:
    01257     if(raw)return false;
    01258     return  _weakref_ddel->Get(key,dest);
    01259   default:return false;
    01260   }
    01261   return false;
    01262 }
    01263
    01264 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
    01265 {
    01266   switch(type(self)){
    01267   case OT_TABLE:
    01268     if(_table(self)->Set(key,val))
    01269       return true;
    01270     if(_table(self)->_delegate) {
    01271       if(Set(_table(self)->_delegate,key,val,false)) {
    01272         return true;
    01273       }
    01274     }
    01275     //keeps going
    01276   case OT_USERDATA:
    01277     if(_delegable(self)->_delegate) {
    01278       SQObjectPtr t;
    01279       Push(self);Push(key);Push(val);
    01280       if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
    01281     }
    01282     break;
    01283   case OT_INSTANCE:{
    01284     if(_instance(self)->Set(key,val))
    01285       return true;
    01286     SQObjectPtr t;
    01287     Push(self);Push(key);Push(val);
    01288     if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
    01289     }
    01290     break;
    01291   case OT_ARRAY:
    01292     if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
    01293     return _array(self)->Set(tointeger(key),val);
    01294   default:
    01295     Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
    01296     return false;
    01297   }
    01298   if(fetchroot) {
    01299     if(_rawval(STK(0)) == _rawval(self) &&
    01300       type(STK(0)) == type(self)) {
    01301         return _table(_roottable)->Set(key,val);
    01302       }
    01303   }
    01304   return false;
    01305 }
    01306
    01307 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
    01308 {
    01309   SQObjectPtr temp_reg;
    01310   SQObjectPtr newobj;
    01311   switch(type(self)){
    01312   case OT_TABLE:
    01313     newobj = _table(self)->Clone();
    01314     goto cloned_mt;
    01315   case OT_INSTANCE:
    01316     newobj = _instance(self)->Clone(_ss(this));
    01317 cloned_mt:
    01318     if(_delegable(newobj)->_delegate){
    01319       Push(newobj);
    01320       Push(self);
    01321       CallMetaMethod(_delegable(newobj),MT_CLONED,2,temp_reg);
    01322     }
    01323     target = newobj;
    01324     return true;
    01325   case OT_ARRAY:
    01326     target = _array(self)->Clone();
    01327     return true;
    01328   default: return false;
    01329   }
    01330 }
    01331
    01332 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
    01333 {
    01334   if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
    01335   switch(type(self)) {
    01336   case OT_TABLE: {
    01337     bool rawcall = true;
    01338     if(_table(self)->_delegate) {
    01339       SQObjectPtr res;
    01340       if(!_table(self)->Get(key,res)) {
    01341         Push(self);Push(key);Push(val);
    01342         rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
    01343       }
    01344     }
    01345     if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
    01346
    01347     break;}
    01348   case OT_INSTANCE: {
    01349     SQObjectPtr res;
    01350     Push(self);Push(key);Push(val);
    01351     if(!CallMetaMethod(_instance(self),MT_NEWSLOT,3,res)) {
    01352       Raise_Error(_SC("class instances do not support the new slot operator"));
    01353       return false;
    01354     }
    01355     break;}
    01356   case OT_CLASS:
    01357     if(!_class(self)->NewSlot(_ss(this),key,val,bstatic)) {
    01358       if(_class(self)->_locked) {
    01359         Raise_Error(_SC("trying to modify a class that has already been instantiated"));
    01360         return false;
    01361       }
    01362       else {
    01363         SQObjectPtr oval = PrintObjVal(key);
    01364         Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
    01365         return false;
    01366       }
    01367     }
    01368     break;
    01369   default:
    01370     Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
    01371     return false;
    01372     break;
    01373   }
    01374   return true;
    01375 }
    01376
    01377 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
    01378 {
    01379   switch(type(self)) {
    01380   case OT_TABLE:
    01381   case OT_INSTANCE:
    01382   case OT_USERDATA: {
    01383     SQObjectPtr t;
    01384     bool handled = false;
    01385     if(_delegable(self)->_delegate) {
    01386       Push(self);Push(key);
    01387       handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
    01388     }
    01389
    01390     if(!handled) {
    01391       if(type(self) == OT_TABLE) {
    01392         if(_table(self)->Get(key,t)) {
    01393           _table(self)->Remove(key);
    01394         }
    01395         else {
    01396           Raise_IdxError((SQObject &)key);
    01397           return false;
    01398         }
    01399       }
    01400       else {
    01401         Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
    01402         return false;
    01403       }
    01404     }
    01405     res = t;
    01406         }
    01407     break;
    01408   default:
    01409     Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
    01410     return false;
    01411   }
    01412   return true;
    01413 }
    01414
    01415 bool SQVM::Call(SQObjectPtr &closure,SQInteger nparams,SQInteger stackbase,SQObjectPtr &outres,SQBool raiseerror,SQBool can_suspend)
    01416 {
    01417 #ifdef _DEBUG
    01418 SQInteger prevstackbase = _stackbase;
    01419 #endif
    01420   switch(type(closure)) {
    01421   case OT_CLOSURE: {
    01422     assert(!can_suspend || this->_can_suspend);
    01423     SQBool backup_suspend = this->_can_suspend;
    01424     this->_can_suspend = can_suspend;
    01425     bool ret = Execute(closure, _top - nparams, nparams, stackbase,outres,raiseerror);
    01426     this->_can_suspend = backup_suspend;
    01427     return ret;
    01428            }
    01429     break;
    01430   case OT_NATIVECLOSURE:{
    01431     bool suspend;
    01432     return CallNative(_nativeclosure(closure), nparams, stackbase, outres,suspend);
    01433
    01434               }
    01435     break;
    01436   case OT_CLASS: {
    01437     SQObjectPtr constr;
    01438     SQObjectPtr temp;
    01439     CreateClassInstance(_class(closure),outres,constr);
    01440     if(type(constr) != OT_NULL) {
    01441       _stack[stackbase] = outres;
    01442       return Call(constr,nparams,stackbase,temp,raiseerror,false);
    01443     }
    01444     return true;
    01445            }
    01446     break;
    01447   default:
    01448     return false;
    01449   }
    01450 #ifdef _DEBUG
    01451   if(!_suspended) {
    01452     assert(_stackbase == prevstackbase);
    01453   }
    01454 #endif
    01455   return true;
    01456 }
    01457
    01458 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,SQInteger nparams,SQObjectPtr &outres)
    01459 {
    01460   SQObjectPtr closure;
    01461   if(del->GetMetaMethod(this, mm, closure)) {
    01462     if(Call(closure, nparams, _top - nparams, outres, SQFalse, SQFalse)) {
    01463       Pop(nparams);
    01464       return true;
    01465     }
    01466   }
    01467   Pop(nparams);
    01468   return false;
    01469 }
    01470
    01471 void SQVM::Remove(SQInteger n) {
    01472   n = (n >= 0)?n + _stackbase - 1:_top + n;
    01473   for(SQInteger i = n; i < _top; i++){
    01474     _stack[i] = _stack[i+1];
    01475   }
    01476   _stack[_top] = _null_;
    01477   _top--;
    01478 }
    01479
    01480 void SQVM::Pop() {
    01481   _stack[--_top] = _null_;
    01482 }
    01483
    01484 void SQVM::Pop(SQInteger n) {
    01485   for(SQInteger i = 0; i < n; i++){
    01486     _stack[--_top] = _null_;
    01487   }
    01488 }
    01489
    01490 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
    01491 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
    01492 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
    01493 SQObjectPtr &SQVM::GetUp(SQInteger n) { return _stack[_top+n]; }
    01494 SQObjectPtr &SQVM::GetAt(SQInteger n) { return _stack[n]; }
    01495
    01496 #ifdef _DEBUG_DUMP
    01497 void SQVM::dumpstack(SQInteger stackbase,bool dumpall)
    01498 {
    01499   SQInteger size=dumpall?_stack.size():_top;
    01500   SQInteger n=0;
    01501   scprintf(_SC("\n>>>>stack dump<<<<\n"));
    01502   CallInfo &ci=_callsstack[_callsstacksize-1];
    01503   scprintf(_SC("IP: %p\n"),ci._ip);
    01504   scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
    01505   scprintf(_SC("prev top: %d\n"),ci._prevtop);
    01506   for(SQInteger i=0;i<size;i++){
    01507     SQObjectPtr &obj=_stack[i];
    01508     if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
    01509     scprintf(_SC("[%d]:"),n);
    01510     switch(type(obj)){
    01511     case OT_FLOAT:      scprintf(_SC("FLOAT %.3f"),_float(obj));break;
    01512     case OT_INTEGER:    scprintf(_SC("INTEGER %d"),_integer(obj));break;
    01513     case OT_BOOL:     scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
    01514     case OT_STRING:     scprintf(_SC("STRING %s"),_stringval(obj));break;
    01515     case OT_NULL:     scprintf(_SC("NULL"));  break;
    01516     case OT_TABLE:      scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
    01517     case OT_ARRAY:      scprintf(_SC("ARRAY %p"),_array(obj));break;
    01518     case OT_CLOSURE:    scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
    01519     case OT_NATIVECLOSURE:  scprintf(_SC("NATIVECLOSURE"));break;
    01520     case OT_USERDATA:   scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
    01521     case OT_GENERATOR:    scprintf(_SC("GENERATOR %p"),_generator(obj));break;
    01522     case OT_THREAD:     scprintf(_SC("THREAD [%p]"),_thread(obj));break;
    01523     case OT_USERPOINTER:  scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
    01524     case OT_CLASS:      scprintf(_SC("CLASS %p"),_class(obj));break;
    01525     case OT_INSTANCE:   scprintf(_SC("INSTANCE %p"),_instance(obj));break;
    01526     case OT_WEAKREF:    scprintf(_SC("WEAKERF %p"),_weakref(obj));break;
    01527     default:
    01528       assert(0);
    01529       break;
    01530     };
    01531     scprintf(_SC("\n"));
    01532     ++n;
    01533   }
    01534 }
    01535
    01536
    01537
    01538 #endif