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;
119 if(is_delegable(o1) && _delegable(o1)->_delegate) {
121 return CallMetaMethod(_delegable(o1),mm,2,dest);
126 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
139 if(_delegable(o)->_delegate) {
141 if(CallMetaMethod(_delegable(o), MT_UNM, 1, temp_reg)) {
150 Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
154 #define _RET_SUCCEED(exp) { result = (exp); return true; }
155 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,int &result)
157 if(type(o1)==type(o2)){
158 if(_userpointer(o1)==_userpointer(o2))_RET_SUCCEED(0);
162 _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
164 _RET_SUCCEED(_integer(o1)-_integer(o2));
166 _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
171 if(_delegable(o1)->_delegate)CallMetaMethod(_delegable(o1),MT_CMP,2,res);
176 if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
177 _RET_SUCCEED(_integer(res));
180 if(sq_isnumeric(o1) && sq_isnumeric(o2)){
181 if((type(o1)==OT_INTEGER) && (type(o2)==OT_FLOAT)) {
182 if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
183 else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
187 if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
188 else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
192 else if(type(o1)==OT_NULL) {_RET_SUCCEED(-1);}
193 else if(type(o2)==OT_NULL) {_RET_SUCCEED(1);}
194 else { Raise_CompareError(o1,o2); return false; }
198 _RET_SUCCEED(0); //cannot happen
201 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
204 if(ObjCmp(o1,o2,r)) {
206 case CMP_G: res = (r > 0)?_true_:_false_; return true;
207 case CMP_GE: res = (r >= 0)?_true_:_false_; return true;
208 case CMP_L: res = (r < 0)?_true_:_false_; return true;
209 case CMP_LE: res = (r <= 0)?_true_:_false_; return true;
217 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
224 int l=_string(str)->_len,ol=_string(obj)->_len;
225 SQChar *s=_sp(rsl(l+ol+1));
226 memcpy(s,_stringval(str),rsl(l));memcpy(s+l,_stringval(obj),rsl(ol));s[l+ol]=_SC('\0');
230 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%g%s"),_float(str),_stringval(obj));
233 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(obj)->_len+1)),_SC("%d%s"),_integer(str),_stringval(obj));
236 Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
239 dest=SQString::Create(_ss(this),_spval);
242 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%g"),_stringval(str),_float(obj));
243 dest=SQString::Create(_ss(this),_spval);
246 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+_string(str)->_len+1)),_SC("%s%d"),_stringval(str),_integer(obj));
247 dest=SQString::Create(_ss(this),_spval);
250 Raise_Error(_SC("string concatenation between '%s' and '%s'"),GetTypeName(str),GetTypeName(obj));
256 const SQChar *IdType2Name(SQObjectType type)
258 switch(_RAW_TYPE(type))
260 case _RT_NULL:return _SC("null");
261 case _RT_INTEGER:return _SC("integer");
262 case _RT_FLOAT:return _SC("float");
263 case _RT_BOOL:return _SC("bool");
264 case _RT_STRING:return _SC("string");
265 case _RT_TABLE:return _SC("table");
266 case _RT_ARRAY:return _SC("array");
267 case _RT_GENERATOR:return _SC("generator");
269 case _RT_NATIVECLOSURE:
270 return _SC("function");
272 case _RT_USERPOINTER:
273 return _SC("userdata");
274 case _RT_THREAD: return _SC("thread");
275 case _RT_FUNCPROTO: return _SC("function");
276 case _RT_CLASS: return _SC("class");
277 case _RT_INSTANCE: return _SC("instance");
283 const SQChar *GetTypeName(const SQObjectPtr &obj1)
285 return IdType2Name(type(obj1));
288 void SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
290 if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
292 if(CallMetaMethod(_delegable(obj1),MT_TYPEOF,1,dest))
295 dest = SQString::Create(_ss(this),GetTypeName(obj1));
298 bool SQVM::Init(SQVM *friendvm, int stacksize)
300 _stack.resize(stacksize);
301 _callsstack.reserve(4);
305 _roottable = SQTable::Create(_ss(this), 0);
307 _roottable = friendvm->_roottable;
308 _errorhandler = friendvm->_errorhandler;
309 _debughook = friendvm->_debughook;
312 sq_base_register(this);
316 extern SQInstructionDesc g_InstrDesc[];
318 bool SQVM::StartCall(SQClosure *closure,int target,int nargs,int stackbase,bool tailcall)
320 SQFunctionProto *func = _funcproto(closure->_function);
321 //const int outerssize = func->_outervalues.size();
323 const int paramssize = func->_parameters.size();
324 // const int oldtop = _top;
325 const int newtop = stackbase + func->_stacksize;
330 if (nargs < paramssize) {
331 Raise_Error(_SC("wrong number of parameters"));
334 for(int n = 0; n < nargs - paramssize; n++) {
335 _vargsstack.push_back(_stack[stackbase+paramssize+n]);
336 _stack[stackbase+paramssize+n] = _null_;
340 if (paramssize != nargs) {
341 Raise_Error(_SC("wrong number of parameters"));
348 PUSH_CALLINFO(this, CallInfo());
350 ci->_prevstkbase = stackbase - _stackbase;
351 ci->_target = target;
352 ci->_prevtop = _top - _stackbase;
359 ci->_vargs.size = (nargs - paramssize);
360 ci->_vargs.base = _vargsstack.size()-(nargs - paramssize);
361 ci->_closure._unVal.pClosure = closure;
362 ci->_closure._type = OT_CLOSURE;
363 ci->_iv = &func->_instructions;
364 ci->_literals = &func->_literals;
365 //grows the stack if needed
366 if (((unsigned int)newtop + (func->_stacksize<<1)) > _stack.size()) {
367 _stack.resize(_stack.size() + (func->_stacksize<<1));
371 _stackbase = stackbase;
372 ci->_ip = ci->_iv->_vals;
376 bool SQVM::Return(int _arg0, int _arg1, SQObjectPtr &retval)
378 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
379 for(int i=0;i<ci->_ncalls;i++)
380 CallDebugHook(_SC('r'));
382 bool broot = ci->_root;
384 int target = ci->_target;
385 int oldstackbase = _stackbase;
386 _stackbase -= ci->_prevstkbase;
387 _top = _stackbase + ci->_prevtop;
388 PopVarArgs(ci->_vargs);
391 if (_arg0 != MAX_FUNC_STACKSIZE) retval = _stack[oldstackbase+_arg1];
392 else retval = _null_;
395 if (_arg0 != MAX_FUNC_STACKSIZE)
396 STK(target) = _stack[oldstackbase+_arg1];
398 STK(target) = _null_;
401 while (last_top >= _top) _stack[last_top--].Null();
402 assert(oldstackbase >= _stackbase);
406 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
408 bool SQVM::LOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
410 _RET_ON_FAIL(ARITH_OP( op , target, a, incr));
415 bool SQVM::PLOCAL_INC(int op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
418 _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
424 bool SQVM::DerefInc(int op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix)
426 SQObjectPtr tmp, tself = self, tkey = key;
427 if (!Get(tself, tkey, tmp, false, true)) { Raise_IdxError(tkey); return false; }
428 _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
429 Set(tself, tkey, target,true);
430 if (postfix) target = tmp;
434 #define arg0 (_i_._arg0)
435 #define arg1 (_i_._arg1)
436 #define sarg1 (*((int *)&_i_._arg1))
437 #define arg2 (_i_._arg2)
438 #define arg3 (_i_._arg3)
439 #define sarg3 (*((char *)&_i_._arg3))
441 SQRESULT SQVM::Suspend()
444 return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
445 if (_nnativecalls!=2)
446 return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
447 return SQ_SUSPEND_FLAG;
450 void SQVM::PopVarArgs(VarArgs &vargs)
452 for(int n = 0; n< vargs.size; n++)
453 _vargsstack.pop_back();
456 #define _FINISH(stoploop) {finished = stoploop; return true; }
457 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
458 &o3,SQObjectPtr &o4,int arg_2,bool &finished)
463 if((nrefidx = _table(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
464 o4 = (SQInteger)nrefidx; _FINISH(false);
466 if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(true);
467 o4 = (SQInteger) nrefidx; _FINISH(false);
469 if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
470 o4 = (SQInteger)nrefidx; _FINISH(false);
472 if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(true);
473 o4 = (SQInteger)nrefidx; _FINISH(false);
476 if(_delegable(o1)->_delegate) {
480 if(CallMetaMethod(_delegable(o1), MT_NEXTI, 2, itr)){
482 if(type(itr) == OT_NULL) _FINISH(true);
483 if(!Get(o1, itr, o3, false,false)) {
484 Raise_Error(_SC("_nexti returned an invalid idx"));
489 Raise_Error(_SC("_nexti failed"));
494 if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(true);
495 if(_generator(o1)->_state == SQGenerator::eSuspended) {
497 if(type(o4) == OT_INTEGER) {
498 idx = _integer(o4) + 1;
502 _generator(o1)->Resume(this, arg_2+1);
508 Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
509 return false; //cannot be hit(just to avoid warnings)
512 bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2)
514 if(type(o1) != OT_TABLE) { Raise_Error(_SC("delegating a '%s'"), GetTypeName(o1)); return false; }
517 if(!_table(o1)->SetDelegate(_table(o2))){
518 Raise_Error(_SC("delegate cycle detected"));
523 _table(o1)->SetDelegate(NULL);
526 Raise_Error(_SC("using '%s' as delegate"), GetTypeName(o2));
533 #define COND_LITERAL (arg3!=0?(*ci->_literals)[arg1]:STK(arg1))
535 #define _GUARD(exp) { if(!exp) { Raise_Error(_lasterror); SQ_THROW();} }
537 #define SQ_THROW() { goto exception_trap; }
539 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
542 SQClosure *closure = SQClosure::Create(_ss(this), func);
543 if( (nouters = func->_outervalues.size()) ) {
544 closure->_outervalues.reserve(nouters);
545 for(int i = 0; i<nouters; i++) {
546 SQOuterVar &v = func->_outervalues[i];
549 closure->_outervalues.push_back(_null_);
550 if(!Get(_stack._vals[_stackbase]/*STK(0)*/, v._src, closure->_outervalues.top(), false,true))
551 {Raise_IdxError(v._src); return false; }
554 closure->_outervalues.push_back(_stack._vals[_stackbase+_integer(v._src)]);
557 closure->_outervalues.push_back(_closure(ci->_closure)->_outervalues[_integer(v._src)]);
567 bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci)
569 if(ci->_vargs.size == 0) {
570 Raise_Error(_SC("the function doesn't have var args"));
573 if(!sq_isnumeric(index)){
574 Raise_Error(_SC("indexing 'vargv' with %s"),GetTypeName(index));
577 int idx = tointeger(index);
578 if(idx < 0 || idx >= ci->_vargs.size){ Raise_Error(_SC("vargv index out of range")); return false; }
579 target = _vargsstack[ci->_vargs.base+idx];
583 bool SQVM::CLASS_OP(SQObjectPtr &target,int baseclass,int attributes)
585 SQClass *base = NULL;
587 if(baseclass != MAX_LITERALS) {
588 if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
589 base = _class(_stack._vals[_stackbase + baseclass]);
591 if(attributes != MAX_FUNC_STACKSIZE) {
592 attrs = _stack._vals[_stackbase+attributes];
594 target = SQClass::Create(_ss(this),base);
595 _class(target)->_attributes = attrs;
599 bool SQVM::IsFalse(SQObjectPtr &o)
601 SQObjectType t = type(o);
602 if((t & SQOBJECT_CANBEFALSE)
603 && ((t == OT_NULL) || ((t == OT_INTEGER || t == OT_BOOL) && _integer(o) == 0)
604 || (t == OT_FLOAT && _float(o) == SQFloat(0.0)))) {
610 bool SQVM::IsEqual(SQObjectPtr &o1,SQObjectPtr &o2,bool &res)
612 if(type(o1) == type(o2)) {
613 res = ((_userpointer(o1) == _userpointer(o2)?true:false));
616 if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
618 if(!ObjCmp(o1, o2,cmpres)) return false;
628 bool SQVM::Execute(SQObjectPtr &closure, int target, int nargs, int stackbase,SQObjectPtr &outres, ExecutionType et)
630 if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
632 AutoDec ad(&_nnativecalls);
634 //temp_reg vars for OP_CALL
640 if(!StartCall(_closure(closure), _top - nargs, nargs, stackbase, false)) {
641 //call the handler if there are no calls in the stack, if not relies on the previous node
642 if(ci == NULL) CallErrorHandler(_lasterror);
647 case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, target); ci->_root = true; traps += ci->_etraps; break;
649 traps = _suspended_traps;
650 ci->_root = _suspended_root;
660 const SQInstruction &_i_ = *ci->_ip++;
661 //dumpstack(_stackbase);
662 //scprintf("\n[%d] %s %d %d %d %d\n",ci->_ip-ci->_iv->_vals,g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
666 if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
667 CallDebugHook(_SC('l'),arg1);
669 case _OP_LOAD: TARGET = (*ci->_literals)[arg1]; continue;
671 temp_reg = STK(arg1);
672 if (type(temp_reg) == OT_CLOSURE){
674 PopVarArgs(ci->_vargs);
675 for (int i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
676 ct_target = ci->_target;
682 temp_reg = STK(arg1);
685 switch (type(temp_reg)) {
687 StartCall(_closure(temp_reg), ct_target, arg3, ct_tailcall?_stackbase:_stackbase+arg2, ct_tailcall);
688 if (_funcproto(_closure(temp_reg)->_function)->_bgenerator) {
689 SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(temp_reg));
690 _GUARD(gen->Yield(this));
691 Return(1, ct_target, temp_reg);
692 STK(ct_target) = gen;
693 while (last_top >= _top) _stack[last_top--].Null();
696 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
697 CallDebugHook(_SC('c'));
700 case OT_NATIVECLOSURE: {
702 _GUARD(CallNative(_nativeclosure(temp_reg), arg3, _stackbase+arg2, ct_tailcall, temp_reg,suspend));
705 _suspended_target = ct_target;
706 _suspended_root = ci->_root;
707 _suspended_traps = traps;
711 STK(ct_target) = temp_reg;
715 _GUARD(CreateClassInstance(_class(temp_reg),arg3,_stackbase+arg2,STK(ct_target)));
723 for (int i = 0; i < arg3; i++) Push(STK(arg2 + i));
724 if (_delegable(temp_reg) && CallMetaMethod(_delegable(temp_reg), MT_CALL, arg3+1, temp_reg)){
725 STK(ct_target) = temp_reg;
728 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
732 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(temp_reg));
738 if (!Get(STK(arg2), STK(arg1), temp_reg, false,true))
739 { Raise_IdxError(STK(arg1)); SQ_THROW(); }
740 goto common_prepcall;
742 if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg,false,true)) {
743 if(type(STK(arg2)) == OT_CLASS) { //hack?
744 if(_class_ddel->Get((*ci->_literals)[arg1],temp_reg)) {
745 STK(arg3) = STK(arg2);
750 { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
753 if(type(STK(arg2)) == OT_CLASS) {
754 STK(arg3) = STK(0); // this
757 STK(arg3) = STK(arg2);
762 if (!Get(STK(arg2), (*ci->_literals)[arg1], temp_reg, false,true)) { Raise_IdxError((*ci->_literals)[arg1]); SQ_THROW();}
765 case _OP_MOVE: TARGET = STK(arg1); continue;
767 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
768 if(arg0 != arg3) TARGET = STK(arg3);
770 case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
772 if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
773 if (arg0 != arg3) TARGET = STK(arg3);
776 if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
781 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
782 TARGET = res?_true_:_false_;
786 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
787 TARGET = (!res)?_true_:_false_;
789 case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
790 case _OP_BITW: _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
792 if(type((ci)->_generator) == OT_GENERATOR) {
793 _generator((ci)->_generator)->Kill();
795 if(Return(arg0, arg1, temp_reg)){
801 case _OP_LOADNULLS:{ for(unsigned int n=0;n<arg1;n++) STK(arg0+n) = _null_; }continue;
802 case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
803 case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
804 case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
805 case _OP_JMP: ci->_ip += (sarg1); continue;
806 case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
807 case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
808 case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
809 case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
811 if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); }
813 case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
814 case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
815 case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL); continue;
817 switch(type(STK(arg1))) {
819 TARGET = _table(STK(arg1))->_delegate?SQObjectPtr(_table(STK(arg1))->_delegate):_null_;
821 case OT_CLASS: TARGET = _class(STK(arg1))->_base?_class(STK(arg1))->_base:_null_;
826 Raise_Error(_SC("the %s type doesn't have a parent slot"), GetTypeName(STK(arg1)));
829 case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((unsigned int)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
830 case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
831 case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
832 case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
833 case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
834 case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
835 case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET)) continue;
836 case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
838 if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
839 {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
840 TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
843 if(IsFalse(STK(arg2))) {
849 if(!IsFalse(STK(arg2))) {
854 case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
855 case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
857 if(type(STK(arg1)) == OT_INTEGER) {
858 TARGET = SQInteger(~_integer(STK(arg1)));
861 Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
864 SQClosure *c = ci->_closure._unVal.pClosure;
865 SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
866 if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
870 if(type(ci->_generator) == OT_GENERATOR) {
871 if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
872 _GUARD(_generator(ci->_generator)->Yield(this));
873 traps -= ci->_etraps;
874 if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
876 else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
877 if(Return(arg0, arg1, temp_reg)){
886 if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
887 _GUARD(_generator(STK(arg1))->Resume(this, arg0));
888 traps += ci->_etraps;
890 case _OP_FOREACH:{ bool finished;
891 _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,finished));
892 if(finished) ci->_ip += sarg1; }
894 case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
896 if(!Clone(STK(arg1), TARGET))
897 { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
899 case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
901 _etraps.push_back(SQExceptionTrap(_top,_stackbase, &ci->_iv->_vals[(ci->_ip-ci->_iv->_vals)+arg1], arg0)); traps++;
905 for(int i=0; i<arg0; i++) {
906 _etraps.pop_back(); traps--;
910 case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
911 case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
913 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3)));
914 _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
915 if(arg0 != arg3) TARGET = STK(arg3);
923 SQObjectPtr currerror = _lasterror;
924 // dumpstack(_stackbase);
930 if(ci->_etraps > 0) {
931 SQExceptionTrap &et = _etraps.top();
933 _top = et._stacksize;
934 _stackbase = et._stackbase;
935 _stack[_stackbase+et._extarget] = currerror;
936 _etraps.pop_back(); traps--; ci->_etraps--;
937 while(last_top >= _top) _stack[last_top--].Null();
938 goto exception_restore;
940 //if is a native closure
941 if(type(ci->_closure) != OT_CLOSURE && n)
943 if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
944 PopVarArgs(ci->_vargs);
947 }while(_callsstack.size());
950 CallErrorHandler(currerror);
951 //remove call stack until a C function is found or the cstack is empty
953 bool exitafterthisone = ci->_root;
954 if(type(ci->_generator) == OT_GENERATOR) _generator(ci->_generator)->Kill();
955 _stackbase -= ci->_prevstkbase;
956 _top = _stackbase + ci->_prevtop;
957 PopVarArgs(ci->_vargs);
959 if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
960 }while(_callsstack.size());
962 while(last_top >= _top) _stack[last_top--].Null();
964 _lasterror = currerror;
970 bool SQVM::CreateClassInstance(SQClass *theclass, int nargs, int stackbase, SQObjectPtr &retval)
973 SQObjectPtr inst = theclass->CreateInstance();
974 _stack[stackbase] = inst;
975 if(theclass->Get(_ss(this)->_constructoridx,constr)) {
976 if(!Call(constr,nargs,stackbase,constr))
983 void SQVM::CallErrorHandler(SQObjectPtr &error)
985 if(type(_errorhandler) != OT_NULL) {
987 Push(_roottable); Push(error);
988 Call(_errorhandler, 2, _top-2, out);
993 void SQVM::CallDebugHook(int type,int forcedline)
995 SQObjectPtr temp_reg;
997 SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
998 Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
999 Call(_debughook,nparams,_top-nparams,temp_reg);
1003 bool SQVM::CallNative(SQNativeClosure *nclosure,int nargs,int stackbase,bool tailcall,SQObjectPtr &retval,bool &suspend)
1006 if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
1007 int nparamscheck = nclosure->_nparamscheck;
1008 if(((nparamscheck > 0) && (nparamscheck != nargs))
1009 || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
1010 Raise_Error(_SC("wrong number of parameters"));
1015 if( (tcs = nclosure->_typecheck.size()) ) {
1016 for(int i = 0; i < nargs && i < tcs; i++)
1017 if((nclosure->_typecheck[i] != -1) && !(type(_stack[stackbase+i]) & nclosure->_typecheck[i])) {
1018 Raise_ParamTypeError(i,nclosure->_typecheck[i],type(_stack[stackbase+i]));
1023 if ((_top + MIN_STACK_OVERHEAD) > (int)_stack.size()) {
1024 _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
1027 int oldstackbase = _stackbase;
1028 _top = stackbase + nargs;
1029 PUSH_CALLINFO(this, CallInfo());
1031 ci->_closure._unVal.pNativeClosure = nclosure;
1032 ci->_closure._type = OT_NATIVECLOSURE;
1033 ci->_prevstkbase = stackbase - _stackbase;
1035 _stackbase = stackbase;
1036 //push free variables
1037 int outers = nclosure->_outervalues.size();
1038 for (int i = 0; i < outers; i++) {
1039 Push(nclosure->_outervalues[i]);
1041 ci->_prevtop = (oldtop - oldstackbase);
1042 int ret = (nclosure->_function)(this);
1045 if( ret == SQ_SUSPEND_FLAG) suspend = true;
1047 _stackbase = oldstackbase;
1050 Raise_Error(_lasterror);
1054 if (ret != 0){ retval = TOP(); }
1055 else { retval = _null_; }
1056 _stackbase = oldstackbase;
1062 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
1066 if(_table(self)->Get(key,dest))return true;
1069 if(sq_isnumeric(key)){
1070 return _array(self)->Get(tointeger(key),dest);
1074 if(_instance(self)->Get(key,dest)) return true;
1079 if(FallBackGet(self,key,dest,raw)) return true;
1082 if(_rawval(STK(0)) == _rawval(self) &&
1083 type(STK(0)) == type(self)) {
1084 return _table(_roottable)->Get(key,dest);
1090 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
1094 return _class(self)->Get(key,dest);
1099 if(_delegable(self)->_delegate) {
1100 if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
1102 if(raw)return false;
1103 Push(self);Push(key);
1104 if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
1107 if(type(self) == OT_TABLE) {
1108 if(raw) return false;
1109 return _table_ddel->Get(key,dest);
1114 if(raw)return false;
1115 return _array_ddel->Get(key,dest);
1117 if(sq_isnumeric(key)){
1118 SQInteger n=tointeger(key);
1119 if(abs(n)<_string(self)->_len){
1120 if(n<0)n=_string(self)->_len-n;
1121 dest=SQInteger(_stringval(self)[n]);
1127 if(raw)return false;
1128 return _string_ddel->Get(key,dest);
1132 if(raw)return false;
1133 Push(self);Push(key);
1134 if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
1135 return _instance_ddel->Get(key,dest);
1138 case OT_INTEGER:case OT_FLOAT:case OT_BOOL:
1139 if(raw)return false;
1140 return _number_ddel->Get(key,dest);
1142 if(raw)return false;
1143 return _generator_ddel->Get(key,dest);
1144 case OT_CLOSURE: case OT_NATIVECLOSURE:
1145 if(raw)return false;
1146 return _closure_ddel->Get(key,dest);
1148 if(raw)return false;
1149 return _thread_ddel->Get(key,dest);
1150 default:return false;
1155 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
1159 if(_table(self)->Set(key,val))
1161 if(_table(self)->_delegate) {
1162 if(Set(_table(self)->_delegate,key,val,false)) {
1168 if(_delegable(self)->_delegate) {
1170 Push(self);Push(key);Push(val);
1171 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1175 if(_instance(self)->Set(key,val))
1178 Push(self);Push(key);Push(val);
1179 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1183 if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
1184 return _array(self)->Set(tointeger(key),val);
1186 Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
1190 if(_rawval(STK(0)) == _rawval(self) &&
1191 type(STK(0)) == type(self)) {
1192 return _table(_roottable)->Set(key,val);
1198 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
1200 SQObjectPtr temp_reg;
1203 target = _table(self)->Clone();
1206 target = _instance(self)->Clone(_ss(this));
1208 if(_delegable(target)->_delegate){
1211 CallMetaMethod(_delegable(target),MT_CLONED,2,temp_reg);
1215 target=_array(self)->Clone();
1217 default: return false;
1221 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val)
1223 if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
1224 switch(type(self)) {
1226 bool rawcall = true;
1227 if(_table(self)->_delegate) {
1229 if(!_table(self)->Get(key,res)) {
1230 Push(self);Push(key);Push(val);
1231 rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
1234 if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
1238 if(!_class(self)->NewSlot(key,val)) {
1239 if(_class(self)->_locked) {
1240 Raise_Error(_SC("trying to modify a class that has already been instantiated"));
1244 SQObjectPtr oval = PrintObjVal(key);
1245 Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
1251 Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
1258 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
1260 switch(type(self)) {
1265 bool handled = false;
1266 if(_delegable(self)->_delegate) {
1267 Push(self);Push(key);
1268 handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
1272 if(type(self) == OT_TABLE) {
1273 if(_table(self)->Get(key,t)) {
1274 _table(self)->Remove(key);
1277 Raise_IdxError((SQObject &)key);
1282 Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
1290 Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
1296 bool SQVM::Call(SQObjectPtr &closure,int nparams,int stackbase,SQObjectPtr &outres)
1299 int prevstackbase = _stackbase;
1301 switch(type(closure)) {
1303 return Execute(closure, _top - nparams, nparams, stackbase,outres);
1305 case OT_NATIVECLOSURE:{
1307 return CallNative(_nativeclosure(closure), nparams, stackbase, false, outres,suspend);
1312 return CreateClassInstance(_class(closure),nparams,stackbase,outres);
1319 assert(_stackbase == prevstackbase);
1325 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,int nparams,SQObjectPtr &outres)
1327 SQObjectPtr closure;
1328 if(del->GetMetaMethod(mm, closure)) {
1329 if(Call(closure, nparams, _top - nparams, outres)) {
1339 _stack[--_top] = _null_;
1341 void SQVM::Pop(int n) {
1342 for(int i = 0; i < n; i++){
1343 _stack[--_top] = _null_;
1347 void SQVM::Remove(int n) {
1348 n = (n >= 0)?n + _stackbase - 1:_top + n;
1349 for(int i = n; i < _top; i++){
1350 _stack[i] = _stack[i+1];
1352 _stack[_top] = _null_;
1356 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
1357 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
1358 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
1359 SQObjectPtr &SQVM::GetUp(int n) { return _stack[_top+n]; }
1360 SQObjectPtr &SQVM::GetAt(int n) { return _stack[n]; }
1363 void SQVM::dumpstack(int stackbase,bool dumpall)
1365 int size=dumpall?_stack.size():_top;
1367 scprintf(_SC("\n>>>>stack dump<<<<\n"));
1368 CallInfo &ci=_callsstack.back();
1369 scprintf(_SC("IP: %d\n"),ci._ip);
1370 scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
1371 scprintf(_SC("prev top: %d\n"),ci._prevtop);
1372 for(int i=0;i<size;i++){
1373 SQObjectPtr &obj=_stack[i];
1374 if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
1375 scprintf(_SC("[%d]:"),n);
1377 case OT_FLOAT: scprintf(_SC("FLOAT %.3f"),_float(obj));break;
1378 case OT_INTEGER: scprintf(_SC("INTEGER %d"),_integer(obj));break;
1379 case OT_BOOL: scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
1380 case OT_STRING: scprintf(_SC("STRING %s"),_stringval(obj));break;
1381 case OT_NULL: scprintf(_SC("NULL")); break;
1382 case OT_TABLE: scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
1383 case OT_ARRAY: scprintf(_SC("ARRAY %p"),_array(obj));break;
1384 case OT_CLOSURE: scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
1385 case OT_NATIVECLOSURE: scprintf(_SC("NATIVECLOSURE"));break;
1386 case OT_USERDATA: scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
1387 case OT_GENERATOR: scprintf(_SC("GENERATOR"));break;
1388 case OT_THREAD: scprintf(_SC("THREAD [%p]"),_thread(obj));break;
1389 case OT_USERPOINTER: scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
1390 case OT_CLASS: scprintf(_SC("CLASS %p"),_class(obj));break;
1391 case OT_INSTANCE: scprintf(_SC("INSTANCE %p"),_instance(obj));break;
1396 scprintf(_SC("\n"));