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._vals[_top-1])
19 bool SQVM::BW_OP(SQUnsignedInteger 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)(*((SQUnsignedInteger*)&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(SQUnsignedInteger 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)) {
44 SQInteger res, i1 = _integer(o1), i2 = _integer(o2);
46 case '+': res = i1 + i2; break;
47 case '-': res = i1 - i2; break;
48 case '/': if(i2 == 0) { Raise_Error(_SC("division by zero")); return false; }
51 case '*': res = i1 * i2; break;
52 case '%': res = i1 % i2; break;
53 default: res = 0xDEADBEEF;
57 SQFloat res, f1 = tofloat(o1), f2 = tofloat(o2);
59 case '+': res = f1 + f2; break;
60 case '-': res = f1 - f2; break;
61 case '/': res = f1 / f2; break;
62 case '*': res = f1 * f2; break;
63 case '%': res = SQFloat(fmod((double)f1,(double)f2)); break;
69 if(op == '+' && (type(o1) == OT_STRING || type(o2) == OT_STRING)){
70 if(!StringCat(o1, o2, trg)) return false;
72 else if(!ArithMetaMethod(op,o1,o2,trg)) {
73 Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2)); return false;
79 SQVM::SQVM(SQSharedState *ss)
84 _suspended_root = SQFalse;
89 _errorhandler = _null_;
92 INIT_CHAIN();ADD_TO_CHAIN(&_ss(this)->_gc_chain,this);
99 _errorhandler = _null_;
102 _callstackdata.resize(0);
103 SQInteger size=_stack.size();
104 for(SQInteger i=0;i<size;i++)
111 //sq_free(_callsstack,_alloccallsstacksize*sizeof(CallInfo));
112 REMOVE_FROM_CHAIN(&_ss(this)->_gc_chain,this);
115 bool SQVM::ArithMetaMethod(SQInteger op,const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &dest)
119 case _SC('+'): mm=MT_ADD; break;
120 case _SC('-'): mm=MT_SUB; break;
121 case _SC('/'): mm=MT_DIV; break;
122 case _SC('*'): mm=MT_MUL; break;
123 case _SC('%'): mm=MT_MODULO; break;
124 default: mm = MT_ADD; assert(0); break; //shutup compiler
126 if(is_delegable(o1) && _delegable(o1)->_delegate) {
128 return CallMetaMethod(_delegable(o1),mm,2,dest);
133 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
146 if(_delegable(o)->_delegate) {
148 if(CallMetaMethod(_delegable(o), MT_UNM, 1, temp_reg)) {
153 default:break; //shutup compiler
155 Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
159 #define _RET_SUCCEED(exp) { result = (exp); return true; }
160 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,SQInteger &result)
162 if(type(o1)==type(o2)){
163 if(_userpointer(o1)==_userpointer(o2))_RET_SUCCEED(0);
167 _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
169 _RET_SUCCEED(_integer(o1)-_integer(o2));
171 _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
175 if(_delegable(o1)->_delegate) {
177 if(CallMetaMethod(_delegable(o1),MT_CMP,2,res)) break;
179 //continues through (no break needed)
181 _RET_SUCCEED( _userpointer(o1) < _userpointer(o2)?-1:1 );
183 if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
184 _RET_SUCCEED(_integer(res));
188 if(sq_isnumeric(o1) && sq_isnumeric(o2)){
189 if((type(o1)==OT_INTEGER) && (type(o2)==OT_FLOAT)) {
190 if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
191 else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
195 if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
196 else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
200 else if(type(o1)==OT_NULL) {_RET_SUCCEED(-1);}
201 else if(type(o2)==OT_NULL) {_RET_SUCCEED(1);}
202 else { Raise_CompareError(o1,o2); return false; }
206 _RET_SUCCEED(0); //cannot happen
209 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
212 if(ObjCmp(o1,o2,r)) {
214 case CMP_G: res = (r > 0)?_true_:_false_; return true;
215 case CMP_GE: res = (r >= 0)?_true_:_false_; return true;
216 case CMP_L: res = (r < 0)?_true_:_false_; return true;
217 case CMP_LE: res = (r <= 0)?_true_:_false_; return true;
225 void SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res)
232 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+1)),_SC("%g"),_float(o));
235 scsprintf(_sp(rsl(NUMBER_MAX_CHAR+1)),_SC("%d"),_integer(o));
238 scsprintf(_sp(rsl(6)),_integer(o)?_SC("true"):_SC("false"));
243 if(_delegable(o)->_delegate) {
245 if(CallMetaMethod(_delegable(o),MT_TOSTRING,1,res)) {
246 if(type(res) == OT_STRING)
248 //else keeps going to the default
252 scsprintf(_sp(rsl(sizeof(void*)+20)),_SC("(%s : 0x%p)"),GetTypeName(o),(void*)_rawval(o));
254 res = SQString::Create(_ss(this),_spval);
258 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
263 SQInteger l = _string(a)->_len , ol = _string(b)->_len;
264 SQChar *s = _sp(rsl(l + ol + 1));
265 memcpy(s, _stringval(a), rsl(l));
266 memcpy(s + l, _stringval(b), rsl(ol));
267 dest = SQString::Create(_ss(this), _spval, l + ol);
271 void SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
273 if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
275 if(CallMetaMethod(_delegable(obj1),MT_TYPEOF,1,dest))
278 dest = SQString::Create(_ss(this),GetTypeName(obj1));
281 bool SQVM::Init(SQVM *friendvm, SQInteger stacksize)
283 _stack.resize(stacksize);
284 //_callsstack.reserve(4);
285 _alloccallsstacksize = 4;
286 _callstackdata.resize(_alloccallsstacksize);
288 _callsstack = &_callstackdata[0];
289 //_callsstack = (CallInfo*)sq_malloc(_alloccallsstacksize*sizeof(CallInfo));
293 _roottable = SQTable::Create(_ss(this), 0);
295 _roottable = friendvm->_roottable;
296 _errorhandler = friendvm->_errorhandler;
297 _debughook = friendvm->_debughook;
300 sq_base_register(this);
304 extern SQInstructionDesc g_InstrDesc[];
306 bool SQVM::StartCall(SQClosure *closure,SQInteger target,SQInteger args,SQInteger stackbase,bool tailcall)
308 SQFunctionProto *func = _funcproto(closure->_function);
310 const SQInteger paramssize = func->_nparameters;
311 const SQInteger newtop = stackbase + func->_stacksize;
312 SQInteger nargs = args;
313 if (paramssize != nargs) {
314 SQInteger ndef = func->_ndefaultparams;
315 if(ndef && nargs < paramssize) {
316 SQInteger diff = paramssize - nargs;
317 for(SQInteger n = ndef - diff; n < ndef; n++) {
318 _stack._vals[stackbase + (nargs++)] = closure->_defaultparams[n];
321 else if(func->_varparams)
323 if (nargs < paramssize) {
324 Raise_Error(_SC("wrong number of parameters"));
327 for(SQInteger n = 0; n < nargs - paramssize; n++) {
328 _vargsstack.push_back(_stack._vals[stackbase+paramssize+n]);
329 _stack._vals[stackbase+paramssize+n] = _null_;
333 Raise_Error(_SC("wrong number of parameters"));
338 if(type(closure->_env) == OT_WEAKREF) {
339 _stack._vals[stackbase] = _weakref(closure->_env)->_obj;
344 lc._generator = NULL;
346 lc._prevstkbase = (SQInt32) ( stackbase - _stackbase );
347 lc._target = (SQInt32) target;
348 lc._prevtop = (SQInt32) (_top - _stackbase);
351 PUSH_CALLINFO(this, lc);
356 ci->_vargs.size = (SQInt32)(nargs - paramssize);
357 ci->_vargs.base = (SQInt32)(_vargsstack.size()-(ci->_vargs.size));
358 ci->_closure = closure;
359 ci->_literals = func->_literals;
360 ci->_ip = func->_instructions;
361 //grows the stack if needed
362 if (((SQUnsignedInteger)newtop + (func->_stacksize<<1)) > _stack.size()) {
363 _stack.resize(_stack.size() + (func->_stacksize<<1));
367 _stackbase = stackbase;
368 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
369 CallDebugHook(_SC('c'));
373 bool SQVM::Return(SQInteger _arg0, SQInteger _arg1, SQObjectPtr &retval)
375 if (type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
376 for(SQInteger i=0;i<ci->_ncalls;i++)
377 CallDebugHook(_SC('r'));
379 SQBool broot = ci->_root;
380 SQInteger last_top = _top;
381 SQInteger target = ci->_target;
382 SQInteger oldstackbase = _stackbase;
383 _stackbase -= ci->_prevstkbase;
384 _top = _stackbase + ci->_prevtop;
385 if(ci->_vargs.size) PopVarArgs(ci->_vargs);
388 if (_arg0 != MAX_FUNC_STACKSIZE) retval = _stack._vals[oldstackbase+_arg1];
389 else retval = _null_;
392 if(target != -1) { //-1 is when a class contructor ret value has to be ignored
393 if (_arg0 != MAX_FUNC_STACKSIZE)
394 STK(target) = _stack._vals[oldstackbase+_arg1];
396 STK(target) = _null_;
400 while (last_top >= _top) _stack._vals[last_top--].Null();
401 assert(oldstackbase >= _stackbase);
402 return broot?true:false;
405 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
407 bool SQVM::LOCAL_INC(SQInteger op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
409 _RET_ON_FAIL(ARITH_OP( op , target, a, incr));
414 bool SQVM::PLOCAL_INC(SQInteger op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
417 _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
423 bool SQVM::DerefInc(SQInteger op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix)
425 SQObjectPtr tmp, tself = self, tkey = key;
426 if (!Get(tself, tkey, tmp, false, true)) { Raise_IdxError(tkey); return false; }
427 _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
428 Set(tself, tkey, target,true);
429 if (postfix) target = tmp;
433 #define arg0 (_i_._arg0)
434 #define arg1 (_i_._arg1)
435 #define sarg1 (*((SQInt32 *)&_i_._arg1))
436 #define arg2 (_i_._arg2)
437 #define arg3 (_i_._arg3)
438 #define sarg3 ((SQInteger)*((signed char *)&_i_._arg3))
440 SQRESULT SQVM::Suspend()
443 return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
444 if (_nnativecalls!=2)
445 return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
446 return SQ_SUSPEND_FLAG;
449 void SQVM::PopVarArgs(VarArgs &vargs)
451 for(SQInteger n = 0; n< vargs.size; n++)
452 _vargsstack.pop_back();
455 #define _FINISH(howmuchtojump) {jump = howmuchtojump; return true; }
456 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
457 &o3,SQObjectPtr &o4,SQInteger arg_2,int exitpos,int &jump)
462 if((nrefidx = _table(o1)->Next(false,o4, o2, o3)) == -1) _FINISH(exitpos);
463 o4 = (SQInteger)nrefidx; _FINISH(1);
465 if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(exitpos);
466 o4 = (SQInteger) nrefidx; _FINISH(1);
468 if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
469 o4 = (SQInteger)nrefidx; _FINISH(1);
471 if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
472 o4 = (SQInteger)nrefidx; _FINISH(1);
475 if(_delegable(o1)->_delegate) {
479 if(CallMetaMethod(_delegable(o1), MT_NEXTI, 2, itr)){
481 if(type(itr) == OT_NULL) _FINISH(exitpos);
482 if(!Get(o1, itr, o3, false,false)) {
483 Raise_Error(_SC("_nexti returned an invalid idx"));
488 Raise_Error(_SC("_nexti failed"));
493 if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(exitpos);
494 if(_generator(o1)->_state == SQGenerator::eSuspended) {
496 if(type(o4) == OT_INTEGER) {
497 idx = _integer(o4) + 1;
501 _generator(o1)->Resume(this, arg_2+1);
505 Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
507 return false; //cannot be hit(just to avoid warnings)
510 bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2)
512 if(type(o1) != OT_TABLE) { Raise_Error(_SC("delegating a '%s'"), GetTypeName(o1)); return false; }
515 if(!_table(o1)->SetDelegate(_table(o2))){
516 Raise_Error(_SC("delegate cycle detected"));
521 _table(o1)->SetDelegate(NULL);
524 Raise_Error(_SC("using '%s' as delegate"), GetTypeName(o2));
531 #define COND_LITERAL (arg3!=0?ci->_literals[arg1]:STK(arg1))
533 #define _GUARD(exp) { if(!exp) { Raise_Error(_lasterror); SQ_THROW();} }
535 #define SQ_THROW() { goto exception_trap; }
537 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
540 SQClosure *closure = SQClosure::Create(_ss(this), func);
541 if((nouters = func->_noutervalues)) {
542 closure->_outervalues.reserve(nouters);
543 for(SQInteger i = 0; i<nouters; i++) {
544 SQOuterVar &v = func->_outervalues[i];
547 closure->_outervalues.push_back(_null_);
548 if(!Get(_stack._vals[_stackbase]/*STK(0)*/, v._src, closure->_outervalues.top(), false,true))
549 {Raise_IdxError(v._src); return false; }
552 closure->_outervalues.push_back(_stack._vals[_stackbase+_integer(v._src)]);
555 closure->_outervalues.push_back(_closure(ci->_closure)->_outervalues[_integer(v._src)]);
560 SQInteger ndefparams;
561 if((ndefparams = func->_ndefaultparams)) {
562 closure->_defaultparams.reserve(ndefparams);
563 for(SQInteger i = 0; i < ndefparams; i++) {
564 SQInteger spos = func->_defaultparams[i];
565 closure->_defaultparams.push_back(_stack._vals[_stackbase + spos]);
573 bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci)
575 if(ci->_vargs.size == 0) {
576 Raise_Error(_SC("the function doesn't have var args"));
579 if(!sq_isnumeric(index)){
580 Raise_Error(_SC("indexing 'vargv' with %s"),GetTypeName(index));
583 SQInteger idx = tointeger(index);
584 if(idx < 0 || idx >= ci->_vargs.size){ Raise_Error(_SC("vargv index out of range")); return false; }
585 target = _vargsstack[ci->_vargs.base+idx];
589 bool SQVM::CLASS_OP(SQObjectPtr &target,SQInteger baseclass,SQInteger attributes)
591 SQClass *base = NULL;
593 if(baseclass != -1) {
594 if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
595 base = _class(_stack._vals[_stackbase + baseclass]);
597 if(attributes != MAX_FUNC_STACKSIZE) {
598 attrs = _stack._vals[_stackbase+attributes];
600 target = SQClass::Create(_ss(this),base);
601 if(type(_class(target)->_metamethods[MT_INHERITED]) != OT_NULL) {
604 Push(target); Push(attrs);
605 Call(_class(target)->_metamethods[MT_INHERITED],nparams,_top - nparams, ret, false);
608 _class(target)->_attributes = attrs;
614 bool SQVM::IsEqual(SQObjectPtr &o1,SQObjectPtr &o2,bool &res)
616 if(type(o1) == type(o2)) {
617 res = ((_userpointer(o1) == _userpointer(o2)?true:false));
620 if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
622 if(!ObjCmp(o1, o2,cmpres)) return false;
632 bool SQVM::IsFalse(SQObjectPtr &o)
634 if((type(o) & SQOBJECT_CANBEFALSE) && ( (type(o) == OT_FLOAT) && (_float(o) == SQFloat(0.0)) )
635 || (_integer(o) == 0) ) { //OT_NULL|OT_INTEGER|OT_BOOL
641 bool SQVM::GETPARENT_OP(SQObjectPtr &o,SQObjectPtr &target)
644 case OT_TABLE: target = _table(o)->_delegate?SQObjectPtr(_table(o)->_delegate):_null_;
646 case OT_CLASS: target = _class(o)->_base?_class(o)->_base:_null_;
649 Raise_Error(_SC("the %s type doesn't have a parent slot"), GetTypeName(o));
655 bool SQVM::Execute(SQObjectPtr &closure, SQInteger target, SQInteger nargs, SQInteger stackbase,SQObjectPtr &outres, SQBool raiseerror,ExecutionType et)
657 if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
659 AutoDec ad(&_nnativecalls);
661 //temp_reg vars for OP_CALL
663 SQInteger ct_stackbase;
668 if(!StartCall(_closure(closure), _top - nargs, nargs, stackbase, false)) {
669 //call the handler if there are no calls in the stack, if not relies on the previous node
670 if(ci == NULL) CallErrorHandler(_lasterror);
675 case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, target); ci->_root = SQTrue; traps += ci->_etraps; break;
677 traps = _suspended_traps;
678 ci->_root = _suspended_root;
679 ci->_vargs = _suspend_varargs;
680 _suspended = SQFalse;
689 const SQInstruction &_i_ = *ci->_ip++;
690 //dumpstack(_stackbase);
691 //scprintf("\n[%d] %s %d %d %d %d\n",ci->_ip-ci->_iv->_vals,g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
695 if(type(_debughook) != OT_NULL && _rawval(_debughook) != _rawval(ci->_closure))
696 CallDebugHook(_SC('l'),arg1);
698 case _OP_LOAD: TARGET = ci->_literals[arg1]; continue;
699 case _OP_LOADINT: TARGET = (SQInteger)arg1; continue;
700 case _OP_LOADFLOAT: TARGET = *((SQFloat *)&arg1); continue;
701 case _OP_DLOAD: TARGET = ci->_literals[arg1]; STK(arg2) = ci->_literals[arg3];continue;
703 temp_reg = STK(arg1);
704 if (type(temp_reg) == OT_CLOSURE){
706 if(ci->_vargs.size) PopVarArgs(ci->_vargs);
707 for (SQInteger i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
708 ct_target = ci->_target;
709 ct_stackbase = _stackbase;
715 temp_reg = STK(arg1);
716 ct_stackbase = _stackbase+arg2;
719 SQObjectPtr clo = temp_reg;
720 SQInteger last_top = _top;
723 _GUARD(StartCall(_closure(clo), ct_target, arg3, ct_stackbase, ct_tailcall));
724 if (_funcproto(_closure(clo)->_function)->_bgenerator) {
725 SQGenerator *gen = SQGenerator::Create(_ss(this), _closure(clo));
726 _GUARD(gen->Yield(this));
727 Return(1, ct_target, clo);
728 STK(ct_target) = gen;
729 while (last_top >= _top) _stack._vals[last_top--].Null();
734 case OT_NATIVECLOSURE: {
736 _GUARD(CallNative(_nativeclosure(clo), arg3, ct_stackbase, clo,suspend));
739 _suspended_target = ct_target;
740 _suspended_root = ci->_root;
741 _suspended_traps = traps;
742 _suspend_varargs = ci->_vargs;
746 if(ct_target != -1) { //skip return value for constructors
747 STK(ct_target) = clo;
753 _GUARD(CreateClassInstance(_class(clo),inst,temp_reg));
754 STK(ct_target) = inst;
755 ct_target = -1; //fakes return value target so that is not overwritten by the constructor
756 if(type(temp_reg) != OT_NULL) {
757 _stack._vals[ct_stackbase] = inst;
758 goto common_call; //hard core spaghetti code(reissues the OP_CALL to invoke the constructor)
767 for (SQInteger i = 0; i < arg3; i++) Push(STK(arg2 + i));
768 if (_delegable(clo) && CallMetaMethod(_delegable(clo), MT_CALL, arg3+1, clo)){
769 STK(ct_target) = clo;
772 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
776 Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
784 SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1);
785 SQObjectPtr &o = STK(arg2);
786 if (!Get(o, key, temp_reg,false,true)) {
787 if(type(o) == OT_CLASS) { //hack?
788 if(_class_ddel->Get(key,temp_reg)) {
794 { Raise_IdxError(key); SQ_THROW();}
797 STK(arg3) = type(o) == OT_CLASS?STK(0):o;
802 if (!Get(STK(arg2), ci->_literals[arg1], temp_reg, false,true)) { Raise_IdxError(ci->_literals[arg1]); SQ_THROW();}
805 case _OP_MOVE: TARGET = STK(arg1); continue;
807 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),false));
808 if(arg0 != arg3) TARGET = STK(arg3);
810 case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
812 if (!Set(STK(arg1), STK(arg2), STK(arg3),true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
813 if (arg0 != arg3) TARGET = STK(arg3);
816 if (!Get(STK(arg1), STK(arg2), temp_reg, false,true)) { Raise_IdxError(STK(arg2)); SQ_THROW(); }
821 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
822 TARGET = res?_true_:_false_;
826 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
827 TARGET = (!res)?_true_:_false_;
829 case _OP_ARITH: _GUARD(ARITH_OP( arg3 , temp_reg, STK(arg2), STK(arg1))); TARGET = temp_reg; continue;
830 case _OP_BITW: _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
833 ci->_generator->Kill();
835 if(Return(arg0, arg1, temp_reg)){
841 case _OP_LOADNULLS:{ for(SQInt32 n=0; n < arg1; n++) STK(arg0+n) = _null_; }continue;
842 case _OP_LOADROOTTABLE: TARGET = _roottable; continue;
843 case _OP_LOADBOOL: TARGET = arg1?_true_:_false_; continue;
844 case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
845 case _OP_JMP: ci->_ip += (sarg1); continue;
846 case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
847 case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
848 case _OP_LOADFREEVAR: TARGET = _closure(ci->_closure)->_outervalues[arg1]; continue;
849 case _OP_VARGC: TARGET = SQInteger(ci->_vargs.size); continue;
851 if(!GETVARGV_OP(TARGET,STK(arg1),ci)) { SQ_THROW(); }
853 case _OP_NEWTABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
854 case _OP_NEWARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
855 case _OP_APPENDARRAY: _array(STK(arg0))->Append(COND_LITERAL); continue;
856 case _OP_GETPARENT: _GUARD(GETPARENT_OP(STK(arg1),TARGET)); continue;
857 case _OP_COMPARITH: _GUARD(DerefInc(arg3, TARGET, STK((((SQUnsignedInteger)arg1&0xFFFF0000)>>16)), STK(arg2), STK(arg1&0x0000FFFF), false)); continue;
858 case _OP_COMPARITHL: _GUARD(LOCAL_INC(arg3, TARGET, STK(arg1), STK(arg2))); continue;
859 case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false));} continue;
860 case _OP_INCL: {SQObjectPtr o(sarg3); _GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));} continue;
861 case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true));} continue;
862 case _OP_PINCL: {SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));} continue;
863 case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET)) continue;
864 case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue;
866 if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE)
867 {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
868 TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_;
871 if(IsFalse(STK(arg2))) {
877 if(!IsFalse(STK(arg2))) {
882 case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
883 case _OP_NOT: TARGET = (IsFalse(STK(arg1))?_true_:_false_); continue;
885 if(type(STK(arg1)) == OT_INTEGER) {
886 SQInteger t = _integer(STK(arg1));
887 TARGET = SQInteger(~t);
890 Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
893 SQClosure *c = ci->_closure._unVal.pClosure;
894 SQFunctionProto *fp = c->_function._unVal.pFunctionProto;
895 if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
900 if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
901 _GUARD(ci->_generator->Yield(this));
902 traps -= ci->_etraps;
903 if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg;
905 else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
906 if(Return(arg0, arg1, temp_reg)){
915 if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
916 _GUARD(_generator(STK(arg1))->Resume(this, arg0));
917 traps += ci->_etraps;
919 case _OP_FOREACH:{ int tojump;
920 _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,sarg1,tojump));
923 case _OP_POSTFOREACH:
924 assert(type(STK(arg0)) == OT_GENERATOR);
925 if(_generator(STK(arg0))->_state == SQGenerator::eDead)
926 ci->_ip += (sarg1 - 1);
928 case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue;
930 if(!Clone(STK(arg1), TARGET))
931 { Raise_Error(_SC("cloning a %s"), GetTypeName(STK(arg1))); SQ_THROW();}
933 case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue;
935 SQInstruction *_iv = _funcproto(_closure(ci->_closure)->_function)->_instructions;
936 _etraps.push_back(SQExceptionTrap(_top,_stackbase, &_iv[(ci->_ip-_iv)+arg1], arg0)); traps++;
941 for(SQInteger i = 0; i < arg0; i++) {
942 _etraps.pop_back(); traps--;
947 case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
948 case _OP_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
950 bool bstatic = (arg0&NEW_SLOT_STATIC_FLAG)?true:false;
951 if(type(STK(arg1)) == OT_CLASS) {
952 if(type(_class(STK(arg1))->_metamethods[MT_NEWMEMBER]) != OT_NULL ) {
953 Push(STK(arg1)); Push(STK(arg2)); Push(STK(arg3));
954 Push((arg0&NEW_SLOT_ATTRIBUTES_FLAG) ? STK(arg2-1) : _null_);
956 if(Call(_class(STK(arg1))->_metamethods[MT_NEWMEMBER], nparams, _top - nparams, temp_reg,SQFalse)) {
962 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),bstatic));
963 if((arg0&NEW_SLOT_ATTRIBUTES_FLAG)) {
964 _class(STK(arg1))->SetAttributes(STK(arg2),STK(arg2-1));
973 SQObjectPtr currerror = _lasterror;
974 // dumpstack(_stackbase);
976 SQInteger last_top = _top;
978 if(_ss(this)->_notifyallexceptions) CallErrorHandler(currerror);
982 if(ci->_etraps > 0) {
983 SQExceptionTrap &et = _etraps.top();
985 _top = et._stacksize;
986 _stackbase = et._stackbase;
987 _stack._vals[_stackbase+et._extarget] = currerror;
988 _etraps.pop_back(); traps--; ci->_etraps--;
989 while(last_top >= _top) _stack._vals[last_top--].Null();
990 goto exception_restore;
992 //if is a native closure
993 if(type(ci->_closure) != OT_CLOSURE && n)
995 if(ci->_generator) ci->_generator->Kill();
996 PopVarArgs(ci->_vargs);
999 } while(_callsstacksize);
1003 if(raiseerror && !_ss(this)->_notifyallexceptions)
1004 CallErrorHandler(currerror);
1006 //remove call stack until a C function is found or the cstack is empty
1008 SQBool exitafterthisone = ci->_root;
1009 if(ci->_generator) ci->_generator->Kill();
1010 _stackbase -= ci->_prevstkbase;
1011 _top = _stackbase + ci->_prevtop;
1012 PopVarArgs(ci->_vargs);
1014 if( (ci && type(ci->_closure) != OT_CLOSURE) || exitafterthisone) break;
1015 } while(_callsstacksize);
1017 while(last_top >= _top) _stack._vals[last_top--].Null();
1019 _lasterror = currerror;
1025 bool SQVM::CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor)
1027 inst = theclass->CreateInstance();
1028 if(!theclass->Get(_ss(this)->_constructoridx,constructor)) {
1029 //if(!Call(constr,nargs,stackbase,constr,false))
1031 constructor = _null_;
1036 void SQVM::CallErrorHandler(SQObjectPtr &error)
1038 if(type(_errorhandler) != OT_NULL) {
1040 Push(_roottable); Push(error);
1041 Call(_errorhandler, 2, _top-2, out,SQFalse);
1046 void SQVM::CallDebugHook(SQInteger type,SQInteger forcedline)
1048 SQObjectPtr temp_reg;
1049 SQInteger nparams=5;
1050 SQFunctionProto *func=_funcproto(_closure(ci->_closure)->_function);
1051 Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
1052 Call(_debughook,nparams,_top-nparams,temp_reg,SQFalse);
1056 bool SQVM::CallNative(SQNativeClosure *nclosure,SQInteger nargs,SQInteger stackbase,SQObjectPtr &retval,bool &suspend)
1058 if (_nnativecalls + 1 > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
1059 SQInteger nparamscheck = nclosure->_nparamscheck;
1060 if(((nparamscheck > 0) && (nparamscheck != nargs))
1061 || ((nparamscheck < 0) && (nargs < (-nparamscheck)))) {
1062 Raise_Error(_SC("wrong number of parameters"));
1067 if((tcs = nclosure->_typecheck.size())) {
1068 for(SQInteger i = 0; i < nargs && i < tcs; i++)
1069 if((nclosure->_typecheck._vals[i] != -1) && !(type(_stack._vals[stackbase+i]) & nclosure->_typecheck[i])) {
1070 Raise_ParamTypeError(i,nclosure->_typecheck._vals[i],type(_stack._vals[stackbase+i]));
1075 if ((_top + MIN_STACK_OVERHEAD) > (SQInteger)_stack.size()) {
1076 _stack.resize(_stack.size() + (MIN_STACK_OVERHEAD<<1));
1078 SQInteger oldtop = _top;
1079 SQInteger oldstackbase = _stackbase;
1080 _top = stackbase + nargs;
1082 lci._closure = nclosure;
1083 lci._generator = NULL;
1085 lci._prevstkbase = (SQInt32) (stackbase - _stackbase);
1087 lci._prevtop = (SQInt32) (oldtop - oldstackbase);
1088 PUSH_CALLINFO(this, lci);
1089 _stackbase = stackbase;
1090 //push free variables
1091 SQInteger outers = nclosure->_outervalues.size();
1092 for (SQInteger i = 0; i < outers; i++) {
1093 Push(nclosure->_outervalues[i]);
1096 if(type(nclosure->_env) == OT_WEAKREF) {
1097 _stack[stackbase] = _weakref(nclosure->_env)->_obj;
1101 SQInteger ret = (nclosure->_function)(this);
1104 if( ret == SQ_SUSPEND_FLAG) suspend = true;
1106 _stackbase = oldstackbase;
1109 Raise_Error(_lasterror);
1113 if (ret != 0){ retval = TOP(); TOP().Null(); }
1114 else { retval = _null_; }
1115 _stackbase = oldstackbase;
1121 bool SQVM::Get(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw, bool fetchroot)
1125 if(_table(self)->Get(key,dest))return true;
1128 if(sq_isnumeric(key)){
1129 return _array(self)->Get(tointeger(key),dest);
1133 if(_instance(self)->Get(key,dest)) return true;
1135 default:break; //shut up compiler
1137 if(FallBackGet(self,key,dest,raw)) return true;
1140 if(_rawval(STK(0)) == _rawval(self) &&
1141 type(STK(0)) == type(self)) {
1142 return _table(_roottable)->Get(key,dest);
1148 bool SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest,bool raw)
1152 return _class(self)->Get(key,dest);
1157 if(_delegable(self)->_delegate) {
1158 if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,raw,false))
1160 if(raw)return false;
1161 Push(self);Push(key);
1162 if(CallMetaMethod(_delegable(self),MT_GET,2,dest))
1165 if(type(self) == OT_TABLE) {
1166 if(raw) return false;
1167 return _table_ddel->Get(key,dest);
1172 if(raw)return false;
1173 return _array_ddel->Get(key,dest);
1175 if(sq_isnumeric(key)){
1176 SQInteger n=tointeger(key);
1177 if(abs((int)n)<_string(self)->_len){
1178 if(n<0)n=_string(self)->_len-n;
1179 dest=SQInteger(_stringval(self)[n]);
1185 if(raw)return false;
1186 return _string_ddel->Get(key,dest);
1190 if(raw)return false;
1191 Push(self);Push(key);
1192 if(!CallMetaMethod(_delegable(self),MT_GET,2,dest)) {
1193 return _instance_ddel->Get(key,dest);
1196 case OT_INTEGER:case OT_FLOAT:case OT_BOOL:
1197 if(raw)return false;
1198 return _number_ddel->Get(key,dest);
1200 if(raw)return false;
1201 return _generator_ddel->Get(key,dest);
1202 case OT_CLOSURE: case OT_NATIVECLOSURE:
1203 if(raw)return false;
1204 return _closure_ddel->Get(key,dest);
1206 if(raw)return false;
1207 return _thread_ddel->Get(key,dest);
1209 if(raw)return false;
1210 return _weakref_ddel->Get(key,dest);
1211 default:return false;
1216 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool fetchroot)
1220 if(_table(self)->Set(key,val))
1222 if(_table(self)->_delegate) {
1223 if(Set(_table(self)->_delegate,key,val,false)) {
1229 if(_delegable(self)->_delegate) {
1231 Push(self);Push(key);Push(val);
1232 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1236 if(_instance(self)->Set(key,val))
1239 Push(self);Push(key);Push(val);
1240 if(CallMetaMethod(_delegable(self),MT_SET,3,t)) return true;
1244 if(!sq_isnumeric(key)) {Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
1245 return _array(self)->Set(tointeger(key),val);
1247 Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
1251 if(_rawval(STK(0)) == _rawval(self) &&
1252 type(STK(0)) == type(self)) {
1253 return _table(_roottable)->Set(key,val);
1259 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
1261 SQObjectPtr temp_reg;
1265 newobj = _table(self)->Clone();
1268 newobj = _instance(self)->Clone(_ss(this));
1270 if(_delegable(newobj)->_delegate){
1273 CallMetaMethod(_delegable(newobj),MT_CLONED,2,temp_reg);
1278 target = _array(self)->Clone();
1280 default: return false;
1284 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
1286 if(type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
1287 switch(type(self)) {
1289 bool rawcall = true;
1290 if(_table(self)->_delegate) {
1292 if(!_table(self)->Get(key,res)) {
1293 Push(self);Push(key);Push(val);
1294 rawcall = !CallMetaMethod(_table(self),MT_NEWSLOT,3,res);
1297 if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
1302 Push(self);Push(key);Push(val);
1303 if(!CallMetaMethod(_instance(self),MT_NEWSLOT,3,res)) {
1304 Raise_Error(_SC("class instances do not support the new slot operator"));
1309 if(!_class(self)->NewSlot(_ss(this),key,val,bstatic)) {
1310 if(_class(self)->_locked) {
1311 Raise_Error(_SC("trying to modify a class that has already been instantiated"));
1315 SQObjectPtr oval = PrintObjVal(key);
1316 Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
1322 Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
1329 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
1331 switch(type(self)) {
1336 bool handled = false;
1337 if(_delegable(self)->_delegate) {
1338 Push(self);Push(key);
1339 handled = CallMetaMethod(_delegable(self),MT_DELSLOT,2,t);
1343 if(type(self) == OT_TABLE) {
1344 if(_table(self)->Get(key,t)) {
1345 _table(self)->Remove(key);
1348 Raise_IdxError((SQObject &)key);
1353 Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
1361 Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
1367 bool SQVM::Call(SQObjectPtr &closure,SQInteger nparams,SQInteger stackbase,SQObjectPtr &outres,SQBool raiseerror)
1370 SQInteger prevstackbase = _stackbase;
1372 switch(type(closure)) {
1374 return Execute(closure, _top - nparams, nparams, stackbase,outres,raiseerror);
1376 case OT_NATIVECLOSURE:{
1378 return CallNative(_nativeclosure(closure), nparams, stackbase, outres,suspend);
1385 CreateClassInstance(_class(closure),outres,constr);
1386 if(type(constr) != OT_NULL) {
1387 _stack[stackbase] = outres;
1388 return Call(constr,nparams,stackbase,temp,raiseerror);
1398 assert(_stackbase == prevstackbase);
1404 bool SQVM::CallMetaMethod(SQDelegable *del,SQMetaMethod mm,SQInteger nparams,SQObjectPtr &outres)
1406 SQObjectPtr closure;
1407 if(del->GetMetaMethod(this, mm, closure)) {
1408 if(Call(closure, nparams, _top - nparams, outres, SQFalse)) {
1417 void SQVM::Remove(SQInteger n) {
1418 n = (n >= 0)?n + _stackbase - 1:_top + n;
1419 for(SQInteger i = n; i < _top; i++){
1420 _stack[i] = _stack[i+1];
1422 _stack[_top] = _null_;
1427 _stack[--_top] = _null_;
1430 void SQVM::Pop(SQInteger n) {
1431 for(SQInteger i = 0; i < n; i++){
1432 _stack[--_top] = _null_;
1436 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
1437 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
1438 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
1439 SQObjectPtr &SQVM::GetUp(SQInteger n) { return _stack[_top+n]; }
1440 SQObjectPtr &SQVM::GetAt(SQInteger n) { return _stack[n]; }
1443 void SQVM::dumpstack(SQInteger stackbase,bool dumpall)
1445 SQInteger size=dumpall?_stack.size():_top;
1447 scprintf(_SC("\n>>>>stack dump<<<<\n"));
1448 CallInfo &ci=_callsstack[_callsstacksize-1];
1449 scprintf(_SC("IP: %p\n"),ci._ip);
1450 scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
1451 scprintf(_SC("prev top: %d\n"),ci._prevtop);
1452 for(SQInteger i=0;i<size;i++){
1453 SQObjectPtr &obj=_stack[i];
1454 if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
1455 scprintf(_SC("[%d]:"),n);
1457 case OT_FLOAT: scprintf(_SC("FLOAT %.3f"),_float(obj));break;
1458 case OT_INTEGER: scprintf(_SC("INTEGER %d"),_integer(obj));break;
1459 case OT_BOOL: scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
1460 case OT_STRING: scprintf(_SC("STRING %s"),_stringval(obj));break;
1461 case OT_NULL: scprintf(_SC("NULL")); break;
1462 case OT_TABLE: scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
1463 case OT_ARRAY: scprintf(_SC("ARRAY %p"),_array(obj));break;
1464 case OT_CLOSURE: scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
1465 case OT_NATIVECLOSURE: scprintf(_SC("NATIVECLOSURE"));break;
1466 case OT_USERDATA: scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
1467 case OT_GENERATOR: scprintf(_SC("GENERATOR %p"),_generator(obj));break;
1468 case OT_THREAD: scprintf(_SC("THREAD [%p]"),_thread(obj));break;
1469 case OT_USERPOINTER: scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
1470 case OT_CLASS: scprintf(_SC("CLASS %p"),_class(obj));break;
1471 case OT_INSTANCE: scprintf(_SC("INSTANCE %p"),_instance(obj));break;
1472 case OT_WEAKREF: scprintf(_SC("WEAKERF %p"),_weakref(obj));break;
1477 scprintf(_SC("\n"));