2 see copyright notice in squirrel.h
4 #include "sqpcheader.h"
8 #include "sqfuncproto.h"
10 #include "sqclosure.h"
13 #include "squserdata.h"
17 #define TOP() (_stack[_top-1])
19 bool SQVM::BW_OP(unsigned int op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
22 SQInteger i1 = _integer(o1), i2 = _integer(o2);
23 if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER))
26 case BW_AND: res = i1 & i2; break;
27 case BW_OR: res = i1 | i2; break;
28 case BW_XOR: res = i1 ^ i2; break;
29 case BW_SHIFTL: res = i1 << i2; break;
30 case BW_SHIFTR: res = i1 >> i2; break;
31 case BW_USHIFTR:res = (SQInteger)(*((unsigned int*)&i1) >> i2); break;
32 default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; }
35 else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),GetTypeName(o1),GetTypeName(o2)); return false;}
40 bool SQVM::ARITH_OP(unsigned int op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
42 if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
43 if((type(o1)==OT_INTEGER) && (type(o2)==OT_INTEGER)) {
45 case '+': trg = _integer(o1) + _integer(o2); break;
46 case '-': trg = _integer(o1) - _integer(o2); break;
47 case '/': if(_integer(o2) == 0) { Raise_Error(_SC("division by zero")); return false; }
48 trg = _integer(o1) / _integer(o2);
50 case '*': trg = _integer(o1) * _integer(o2); break;
51 case '%': trg = _integer(o1) % _integer(o2); break;
55 case '+': trg = tofloat(o1) + tofloat(o2); break;
56 case '-': trg = tofloat(o1) - tofloat(o2); break;
57 case '/': trg = tofloat(o1) / tofloat(o2); break;
58 case '*': trg = tofloat(o1) * tofloat(o2); break;
59 case '%': trg = SQFloat(fmod((double)tofloat(o1),(double)tofloat(o2))); break;
63 if(op == '+' && (type(o1) == OT_STRING || type(o2) == OT_STRING)){
64 if(!StringCat(o1, o2, trg)) return false;
66 else if(!ArithMetaMethod(op,o1,o2,trg)) {
67 Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2)); return false;
73 SQObjectPtr &stack_get(HSQUIRRELVM v,int idx){return ((idx>=0)?(v->GetAt(idx+v->_stackbase-1)):(v->GetUp(idx)));}
75 SQVM::SQVM(SQSharedState *ss)
80 _suspended_root=false;
86 _errorhandler = _null_;
88 INIT_CHAIN();ADD_TO_CHAIN(&_ss(this)->_gc_chain,this);
95 _errorhandler = _null_;
98 int size=_stack.size();
99 for(int i=0;i<size;i++)
106 REMOVE_FROM_CHAIN(&_ss(this)->_gc_chain,this);
109 bool SQVM::ArithMetaMethod(int op,const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &dest)
113 case _SC('+'): mm=MT_ADD; break;
114 case _SC('-'): mm=MT_SUB; break;
115 case _SC('/'): mm=MT_DIV; break;
116 case _SC('*'): mm=MT_MUL; break;
117 case _SC('%'): mm=MT_MODULO; break;
118 default: mm=MT_ADD; assert(0); break;
120 if(is_delegable(o1) && _delegable(o1)->_delegate) {
122 return CallMetaMethod(_delegable(o1),mm,2,dest);
127 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
140 if(_delegable(o)->_delegate) {
142 if(CallMetaMethod(_delegable(o), MT_UNM, 1, temp_reg)) {
151 Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
155 #define _RET_SUCCEED(exp) { result = (exp); return true; }
156 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,int &result)
158 if(type(o1)==type(o2)){
159 if(_userpointer(o1)==_userpointer(o2))_RET_SUCCEED(0);
163 _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
165 _RET_SUCCEED(_integer(o1)-_integer(o2));
167 _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
172 if(_delegable(o1)->_delegate)CallMetaMethod(_delegable(o1),MT_CMP,2,res);
177 if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
178 _RET_SUCCEED(_integer(res));
181 if(sq_isnumeric(o1) && sq_isnumeric(o2)){
182 if((type(o1)==OT_INTEGER) && (type(o2)==OT_FLOAT)) {
183 if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
184 else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
188 if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
189 else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
193 else if(type(o1)==OT_NULL) {_RET_SUCCEED(-1);}
194 else if(type(o2)==OT_NULL) {_RET_SUCCEED(1);}
195 else { Raise_CompareError(o1,o2); return false; }
199 _RET_SUCCEED(0); //cannot happen
202 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
205 if(ObjCmp(o1,o2,r)) {
207 case CMP_G: res = (r > 0)?_true_:_false_; return true;
208 case CMP_GE: res = (r >= 0)?_true_:_false_; return true;
209 case CMP_L: res = (r < 0)?_true_:_false_; return true;
210 case CMP_LE: res = (r <= 0)?_true_:_false_; return true;
218 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
225 int l=_string(str)->_len,ol=_string(obj)->_len;
226 SQChar *s=_sp(rsl(l+ol+1));
227 memcpy(s,_stringval(str),rsl(l));memcpy(s+l,_stringval(obj),rsl(ol));s[l+ol]=_SC('\0');
231 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%g%s"),_float(str),_stringval(obj));
234 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%d%s"),_integer(str),_stringval(obj));
237 Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
240 dest=SQString::Create(_ss(this),_spval);
243 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%g"),_stringval(str),_float(obj));
244 dest=SQString::Create(_ss(this),_spval);
247 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%d"),_stringval(str),_integer(obj));
248 dest=SQString::Create(_ss(this),_spval);
251 Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
257 const SQChar *IdType2Name(SQObjectType type)
259 switch(_RAW_TYPE(type))
261 case _RT_NULL:return _SC("null");
262 case _RT_INTEGER:return _SC("integer");
263 case _RT_FLOAT:return _SC("float");
264 case _RT_BOOL:return _SC("bool");
265 case _RT_STRING:return _SC("string");
266 case _RT_TABLE:return _SC("table");
267 case _RT_ARRAY:return _SC("array");
268 case _RT_GENERATOR:return _SC("generator");
270 case _RT_NATIVECLOSURE:
271 return _SC("function");
273 case _RT_USERPOINTER:
274 return _SC("userdata");
275 case _RT_THREAD: return _SC("thread");
276 case _RT_FUNCPROTO: return _SC("function");
277 case _RT_CLASS: return _SC("class");
278 case _RT_INSTANCE: return _SC("instance");
284 const SQChar *GetTypeName(const SQObjectPtr &obj1)
286 return IdType2Name(type(obj1));
289 void SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
291 if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
293 if(CallMetaMethod(_delegable(obj1),MT_TYPEOF,1,dest))
296 dest = SQString::Create(_ss(this),GetTypeName(obj1));
299 bool SQVM::Init(SQVM *friendvm, int stacksize)
301 _stack.resize(stacksize);
302 _callsstack.reserve(4);
306 _roottable = SQTable::Create(_ss(this), 0);
308 _roottable = friendvm->_roottable;
309 _errorhandler = friendvm->_errorhandler;
310 _debughook = friendvm->_debughook;
313 sq_base_register(this);
317 extern SQInstructionDesc g_InstrDesc[];
319 bool SQVM::StartCall(SQClosure *closure,int target,int nargs,int stackbase,bool tailcall)
321 SQFunctionProto *func = _funcproto(closure->_function);
322 //const int outerssize = func->_outervalues.size();
324 const int paramssize = func->_parameters.size();
325 // const int oldtop = _top;
326 const int newtop = stackbase + func->_stacksize;
331 if (nargs < paramssize) {
332 Raise_Error(_SC("wrong number of parameters"));
335 for(int n = 0; n < nargs - paramssize; n++) {
336 _vargsstack.push_back(_stack[stackbase+paramssize+n]);
337 _stack[stackbase+paramssize+n] = _null_;
341 if (paramssize != nargs) {
342 Raise_Error(_SC("wrong number of parameters"));
349 PUSH_CALLINFO(this, CallInfo());
351 ci->_prevstkbase = stackbase - _stackbase;
352 ci->_target = target;
353 ci->_prevtop = _top - _stackbase;
360 ci->_vargs.size = (nargs - paramssize);
361 ci->_vargs.base = _vargsstack.size()-(nargs - paramssize);
362 ci->_closure._unVal.pClosure = closure;
363 ci->_closure._type = OT_CLOSURE;
364 ci->_iv = &func->_instructions;
365 ci->_literals = &func->_literals;
366 //grows the stack if needed
367 if (((unsigned int)newtop + (func->_stacksize<<1)) > _stack.size()) {
368 _stack.resize(_stack.size() + (func->_stacksize<<1));
372 _stackbase = stackbase;
373 ci->_ip = ci->_iv->_vals;
377 bool SQVM::Return(int _arg0, int _arg1, SQObjectPtr &retval)
379 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
380 for(int i=0;i<ci->_ncalls;i++)
381 CallDebugHook(_SC('r'));
383 bool broot = ci->_root;
385 int target = ci->_target;
386 int oldstackbase = _stackbase;
387 _stackbase -= ci->_prevstkbase;
388 _top = _stackbase + ci->_prevtop;
389 PopVarArgs(ci->_vargs);
392 if (_arg0 != MAX_FUNC_STACKSIZE) retval = _stack[oldstackbase+_arg1];
393 else retval = _null_;
396 if (_arg0 != MAX_FUNC_STACKSIZE)
397 STK(target) = _stack[oldstackbase+_arg1];
399 STK(target) = _null_;
402 while (last_top >= _top) _stack[last_top--].Null();
403 assert(oldstackbase >= _stackbase);
407 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
409 bool SQVM::LOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
411 _RET_ON_FAIL(ARITH_OP( op , target, a, incr));
416 bool SQVM::PLOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
419 _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
425 bool SQVM::DerefInc(int op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix)
427 SQObjectPtr tmp, tself = self, tkey = key;
428 if (!Get(tself, tkey, tmp, false, true)) { Raise_IdxError(tkey); return false; }
429 _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
430 Set(tself, tkey, target,true);
431 if (postfix) target = tmp;
435 #define arg0 (_i_._arg0)
436 #define arg1 (_i_._arg1)
437 #define sarg1 (*((int *)&_i_._arg1))
438 #define arg2 (_i_._arg2)
439 #define arg3 (_i_._arg3)
440 #define sarg3 (*((char *)&_i_._arg3))
442 SQRESULT SQVM::Suspend()
445 return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
446 if (_nnativecalls!=2)
447 return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
448 return SQ_SUSPEND_FLAG;
451 void SQVM::PopVarArgs(VarArgs &vargs)
453 for(int n = 0; n< vargs.size; n++)
454 _vargsstack.pop_back();
457 #define _FINISH(stoploop) {finished = stoploop; return true; }
458 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
459 &o3,SQObjectPtr &o4,int arg_2,bool &finished)
464 if((nrefidx = _table(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
465 o4 = (SQInteger)nrefidx; _FINISH(false);
467 if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
468 o4 = (SQInteger) nrefidx; _FINISH(false);
470 if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
471 o4 = (SQInteger)nrefidx; _FINISH(false);
473 if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
474 o4 = (SQInteger)nrefidx; _FINISH(false);
477 if(_delegable(o1)->_delegate) {
481 if(CallMetaMethod(_delegable(o1), MT_NEXTI, 2, itr)){
483 if(type(itr) == OT_NULL) _FINISH(true);
484 if(!Get(o1, itr, o3, false,false)) {
485 Raise_Error(_SC("_nexti returned an invalid idx"));
490 Raise_Error(_SC("_nexti failed"));
495 if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(true);
496 if(_generator(o1)->_state == SQGenerator::eSuspended) {
498 if(type(o4) == OT_INTEGER) {
499 idx = _integer(o4) + 1;
503 _generator(o1)->Resume(this, arg_2+1);
509 Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
510 return false; //cannot be hit(just to avoid warnings)
513 bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2)
515 if(type(o1) != OT_TABLE) { Raise_Error(_SC("delegating a '%s'"), GetTypeName(o1)); return false; }
518 if(!_table(o1)->SetDelegate(_table(o2))){
519 Raise_Error(_SC("delegate cycle detected"));
524 _table(o1)->SetDelegate(NULL);
527 Raise_Error(_SC("using '%s' as delegate"), GetTypeName(o2));
534 #define COND_LITERAL (arg3!=0?(*ci->_literals)[arg1]:STK(arg1))
536 #define _GUARD(exp) { if(!exp) { Raise_Error(_lasterror); SQ_THROW();} }
538 #define SQ_THROW() { goto exception_trap; }
540 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
543 SQClosure *closure = SQClosure::Create(_ss(this), func);
544 if( (nouters = func->_outervalues.size()) ) {
545 closure->_outervalues.reserve(nouters);
546 for(int i = 0; i<nouters; i++) {
547 SQOuterVar &v = func->_outervalues[i];
550 closure->_outervalues.push_back(_null_);
551 if(!Get(_stack._vals[_stackbase]/*STK(0)*/, v._src, closure->_outervalues.top(), false,true))
552 {Raise_IdxError(v._src); return false; }
555 closure->_outervalues.push_back(_stack._vals[_stackbase+_integer(v._src)]);
558 closure->_outervalues.push_back(_closure(ci->_closure)->_outervalues[_integer(v._src)]);
568 bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci)
570 if(ci->_vargs.size == 0) {
571 Raise_Error(_SC("the function doesn't have var args"));
574 if(!sq_isnumeric(index)){
575 Raise_Error(_SC("indexing 'vargv' with %s"),GetTypeName(index));
578 int idx = tointeger(index);
579 if(idx < 0 || idx >= ci->_vargs.size){ Raise_Error(_SC("vargv index out of range")); return false; }
580 target = _vargsstack[ci->_vargs.base+idx];
584 bool SQVM::CLASS_OP(SQObjectPtr &target,int baseclass,int attributes)
586 SQClass *base = NULL;
588 if(baseclass != MAX_LITERALS) {
589 if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
590 base = _class(_stack._vals[_stackbase + baseclass]);
592 if(attributes != MAX_FUNC_STACKSIZE) {
593 attrs = _stack._vals[_stackbase+attributes];
595 target = SQClass::Create(_ss(this),base);
596 _class(target)->_attributes = attrs;
600 bool SQVM::IsFalse(SQObjectPtr &o)
602 SQObjectType t = type(o);
603 if((t & SQOBJECT_CANBEFALSE)
604 && ((t == OT_NULL) || ((t == OT_INTEGER || t == OT_BOOL) && _integer(o) == 0)
605 || (t == OT_FLOAT && _float(o) == SQFloat(0.0)))) {
611 bool SQVM::IsEqual(SQObjectPtr &o1,SQObjectPtr &o2,bool &res)
613 if(type(o1) == type(o2)) {
614 res = ((_userpointer(o1) == _userpointer(o2)?true:false));
617 if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
619 if(!ObjCmp(o1, o2,cmpres)) return false;
629 bool SQVM::Execute(SQObjectPtr &closure, int target, int nargs, int stackbase,SQObjectPtr &outres, ExecutionType et)
631 if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
633 AutoDec ad(&_nnativecalls);
635 //temp_reg vars for OP_CALL
641 if(!StartCall(_closure(closure), _top - nargs, nargs, stackbase, false)) {
642 //call the handler if there are no calls in the stack, if not relies on the previous node
643 if(ci == NULL) CallErrorHandler(_lasterror);
648 case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, target); ci->_root = true; traps += ci->_etraps; break;
650 traps = _suspended_traps;
651 ci->_root = _suspended_root;
661 const SQInstruction &_i_ = *ci->_ip++;
662 //dumpstack(_stackbase);
663 //scprintf("\n[%d] %s %d %d %d %d\n",ci->_ip-ci->_iv->_vals,g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
667 if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
668 CallDebugHook(_SC('l'),arg1);
670 case _OP_LOAD: TARGET = (*ci->_literals)[arg1]; continue;
672 temp_reg = STK(arg1);
673 if (type(temp_reg) == OT_CLOSURE){
675 PopVarArgs(ci->_vargs);
676 for (int i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
677 ct_target = ci->_target;
683 temp_reg = STK(arg1);
686 switch (type(temp_reg)) {
688 StartCall(_closure(temp_reg), ct_target, arg3, ct_tailcall?_stackbase:_stackbase+arg2, ct_tailcall);
689 if (_funcproto(_closure(temp_reg)->_function)->_bgenerator) {
690 SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(temp_reg));
691 _GUARD(gen->Yield(this));
692 Return(1, ct_target, temp_reg);
693 STK(ct_target) = gen;
694 while (last_top >= _top) _stack[last_top--].Null();
697 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
698 CallDebugHook(_SC('c'));
701 case OT_NATIVECLOSURE: {
703 _GUARD(CallNative(_nativeclosure(temp_reg), arg3, _stackbase+arg2, ct_tailcall, temp_reg,suspend));
706 _suspended_target = ct_target;
707 _suspended_root = ci->_root;
708 _suspended_traps = traps;
712 STK(ct_target) = temp_reg;
716 _GUARD(CreateClassInstance(_class(temp_reg),arg3,_stackbase+arg2,STK(ct_target)));
724 for (int i = 0; i < arg3; i++) Push(STK(arg2 + i));
725 if (_delegable(temp_reg) && CallMetaMethod(_delegable(temp_reg), MT_CALL, arg3+1, temp_reg)){
726 STK(ct_target) = temp_reg;
729 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
733 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
739 if (!Get(STK(arg2), STK(arg1), temp_reg, false,true))
740 { Raise_IdxError(STK(arg1)); SQ_THROW(); }
741 goto common_prepcall;
743 if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg,false,true)) {
744 if(type(STK(arg2)) == OT_CLASS) { //hack?
745 if(_class_ddel->Get((*ci->_literals)[arg1],temp_reg)) {
746 STK(arg3) = STK(arg2);
751 { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
754 if(type(STK(arg2)) == OT_CLASS) {
755 STK(arg3) = STK(0); // this
758 STK(arg3) = STK(arg2);
763 if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg, false,true)) { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
766 case _OP_MOVE: TARGET = STK(arg1); continue;
768 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
769 if(arg0 != arg3) TARGET = STK(arg3);
771 case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
773 if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
774 if (arg0 != arg3) TARGET = STK(arg3);
777 if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
782 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
783 TARGET = res?_true_:_false_;
787 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
788 TARGET = (!res)?_true_:_false_;
790 case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
791 case _OP_BITW: _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
793 if(type((ci)->_generator) == OT_GENERATOR) {
794 _generator((ci)->_generator)->Kill();
796 if(Return(arg0, arg1, temp_reg)){
802 case _OP_LOADNULLS:{ for(unsigned int n=0;n<arg1;n++) STK(arg0+n) = _null_; }continue;
803 case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
804 case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
805 case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
806 case _OP_JMP: ci->_ip += (sarg1); continue;
807 case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
808 case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
809 case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
810 case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
812 if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); }
814 case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
815 case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
816 case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL); continue;
818 switch(type(STK(arg1))) {
820 TARGET = _table(STK(arg1))->_delegate?SQObjectPtr(_table(STK(arg1))->_delegate):_null_;
822 case OT_CLASS: TARGET = _class(STK(arg1))->_base?_class(STK(arg1))->_base:_null_;
827 Raise_Error(_SC("the %s type doesn't have a parent slot"), GetTypeName(STK(arg1)));
830 case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((unsigned int)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
831 case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
832 case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
833 case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
834 case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
835 case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
836 case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET)) continue;
837 case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
839 if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
840 {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
841 TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
844 if(IsFalse(STK(arg2))) {
850 if(!IsFalse(STK(arg2))) {
855 case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
856 case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
858 if(type(STK(arg1)) == OT_INTEGER) {
859 TARGET = SQInteger(~_integer(STK(arg1)));
862 Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
865 SQClosure *c = ci->_closure._unVal.pClosure;
866 SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
867 if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
871 if(type(ci->_generator) == OT_GENERATOR) {
872 if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
873 _GUARD(_generator(ci->_generator)->Yield(this));
874 traps -= ci->_etraps;
875 if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
877 else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
878 if(Return(arg0, arg1, temp_reg)){
887 if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
888 _GUARD(_generator(STK(arg1))->Resume(this, arg0));
889 traps += ci->_etraps;
891 case _OP_FOREACH:{ bool finished;
892 _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,finished));
893 if(finished) ci->_ip += sarg1; }
895 case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
897 if(!Clone(STK(arg1), TARGET))
898 { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
900 case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
902 _etraps.push_back(SQExceptionTrap(_top,_stackbase, &ci->_iv->_vals[(ci->_ip-ci->_iv->_vals)+arg1], arg0)); traps++;
906 for(int i=0; i<arg0; i++) {
907 _etraps.pop_back(); traps--;
911 case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
912 case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
914 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
915 _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
916 if(arg0 != arg3) TARGET = STK(arg3);
924 SQObjectPtr currerror = _lasterror;
925 // dumpstack(_stackbase);
931 if(ci->_etraps > 0) {
932 SQExceptionTrap &et = _etraps.top();
934 _top = et._stacksize;
935 _stackbase = et._stackbase;
936 _stack[_stackbase+et._extarget] = currerror;
937 _etraps.pop_back(); traps--; ci->_etraps--;
938 while(last_top >= _top) _stack[last_top--].Null();
939 goto exception_restore;
941 //if is a native closure
942 if(type(ci->_closure) != OT_CLOSURE && n)
944 if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
945 PopVarArgs(ci->_vargs);
948 }while(_callsstack.size());
951 CallErrorHandler(currerror);
952 //remove call stack until a C function is found or the cstack is empty
954 bool exitafterthisone = ci->_root;
955 if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
956 _stackbase -= ci->_prevstkbase;
957 _top = _stackbase + ci->_prevtop;
958 PopVarArgs(ci->_vargs);
960 if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
961 }while(_callsstack.size());
963 while(last_top >= _top) _stack[last_top--].Null();
965 _lasterror = currerror;
971 bool SQVM::CreateClassInstance(SQClass *theclass, int nargs, int stackbase, SQObjectPtr &retval)
974 SQObjectPtr inst = theclass->CreateInstance();
975 _stack[stackbase] = inst;
976 if(theclass->Get(_ss(this)->_constructoridx,constr)) {
977 if(!Call(constr,nargs,stackbase,constr))
984 void SQVM::CallErrorHandler(SQObjectPtr &error)
986 if(type(_errorhandler) != OT_NULL) {
988 Push(_roottable); Push(error);
989 Call(_errorhandler, 2, _top-2, out);
994 void SQVM::CallDebugHook(int type,int forcedline)
996 SQObjectPtr temp_reg;
998 SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
999 Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
1000 Call(_debughook,nparams,_top-nparams,temp_reg);
1004 bool SQVM::CallNative(SQNativeClosure *nclosure,int nargs,int stackbase,bool tailcall,SQObjectPtr &retval,bool &suspend)
1007 if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
1008 int nparamscheck = nclosure->_nparamscheck;
1009 if(((nparamscheck > 0) && (nparamscheck != nargs))
1010 || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
1011 Raise_Error(_SC("wrong number of parameters"));
1016 if( (tcs = nclosure->_typecheck.size()) ) {
1017 for(int i = 0; i < nargs && i < tcs; i++)
1018 if((nclosure->_typecheck[i] != -1) && !(type(_stack[stackbase+i]) & nclosure->_typecheck[i])) {
1019 Raise_ParamTypeError(i,nclosure->_typecheck[i],type(_stack[stackbase+i]));
1024 if ((_top + MIN_STACK_OVERHEAD) > (int)_stack.size()) {
1025 _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
1028 int oldstackbase = _stackbase;
1029 _top = stackbase + nargs;
1030 PUSH_CALLINFO(this, CallInfo());
1032 ci->_closure._unVal.pNativeClosure = nclosure;
1033 ci->_closure._type = OT_NATIVECLOSURE;
1034 ci->_prevstkbase = stackbase - _stackbase;
1036 _stackbase = stackbase;
1037 //push free variables
1038 int outers = nclosure->_outervalues.size();
1039 for (int i = 0; i < outers; i++) {
1040 Push(nclosure->_outervalues[i]);
1042 ci->_prevtop = (oldtop - oldstackbase);
1043 int ret = (nclosure->_function)(this);
1046 if( ret == SQ_SUSPEND_FLAG) suspend = true;
1048 _stackbase = oldstackbase;
1051 Raise_Error(_lasterror);
1055 if (ret != 0){ retval = TOP(); }
1056 else { retval = _null_; }
1057 _stackbase = oldstackbase;
1063 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
1067 if(_table(self)->Get(key,dest))return true;
1070 if(sq_isnumeric(key)){
1071 return _array(self)->Get(tointeger(key),dest);
1075 if(_instance(self)->Get(key,dest)) return true;
1080 if(FallBackGet(self,key,dest,raw)) return true;
1083 if(_rawval(STK(0)) == _rawval(self) &&
1084 type(STK(0)) == type(self)) {
1085 return _table(_roottable)->Get(key,dest);
1091 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
1095 return _class(self)->Get(key,dest);
1100 if(_delegable(self)->_delegate) {
1101 if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
1103 if(raw)return false;
1104 Push(self);Push(key);
1105 if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
1108 if(type(self) == OT_TABLE) {
1109 if(raw) return false;
1110 return _table_ddel->Get(key,dest);
1115 if(raw)return false;
1116 return _array_ddel->Get(key,dest);
1118 if(sq_isnumeric(key)){
1119 SQInteger n=tointeger(key);
1120 if(abs(n)<_string(self)->_len){
1121 if(n<0)n=_string(self)->_len-n;
1122 dest=SQInteger(_stringval(self)[n]);
1128 if(raw)return false;
1129 return _string_ddel->Get(key,dest);
1133 if(raw)return false;
1134 Push(self);Push(key);
1135 if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
1136 return _instance_ddel->Get(key,dest);
1139 case OT_INTEGER:case OT_FLOAT:case OT_BOOL:
1140 if(raw)return false;
1141 return _number_ddel->Get(key,dest);
1143 if(raw)return false;
1144 return _generator_ddel->Get(key,dest);
1145 case OT_CLOSURE: case OT_NATIVECLOSURE:
1146 if(raw)return false;
1147 return _closure_ddel->Get(key,dest);
1149 if(raw)return false;
1150 return _thread_ddel->Get(key,dest);
1151 default:return false;
1156 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
1160 if(_table(self)->Set(key,val))
1162 if(_table(self)->_delegate) {
1163 if(Set(_table(self)->_delegate,key,val,false)) {
1169 if(_delegable(self)->_delegate) {
1171 Push(self);Push(key);Push(val);
1172 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1176 if(_instance(self)->Set(key,val))
1179 Push(self);Push(key);Push(val);
1180 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1184 if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
1185 return _array(self)->Set(tointeger(key),val);
1187 Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
1191 if(_rawval(STK(0)) == _rawval(self) &&
1192 type(STK(0)) == type(self)) {
1193 return _table(_roottable)->Set(key,val);
1199 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
1201 SQObjectPtr temp_reg;
1204 target = _table(self)->Clone();
1207 target = _instance(self)->Clone(_ss(this));
1209 if(_delegable(target)->_delegate){
1212 CallMetaMethod(_delegable(target),MT_CLONED,2,temp_reg);
1216 target=_array(self)->Clone();
1218 default: return false;
1222 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val)
1224 if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
1225 switch(type(self)) {
1227 bool rawcall = true;
1228 if(_table(self)->_delegate) {
1230 if(!_table(self)->Get(key,res)) {
1231 Push(self);Push(key);Push(val);
1232 rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
1235 if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
1239 if(!_class(self)->NewSlot(key,val)) {
1240 if(_class(self)->_locked) {
1241 Raise_Error(_SC("trying to modify a class that has already been instantiated"));
1245 SQObjectPtr oval = PrintObjVal(key);
1246 Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
1252 Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
1259 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
1261 switch(type(self)) {
1266 bool handled = false;
1267 if(_delegable(self)->_delegate) {
1268 Push(self);Push(key);
1269 handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
1273 if(type(self) == OT_TABLE) {
1274 if(_table(self)->Get(key,t)) {
1275 _table(self)->Remove(key);
1278 Raise_IdxError((SQObject &)key);
1283 Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
1291 Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
1297 bool SQVM::Call(SQObjectPtr &closure,int nparams,int stackbase,SQObjectPtr &outres)
1300 int prevstackbase = _stackbase;
1302 switch(type(closure)) {
1304 return Execute(closure, _top - nparams, nparams, stackbase,outres);
1306 case OT_NATIVECLOSURE:{
1308 return CallNative(_nativeclosure(closure), nparams, stackbase, false, outres,suspend);
1313 return CreateClassInstance(_class(closure),nparams,stackbase,outres);
1320 assert(_stackbase == prevstackbase);
1326 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,int nparams,SQObjectPtr &outres)
1328 SQObjectPtr closure;
1329 if(del->GetMetaMethod(mm, closure)) {
1330 if(Call(closure, nparams, _top - nparams, outres)) {
1340 _stack[--_top] = _null_;
1342 void SQVM::Pop(int n) {
1343 for(int i = 0; i < n; i++){
1344 _stack[--_top] = _null_;
1348 void SQVM::Remove(int n) {
1349 n = (n >= 0)?n + _stackbase - 1:_top + n;
1350 for(int i = n; i < _top; i++){
1351 _stack[i] = _stack[i+1];
1353 _stack[_top] = _null_;
1357 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
1358 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
1359 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
1360 SQObjectPtr &SQVM::GetUp(int n) { return _stack[_top+n]; }
1361 SQObjectPtr &SQVM::GetAt(int n) { return _stack[n]; }
1364 void SQVM::dumpstack(int stackbase,bool dumpall)
1366 int size=dumpall?_stack.size():_top;
1368 scprintf(_SC("\n>>>>stack dump<<<<\n"));
1369 CallInfo &ci=_callsstack.back();
1370 scprintf(_SC("IP: %d\n"),ci._ip);
1371 scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
1372 scprintf(_SC("prev top: %d\n"),ci._prevtop);
1373 for(int i=0;i<size;i++){
1374 SQObjectPtr &obj=_stack[i];
1375 if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
1376 scprintf(_SC("[%d]:"),n);
1378 case OT_FLOAT: scprintf(_SC("FLOAT %.3f"),_float(obj));break;
1379 case OT_INTEGER: scprintf(_SC("INTEGER %d"),_integer(obj));break;
1380 case OT_BOOL: scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
1381 case OT_STRING: scprintf(_SC("STRING %s"),_stringval(obj));break;
1382 case OT_NULL: scprintf(_SC("NULL")); break;
1383 case OT_TABLE: scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
1384 case OT_ARRAY: scprintf(_SC("ARRAY %p"),_array(obj));break;
1385 case OT_CLOSURE: scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
1386 case OT_NATIVECLOSURE: scprintf(_SC("NATIVECLOSURE"));break;
1387 case OT_USERDATA: scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
1388 case OT_GENERATOR: scprintf(_SC("GENERATOR"));break;
1389 case OT_THREAD: scprintf(_SC("THREAD [%p]"),_thread(obj));break;
1390 case OT_USERPOINTER: scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
1391 case OT_CLASS: scprintf(_SC("CLASS %p"),_class(obj));break;
1392 case OT_INSTANCE: scprintf(_SC("INSTANCE %p"),_instance(obj));break;
1397 scprintf(_SC("\n"));