[DEV] rework Array, RefCounted and WeakRef

This commit is contained in:
Edouard DUPIN 2018-06-27 01:55:10 +02:00
parent db219fa8e6
commit 68295a1431
38 changed files with 973 additions and 833 deletions

View File

@ -318,7 +318,7 @@ int main(int argc, char* argv[])
HRABBITVM v; HRABBITVM v;
int64_t retval = 0; int64_t retval = 0;
#if defined(_MSC_VER) && defined(_DEBUG) #if defined(_MSC_VER) && defined(_DEBUG)
_CrtSetAllocHook(MemAllocHook); _CrtsetAllocHook(MemAllocHook);
#endif #endif
v=sq_open(1024); v=sq_open(1024);

View File

@ -173,7 +173,7 @@ html_static_path = ['_static']
# If true, links to the reST sources are added to the pages. # If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True #html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # If true, "created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True #html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
@ -285,5 +285,5 @@ texinfo_documents = [
# How to display URL addresses: 'footnote', 'no', or 'inline'. # How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote' #texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu. # If true, do not generate a @detailmenu in the "top" node's menu.
#texinfo_no_detailmenu = False #texinfo_no_detailmenu = False

View File

@ -39,6 +39,8 @@ def configure(target, my_module):
'rabbit/sqcompiler.cpp', 'rabbit/sqcompiler.cpp',
'rabbit/sqdebug.cpp', 'rabbit/sqdebug.cpp',
'rabbit/sqfuncstate.cpp', 'rabbit/sqfuncstate.cpp',
'rabbit/RefCounted.cpp',
'rabbit/WeakRef.cpp',
]) ])
my_module.compile_version("c++", 2011) my_module.compile_version("c++", 2011)
my_module.add_depend([ my_module.add_depend([
@ -60,12 +62,14 @@ def configure(target, my_module):
'rabbit/sqfuncproto.hpp', 'rabbit/sqfuncproto.hpp',
'rabbit/sqconfig.hpp', 'rabbit/sqconfig.hpp',
'rabbit/sqcompiler.hpp', 'rabbit/sqcompiler.hpp',
'rabbit/sqarray.hpp', 'rabbit/Array.hpp',
'rabbit/sqclosure.hpp', 'rabbit/sqclosure.hpp',
'rabbit/sqlexer.hpp', 'rabbit/sqlexer.hpp',
'rabbit/sqfuncstate.hpp', 'rabbit/sqfuncstate.hpp',
'rabbit/sqstring.hpp', 'rabbit/sqstring.hpp',
'rabbit/sqtable.hpp', 'rabbit/sqtable.hpp',
'rabbit/RefCounted.hpp',
'rabbit/WeakRef.hpp',
]) ])
return True return True

View File

@ -25,7 +25,7 @@ static int64_t _blob_resize(HRABBITVM v)
SETUP_BLOB(v); SETUP_BLOB(v);
int64_t size; int64_t size;
sq_getinteger(v,2,&size); sq_getinteger(v,2,&size);
if(!self->Resize(size)) if(!self->resize(size))
return sq_throwerror(v,_SC("resize failed")); return sq_throwerror(v,_SC("resize failed"));
return 0; return 0;
} }
@ -47,7 +47,7 @@ static int64_t _blob_swap4(HRABBITVM v)
{ {
SETUP_BLOB(v); SETUP_BLOB(v);
int64_t num=(self->Len()-(self->Len()%4))>>2; int64_t num=(self->Len()-(self->Len()%4))>>2;
unsigned int *t=(unsigned int *)self->GetBuf(); unsigned int *t=(unsigned int *)self->getBuf();
for(int64_t i = 0; i < num; i++) { for(int64_t i = 0; i < num; i++) {
__swap_dword(&t[i]); __swap_dword(&t[i]);
} }
@ -58,7 +58,7 @@ static int64_t _blob_swap2(HRABBITVM v)
{ {
SETUP_BLOB(v); SETUP_BLOB(v);
int64_t num=(self->Len()-(self->Len()%2))>>1; int64_t num=(self->Len()-(self->Len()%2))>>1;
unsigned short *t = (unsigned short *)self->GetBuf(); unsigned short *t = (unsigned short *)self->getBuf();
for(int64_t i = 0; i < num; i++) { for(int64_t i = 0; i < num; i++) {
__swap_word(&t[i]); __swap_word(&t[i]);
} }
@ -73,7 +73,7 @@ static int64_t _blob__set(HRABBITVM v)
sq_getinteger(v,3,&val); sq_getinteger(v,3,&val);
if(idx < 0 || idx >= self->Len()) if(idx < 0 || idx >= self->Len())
return sq_throwerror(v,_SC("index out of range")); return sq_throwerror(v,_SC("index out of range"));
((unsigned char *)self->GetBuf())[idx] = (unsigned char) val; ((unsigned char *)self->getBuf())[idx] = (unsigned char) val;
sq_push(v,3); sq_push(v,3);
return 1; return 1;
} }
@ -91,7 +91,7 @@ static int64_t _blob__get(HRABBITVM v)
sq_getinteger(v,2,&idx); sq_getinteger(v,2,&idx);
if(idx < 0 || idx >= self->Len()) if(idx < 0 || idx >= self->Len())
return sq_throwerror(v,_SC("index out of range")); return sq_throwerror(v,_SC("index out of range"));
sq_pushinteger(v,((unsigned char *)self->GetBuf())[idx]); sq_pushinteger(v,((unsigned char *)self->getBuf())[idx]);
return 1; return 1;
} }
@ -157,7 +157,7 @@ static int64_t _blob__cloned(HRABBITVM v)
} }
//SQBlob *thisone = new SQBlob(other->Len()); //SQBlob *thisone = new SQBlob(other->Len());
SQBlob *thisone = new (sq_malloc(sizeof(SQBlob)))SQBlob(other->Len()); SQBlob *thisone = new (sq_malloc(sizeof(SQBlob)))SQBlob(other->Len());
memcpy(thisone->GetBuf(),other->GetBuf(),thisone->Len()); memcpy(thisone->getBuf(),other->getBuf(),thisone->Len());
if(SQ_FAILED(sq_setinstanceup(v,1,thisone))) { if(SQ_FAILED(sq_setinstanceup(v,1,thisone))) {
thisone->~SQBlob(); thisone->~SQBlob();
sq_free(thisone,sizeof(SQBlob)); sq_free(thisone,sizeof(SQBlob));
@ -244,7 +244,7 @@ SQRESULT sqstd_getblob(HRABBITVM v,int64_t idx,SQUserPointer *ptr)
SQBlob *blob; SQBlob *blob;
if(SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer *)&blob,(SQUserPointer)SQSTD_BLOB_TYPE_TAG))) if(SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer *)&blob,(SQUserPointer)SQSTD_BLOB_TYPE_TAG)))
return -1; return -1;
*ptr = blob->GetBuf(); *ptr = blob->getBuf();
return SQ_OK; return SQ_OK;
} }
@ -269,7 +269,7 @@ SQUserPointer sqstd_createblob(HRABBITVM v, int64_t size)
if(SQ_SUCCEEDED(sq_call(v,2,SQTrue,SQFalse)) if(SQ_SUCCEEDED(sq_call(v,2,SQTrue,SQFalse))
&& SQ_SUCCEEDED(sq_getinstanceup(v,-1,(SQUserPointer *)&blob,(SQUserPointer)SQSTD_BLOB_TYPE_TAG))) { && SQ_SUCCEEDED(sq_getinstanceup(v,-1,(SQUserPointer *)&blob,(SQUserPointer)SQSTD_BLOB_TYPE_TAG))) {
sq_remove(v,-2); sq_remove(v,-2);
return blob->GetBuf(); return blob->getBuf();
} }
} }
sq_settop(v,top); sq_settop(v,top);

View File

@ -39,7 +39,7 @@ struct SQBlob : public SQStream
_ptr += n; _ptr += n;
return n; return n;
} }
bool Resize(int64_t n) { bool resize(int64_t n) {
if(!_owns) return false; if(!_owns) return false;
if(n != _allocated) { if(n != _allocated) {
unsigned char *newbuf = (unsigned char *)sq_malloc(n); unsigned char *newbuf = (unsigned char *)sq_malloc(n);
@ -63,9 +63,9 @@ struct SQBlob : public SQStream
bool ret = true; bool ret = true;
if(_size + n > _allocated) { if(_size + n > _allocated) {
if(_size + n > _size * 2) if(_size + n > _size * 2)
ret = Resize(_size + n); ret = resize(_size + n);
else else
ret = Resize(_size * 2); ret = resize(_size * 2);
} }
_size = _size + n; _size = _size + n;
return ret; return ret;
@ -101,7 +101,7 @@ struct SQBlob : public SQStream
int64_t Flush() { return 0; } int64_t Flush() { return 0; }
int64_t Tell() { return _ptr; } int64_t Tell() { return _ptr; }
int64_t Len() { return _size; } int64_t Len() { return _size; }
SQUserPointer GetBuf(){ return _buf; } SQUserPointer getBuf(){ return _buf; }
private: private:
int64_t _size; int64_t _size;
int64_t _allocated; int64_t _allocated;

View File

@ -110,7 +110,7 @@ struct SQFile : public SQStream {
} }
bool IsValid() { return _handle?true:false; } bool IsValid() { return _handle?true:false; }
bool EOS() { return Tell()==Len()?true:false;} bool EOS() { return Tell()==Len()?true:false;}
SQFILE GetHandle() {return _handle;} SQFILE getHandle() {return _handle;}
private: private:
SQFILE _handle; SQFILE _handle;
bool _owns; bool _owns;
@ -208,7 +208,7 @@ SQRESULT sqstd_getfile(HRABBITVM v, int64_t idx, SQFILE *file)
{ {
SQFile *fileobj = NULL; SQFile *fileobj = NULL;
if(SQ_SUCCEEDED(sq_getinstanceup(v,idx,(SQUserPointer*)&fileobj,(SQUserPointer)SQSTD_FILE_TYPE_TAG))) { if(SQ_SUCCEEDED(sq_getinstanceup(v,idx,(SQUserPointer*)&fileobj,(SQUserPointer)SQSTD_FILE_TYPE_TAG))) {
*file = fileobj->GetHandle(); *file = fileobj->getHandle();
return SQ_OK; return SQ_OK;
} }
return sq_throwerror(v,_SC("not a file")); return sq_throwerror(v,_SC("not a file"));

20
rabbit/Array.cpp Normal file
View File

@ -0,0 +1,20 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#include <rabbit/Array.hpp>
void rabbit::Array::extend(const rabbit::Array *a){
int64_t xlen = a->size();
// TODO: check this condition...
if(xlen) {
for(int64_t iii=0;iii<xlen;++iii) {
append((*a)[iii]);
}
}
}

131
rabbit/Array.hpp Normal file
View File

@ -0,0 +1,131 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#pragma once
namespace rabbit {
class Array : public rabbit::RefCounted
{
private:
Array(SQSharedState* _ss,
int64_t _nsize) {
m_data.resize(_nsize);
}
~Array() {
// TODO: Clean DATA ...
}
public:
// TODO : remove this ETK_ALLOC can do it natively ...
static Array* create(SQSharedState* _ss,
int64_t _nInitialsize) {
Array *newarray=(Array*)SQ_MALLOC(sizeof(Array));
new (newarray) Array(_ss, _nInitialsize);
return newarray;
}
void finalize() {
m_data.resize(0);
}
bool get(const int64_t _nidx,
SQObjectPtr& _val) {
if( _nidx >= 0
&& _nidx < (int64_t)m_data.size()){
SQObjectPtr &o = m_data[_nidx];
_val = _realval(o);
return true;
}
return false;
}
bool set(const int64_t _nidx,const SQObjectPtr& _val) {
if(_nidx>=0 && _nidx<(int64_t)m_data.size()){
m_data[_nidx] = _val;
return true;
}
return false;
}
int64_t next(const SQObjectPtr& _refpos,
SQObjectPtr& _outkey,
SQObjectPtr& _outval) {
uint64_t idx=translateIndex(_refpos);
while(idx<m_data.size()){
//first found
_outkey=(int64_t)idx;
SQObjectPtr& o = m_data[idx];
_outval = _realval(o);
//return idx for the next iteration
return ++idx;
}
//nothing to iterate anymore
return -1;
}
Array* clone() {
Array *anew = create(NULL,0);
anew->m_data.copy(m_data);
return anew;
}
int64_t size() const {
return m_data.size();
}
void resize(int64_t _size) {
SQObjectPtr empty;
resize(_size, empty);
}
void resize(int64_t _size,
SQObjectPtr& _fill) {
m_data.resize(_size, _fill);
shrinkIfNeeded();
}
void reserve(int64_t _size) {
m_data.reserve(_size);
}
void append(const SQObject& _o) {
m_data.push_back(_o);
}
void extend(const Array* _a);
SQObjectPtr &top(){
return m_data.top();
}
void pop() {
m_data.pop_back();
shrinkIfNeeded();
}
bool insert(int64_t _idx,const SQObject& _val) {
if( _idx < 0
|| _idx > (int64_t)m_data.size()) {
return false;
}
m_data.insert(_idx, _val);
return true;
}
void shrinkIfNeeded() {
if(m_data.size() <= m_data.capacity()>>2) {
//shrink the array
m_data.shrinktofit();
}
}
bool remove(int64_t _idx) {
if( _idx < 0
|| _idx >= (int64_t)m_data.size()) {
return false;
}
m_data.remove(_idx);
shrinkIfNeeded();
return true;
}
void release() {
sq_delete(this, Array);
}
SQObjectPtr& operator[] (const size_t _pos) {
return m_data[_pos];
}
const SQObjectPtr& operator[] (const size_t _pos) const {
return m_data[_pos];
}
private:
SQObjectPtrVec m_data;
};
}

44
rabbit/RefCounted.cpp Normal file
View File

@ -0,0 +1,44 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#include <rabbit/RefCounted.hpp>
#include <rabbit/WeakRef.hpp>
#include <rabbit/rabbit.hpp>
#include <rabbit/squtils.hpp>
#include <etk/Allocator.hpp>
rabbit::WeakRef * rabbit::RefCounted::getWeakRef(SQObjectType type) {
if(!_weakref) {
sq_new(_weakref, WeakRef);
#if defined(SQUSEDOUBLE) && !defined(_SQ64)
_weakref->_obj._unVal.raw = 0; //clean the whole union on 32 bits with double
#endif
_weakref->_obj._type = type;
_weakref->_obj._unVal.pRefCounted = this;
}
return _weakref;
}
rabbit::RefCounted::~RefCounted() {
if(_weakref) {
_weakref->_obj._type = OT_NULL;
_weakref->_obj._unVal.pRefCounted = NULL;
}
}
void rabbit::RefCounted::refCountIncrement() {
_uiRef++;
}
int64_t rabbit::RefCounted::refCountDecrement() {
return --_uiRef;
}
int64_t rabbit::RefCounted::refCountget() {
return _uiRef;
}

30
rabbit/RefCounted.hpp Normal file
View File

@ -0,0 +1,30 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <rabbit/rabbit.hpp>
namespace rabbit {
class WeakRef;
class RefCounted {
protected:
int64_t _uiRef = 0;
struct WeakRef *_weakref = null;
public:
RefCounted() {}
virtual ~RefCounted();
WeakRef *getWeakRef(SQObjectType _type);
virtual void release() = 0;
void refCountIncrement();
int64_t refCountDecrement();
int64_t refCountget();
friend WeakRef;
};
}

View File

@ -15,16 +15,16 @@ namespace rabbit {
m_hook = NULL; m_hook = NULL;
} }
~UserData() { ~UserData() {
SetDelegate(NULL); setDelegate(NULL);
} }
static UserData* Create(SQSharedState *ss, int64_t size) { static UserData* create(SQSharedState *ss, int64_t size) {
UserData* ud = (UserData*)SQ_MALLOC(sq_aligning(sizeof(UserData))+size); UserData* ud = (UserData*)SQ_MALLOC(sq_aligning(sizeof(UserData))+size);
new (ud) UserData(ss); new (ud) UserData(ss);
ud->m_size = size; ud->m_size = size;
ud->m_typetag = 0; ud->m_typetag = 0;
return ud; return ud;
} }
void Release() { void release() {
if (m_hook) { if (m_hook) {
m_hook((SQUserPointer)sq_aligning(this + 1),m_size); m_hook((SQUserPointer)sq_aligning(this + 1),m_size);
} }
@ -32,7 +32,7 @@ namespace rabbit {
this->~UserData(); this->~UserData();
SQ_FREE(this, sq_aligning(sizeof(UserData)) + tsize); SQ_FREE(this, sq_aligning(sizeof(UserData)) + tsize);
} }
const int64_t& getSize() const { const int64_t& getsize() const {
return m_size; return m_size;
} }
const SQUserPointer& getTypeTag() const { const SQUserPointer& getTypeTag() const {

19
rabbit/WeakRef.cpp Normal file
View File

@ -0,0 +1,19 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#include <rabbit/RefCounted.hpp>
#include <rabbit/WeakRef.hpp>
#include <rabbit/rabbit.hpp>
#include <rabbit/squtils.hpp>
void rabbit::WeakRef::release() {
if(ISREFCOUNTED(_obj._type)) {
_obj._unVal.pRefCounted->_weakref = null;
}
sq_delete(this, WeakRef);
}

23
rabbit/WeakRef.hpp Normal file
View File

@ -0,0 +1,23 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <rabbit/RefCounted.hpp>
namespace rabbit {
class WeakRef: public RefCounted {
public:
void release();
public:
SQObject _obj;
protected:
friend RefCounted;
};
}

View File

@ -27,19 +27,20 @@
struct SQVM; struct SQVM;
struct SQTable; struct SQTable;
struct SQArray;
struct SQString; struct SQString;
struct SQClosure; struct SQClosure;
struct SQGenerator; struct SQGenerator;
struct SQNativeClosure; struct SQNativeClosure;
struct SQFunctionProto; struct SQFunctionProto;
struct SQRefCounted;
struct SQClass; struct SQClass;
struct SQInstance; struct SQInstance;
struct SQDelegable; struct SQDelegable;
struct SQOuter; struct SQOuter;
namespace rabbit { namespace rabbit {
class UserData; class UserData;
class Array;
class RefCounted;
class WeakRef;
} }
#ifdef _UNICODE #ifdef _UNICODE
@ -116,7 +117,7 @@ typedef enum tagSQObjectType{
typedef union tagSQObjectValue typedef union tagSQObjectValue
{ {
struct SQTable *pTable; struct SQTable *pTable;
struct SQArray *pArray; struct rabbit::Array *pArray;
struct SQClosure *pClosure; struct SQClosure *pClosure;
struct SQOuter *pOuter; struct SQOuter *pOuter;
struct SQGenerator *pGenerator; struct SQGenerator *pGenerator;
@ -127,12 +128,12 @@ typedef union tagSQObjectValue
float_t fFloat; float_t fFloat;
SQUserPointer pUserPointer; SQUserPointer pUserPointer;
struct SQFunctionProto *pFunctionProto; struct SQFunctionProto *pFunctionProto;
struct SQRefCounted *pRefCounted; struct rabbit::RefCounted *pRefCounted;
struct SQDelegable *pDelegable; struct SQDelegable *pDelegable;
struct SQVM *pThread; struct SQVM *pThread;
struct SQClass *pClass; struct SQClass *pClass;
struct SQInstance *pInstance; struct SQInstance *pInstance;
struct SQWeakRef *pWeakRef; struct rabbit::WeakRef *pWeakRef;
SQRawObjectVal raw; SQRawObjectVal raw;
}SQObjectValue; }SQObjectValue;

View File

@ -9,7 +9,7 @@
#include <rabbit/sqvm.hpp> #include <rabbit/sqvm.hpp>
#include <rabbit/sqstring.hpp> #include <rabbit/sqstring.hpp>
#include <rabbit/sqtable.hpp> #include <rabbit/sqtable.hpp>
#include <rabbit/sqarray.hpp> #include <rabbit/Array.hpp>
#include <rabbit/sqfuncproto.hpp> #include <rabbit/sqfuncproto.hpp>
#include <rabbit/sqclosure.hpp> #include <rabbit/sqclosure.hpp>
#include <rabbit/UserData.hpp> #include <rabbit/UserData.hpp>
@ -39,8 +39,8 @@ static bool sq_aux_gettypedarg(HRABBITVM v,int64_t idx,SQObjectType type,SQObjec
int64_t sq_aux_invalidtype(HRABBITVM v,SQObjectType type) int64_t sq_aux_invalidtype(HRABBITVM v,SQObjectType type)
{ {
uint64_t buf_size = 100 *sizeof(SQChar); uint64_t buf_size = 100 *sizeof(SQChar);
scsprintf(_ss(v)->GetScratchPad(buf_size), buf_size, _SC("unexpected type %s"), IdType2Name(type)); scsprintf(_ss(v)->getScratchPad(buf_size), buf_size, _SC("unexpected type %s"), IdType2Name(type));
return sq_throwerror(v, _ss(v)->GetScratchPad(-1)); return sq_throwerror(v, _ss(v)->getScratchPad(-1));
} }
HRABBITVM sq_open(int64_t initialstacksize) HRABBITVM sq_open(int64_t initialstacksize)
@ -133,7 +133,7 @@ SQRESULT sq_compile(HRABBITVM v,SQLEXREADFUNC read,SQUserPointer p,const SQChar
SQObjectPtr o; SQObjectPtr o;
#ifndef NO_COMPILER #ifndef NO_COMPILER
if(Compile(v, read, p, sourcename, o, raiseerror?true:false, _ss(v)->_debuginfo)) { if(Compile(v, read, p, sourcename, o, raiseerror?true:false, _ss(v)->_debuginfo)) {
v->Push(SQClosure::Create(_ss(v), _funcproto(o), _table(v->_roottable)->GetWeakRef(OT_TABLE))); v->Push(SQClosure::create(_ss(v), _funcproto(o), _table(v->_roottable)->getWeakRef(OT_TABLE)));
return SQ_OK; return SQ_OK;
} }
return SQ_ERROR; return SQ_ERROR;
@ -161,21 +161,21 @@ void sq_addref(HRABBITVM v,HSQOBJECT *po)
uint64_t sq_getrefcount(HRABBITVM v,HSQOBJECT *po) uint64_t sq_getrefcount(HRABBITVM v,HSQOBJECT *po)
{ {
if(!ISREFCOUNTED(sq_type(*po))) return 0; if(!ISREFCOUNTED(sq_type(*po))) return 0;
return po->_unVal.pRefCounted->_uiRef; return po->_unVal.pRefCounted->refCountget();
} }
SQBool sq_release(HRABBITVM v,HSQOBJECT *po) SQBool sq_release(HRABBITVM v,HSQOBJECT *po)
{ {
if(!ISREFCOUNTED(sq_type(*po))) return SQTrue; if(!ISREFCOUNTED(sq_type(*po))) return SQTrue;
bool ret = (po->_unVal.pRefCounted->_uiRef <= 1) ? SQTrue : SQFalse; bool ret = (po->_unVal.pRefCounted->refCountget() <= 1) ? SQTrue : SQFalse;
__Release(po->_type,po->_unVal); __release(po->_type,po->_unVal);
return ret; //the ret val doesn't work(and cannot be fixed) return ret; //the ret val doesn't work(and cannot be fixed)
} }
uint64_t sq_getvmrefcount(HRABBITVM SQ_UNUSED_ARG(v), const HSQOBJECT *po) uint64_t sq_getvmrefcount(HRABBITVM SQ_UNUSED_ARG(v), const HSQOBJECT *po)
{ {
if (!ISREFCOUNTED(sq_type(*po))) return 0; if (!ISREFCOUNTED(sq_type(*po))) return 0;
return po->_unVal.pRefCounted->_uiRef; return po->_unVal.pRefCounted->refCountget();
} }
const SQChar *sq_objtostring(const HSQOBJECT *o) const SQChar *sq_objtostring(const HSQOBJECT *o)
@ -226,7 +226,7 @@ void sq_pushnull(HRABBITVM v)
void sq_pushstring(HRABBITVM v,const SQChar *s,int64_t len) void sq_pushstring(HRABBITVM v,const SQChar *s,int64_t len)
{ {
if(s) if(s)
v->Push(SQObjectPtr(SQString::Create(_ss(v), s, len))); v->Push(SQObjectPtr(SQString::create(_ss(v), s, len)));
else v->PushNull(); else v->PushNull();
} }
@ -257,24 +257,24 @@ void sq_pushthread(HRABBITVM v, HRABBITVM thread)
SQUserPointer sq_newuserdata(HRABBITVM v,uint64_t size) SQUserPointer sq_newuserdata(HRABBITVM v,uint64_t size)
{ {
rabbit::UserData *ud = rabbit::UserData::Create(_ss(v), size + SQ_ALIGNMENT); rabbit::UserData *ud = rabbit::UserData::create(_ss(v), size + SQ_ALIGNMENT);
v->Push(ud); v->Push(ud);
return (SQUserPointer)sq_aligning(ud + 1); return (SQUserPointer)sq_aligning(ud + 1);
} }
void sq_newtable(HRABBITVM v) void sq_newtable(HRABBITVM v)
{ {
v->Push(SQTable::Create(_ss(v), 0)); v->Push(SQTable::create(_ss(v), 0));
} }
void sq_newtableex(HRABBITVM v,int64_t initialcapacity) void sq_newtableex(HRABBITVM v,int64_t initialcapacity)
{ {
v->Push(SQTable::Create(_ss(v), initialcapacity)); v->Push(SQTable::create(_ss(v), initialcapacity));
} }
void sq_newarray(HRABBITVM v,int64_t size) void sq_newarray(HRABBITVM v,int64_t size)
{ {
v->Push(SQArray::Create(_ss(v), size)); v->Push(rabbit::Array::create(_ss(v), size));
} }
SQRESULT sq_newclass(HRABBITVM v,SQBool hasbase) SQRESULT sq_newclass(HRABBITVM v,SQBool hasbase)
@ -286,7 +286,7 @@ SQRESULT sq_newclass(HRABBITVM v,SQBool hasbase)
return sq_throwerror(v,_SC("invalid base type")); return sq_throwerror(v,_SC("invalid base type"));
baseclass = _class(base); baseclass = _class(base);
} }
SQClass *newclass = SQClass::Create(_ss(v), baseclass); SQClass *newclass = SQClass::create(_ss(v), baseclass);
if(baseclass) v->Pop(); if(baseclass) v->Pop();
v->Push(newclass); v->Push(newclass);
return SQ_OK; return SQ_OK;
@ -306,7 +306,7 @@ SQRESULT sq_arrayappend(HRABBITVM v,int64_t idx)
sq_aux_paramscheck(v,2); sq_aux_paramscheck(v,2);
SQObjectPtr *arr; SQObjectPtr *arr;
_GETSAFE_OBJ(v, idx, OT_ARRAY,arr); _GETSAFE_OBJ(v, idx, OT_ARRAY,arr);
_array(*arr)->Append(v->GetUp(-1)); _array(*arr)->append(v->getUp(-1));
v->Pop(); v->Pop();
return SQ_OK; return SQ_OK;
} }
@ -316,9 +316,11 @@ SQRESULT sq_arraypop(HRABBITVM v,int64_t idx,SQBool pushval)
sq_aux_paramscheck(v, 1); sq_aux_paramscheck(v, 1);
SQObjectPtr *arr; SQObjectPtr *arr;
_GETSAFE_OBJ(v, idx, OT_ARRAY,arr); _GETSAFE_OBJ(v, idx, OT_ARRAY,arr);
if(_array(*arr)->Size() > 0) { if(_array(*arr)->size() > 0) {
if(pushval != 0){ v->Push(_array(*arr)->Top()); } if(pushval != 0){
_array(*arr)->Pop(); v->Push(_array(*arr)->top());
}
_array(*arr)->pop();
return SQ_OK; return SQ_OK;
} }
return sq_throwerror(v, _SC("empty array")); return sq_throwerror(v, _SC("empty array"));
@ -330,7 +332,7 @@ SQRESULT sq_arrayresize(HRABBITVM v,int64_t idx,int64_t newsize)
SQObjectPtr *arr; SQObjectPtr *arr;
_GETSAFE_OBJ(v, idx, OT_ARRAY,arr); _GETSAFE_OBJ(v, idx, OT_ARRAY,arr);
if(newsize >= 0) { if(newsize >= 0) {
_array(*arr)->Resize(newsize); _array(*arr)->resize(newsize);
return SQ_OK; return SQ_OK;
} }
return sq_throwerror(v,_SC("negative size")); return sq_throwerror(v,_SC("negative size"));
@ -342,15 +344,16 @@ SQRESULT sq_arrayreverse(HRABBITVM v,int64_t idx)
sq_aux_paramscheck(v, 1); sq_aux_paramscheck(v, 1);
SQObjectPtr *o; SQObjectPtr *o;
_GETSAFE_OBJ(v, idx, OT_ARRAY,o); _GETSAFE_OBJ(v, idx, OT_ARRAY,o);
SQArray *arr = _array(*o); rabbit::Array *arr = _array(*o);
if(arr->Size() > 0) { if(arr->size() > 0) {
SQObjectPtr t; SQObjectPtr t;
int64_t size = arr->Size(); int64_t size = arr->size();
int64_t n = size >> 1; size -= 1; int64_t n = size >> 1; size -= 1;
for(int64_t i = 0; i < n; i++) { for(int64_t i = 0; i < n; i++) {
t = arr->_values[i]; // TODO: set a swap
arr->_values[i] = arr->_values[size-i]; t = (*arr)[i];
arr->_values[size-i] = t; (*arr)[i] = (*arr)[size-i];
(*arr)[size-i] = t;
} }
return SQ_OK; return SQ_OK;
} }
@ -362,7 +365,7 @@ SQRESULT sq_arrayremove(HRABBITVM v,int64_t idx,int64_t itemidx)
sq_aux_paramscheck(v, 1); sq_aux_paramscheck(v, 1);
SQObjectPtr *arr; SQObjectPtr *arr;
_GETSAFE_OBJ(v, idx, OT_ARRAY,arr); _GETSAFE_OBJ(v, idx, OT_ARRAY,arr);
return _array(*arr)->Remove(itemidx) ? SQ_OK : sq_throwerror(v,_SC("index out of range")); return _array(*arr)->remove(itemidx) ? SQ_OK : sq_throwerror(v,_SC("index out of range"));
} }
SQRESULT sq_arrayinsert(HRABBITVM v,int64_t idx,int64_t destpos) SQRESULT sq_arrayinsert(HRABBITVM v,int64_t idx,int64_t destpos)
@ -370,17 +373,17 @@ SQRESULT sq_arrayinsert(HRABBITVM v,int64_t idx,int64_t destpos)
sq_aux_paramscheck(v, 1); sq_aux_paramscheck(v, 1);
SQObjectPtr *arr; SQObjectPtr *arr;
_GETSAFE_OBJ(v, idx, OT_ARRAY,arr); _GETSAFE_OBJ(v, idx, OT_ARRAY,arr);
SQRESULT ret = _array(*arr)->Insert(destpos, v->GetUp(-1)) ? SQ_OK : sq_throwerror(v,_SC("index out of range")); SQRESULT ret = _array(*arr)->insert(destpos, v->getUp(-1)) ? SQ_OK : sq_throwerror(v,_SC("index out of range"));
v->Pop(); v->Pop();
return ret; return ret;
} }
void sq_newclosure(HRABBITVM v,SQFUNCTION func,uint64_t nfreevars) void sq_newclosure(HRABBITVM v,SQFUNCTION func,uint64_t nfreevars)
{ {
SQNativeClosure *nc = SQNativeClosure::Create(_ss(v), func,nfreevars); SQNativeClosure *nc = SQNativeClosure::create(_ss(v), func,nfreevars);
nc->_nparamscheck = 0; nc->_nparamscheck = 0;
for(uint64_t i = 0; i < nfreevars; i++) { for(uint64_t i = 0; i < nfreevars; i++) {
nc->_outervalues[i] = v->Top(); nc->_outervalues[i] = v->top();
v->Pop(); v->Pop();
} }
v->Push(SQObjectPtr(nc)); v->Push(SQObjectPtr(nc));
@ -411,7 +414,7 @@ SQRESULT sq_setnativeclosurename(HRABBITVM v,int64_t idx,const SQChar *name)
SQObject o = stack_get(v, idx); SQObject o = stack_get(v, idx);
if(sq_isnativeclosure(o)) { if(sq_isnativeclosure(o)) {
SQNativeClosure *nc = _nativeclosure(o); SQNativeClosure *nc = _nativeclosure(o);
nc->_name = SQString::Create(_ss(v),name); nc->_name = SQString::create(_ss(v),name);
return SQ_OK; return SQ_OK;
} }
return sq_throwerror(v,_SC("the object is not a nativeclosure")); return sq_throwerror(v,_SC("the object is not a nativeclosure"));
@ -451,11 +454,11 @@ SQRESULT sq_bindenv(HRABBITVM v,int64_t idx)
!sq_isclass(env) && !sq_isclass(env) &&
!sq_isinstance(env)) !sq_isinstance(env))
return sq_throwerror(v,_SC("invalid environment")); return sq_throwerror(v,_SC("invalid environment"));
SQWeakRef *w = _refcounted(env)->GetWeakRef(sq_type(env)); rabbit::WeakRef *w = _refcounted(env)->getWeakRef(sq_type(env));
SQObjectPtr ret; SQObjectPtr ret;
if(sq_isclosure(o)) { if(sq_isclosure(o)) {
SQClosure *c = _closure(o)->Clone(); SQClosure *c = _closure(o)->clone();
__ObjRelease(c->_env); __Objrelease(c->_env);
c->_env = w; c->_env = w;
__ObjAddRef(c->_env); __ObjAddRef(c->_env);
if(_closure(o)->_base) { if(_closure(o)->_base) {
@ -465,8 +468,8 @@ SQRESULT sq_bindenv(HRABBITVM v,int64_t idx)
ret = c; ret = c;
} }
else { //then must be a native closure else { //then must be a native closure
SQNativeClosure *c = _nativeclosure(o)->Clone(); SQNativeClosure *c = _nativeclosure(o)->clone();
__ObjRelease(c->_env); __Objrelease(c->_env);
c->_env = w; c->_env = w;
__ObjAddRef(c->_env); __ObjAddRef(c->_env);
ret = c; ret = c;
@ -498,7 +501,7 @@ SQRESULT sq_setclosureroot(HRABBITVM v,int64_t idx)
SQObject o = stack_get(v, -1); SQObject o = stack_get(v, -1);
if(!sq_isclosure(c)) return sq_throwerror(v, _SC("closure expected")); if(!sq_isclosure(c)) return sq_throwerror(v, _SC("closure expected"));
if(sq_istable(o)) { if(sq_istable(o)) {
_closure(c)->SetRoot(_table(o)->GetWeakRef(OT_TABLE)); _closure(c)->setRoot(_table(o)->getWeakRef(OT_TABLE));
v->Pop(); v->Pop();
return SQ_OK; return SQ_OK;
} }
@ -518,7 +521,7 @@ SQRESULT sq_clear(HRABBITVM v,int64_t idx)
SQObject &o=stack_get(v,idx); SQObject &o=stack_get(v,idx);
switch(sq_type(o)) { switch(sq_type(o)) {
case OT_TABLE: _table(o)->Clear(); break; case OT_TABLE: _table(o)->Clear(); break;
case OT_ARRAY: _array(o)->Resize(0); break; case OT_ARRAY: _array(o)->resize(0); break;
default: default:
return sq_throwerror(v, _SC("clear only works on table and array")); return sq_throwerror(v, _SC("clear only works on table and array"));
break; break;
@ -705,7 +708,7 @@ SQRESULT sq_clone(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &o = stack_get(v,idx); SQObjectPtr &o = stack_get(v,idx);
v->PushNull(); v->PushNull();
if(!v->Clone(o, stack_get(v, -1))){ if(!v->clone(o, stack_get(v, -1))){
v->Pop(); v->Pop();
return SQ_ERROR; return SQ_ERROR;
} }
@ -719,8 +722,8 @@ int64_t sq_getsize(HRABBITVM v, int64_t idx)
switch(type) { switch(type) {
case OT_STRING: return _string(o)->_len; case OT_STRING: return _string(o)->_len;
case OT_TABLE: return _table(o)->CountUsed(); case OT_TABLE: return _table(o)->CountUsed();
case OT_ARRAY: return _array(o)->Size(); case OT_ARRAY: return _array(o)->size();
case OT_USERDATA: return _userdata(o)->getSize(); case OT_USERDATA: return _userdata(o)->getsize();
case OT_INSTANCE: return _instance(o)->_class->_udsize; case OT_INSTANCE: return _instance(o)->_class->_udsize;
case OT_CLASS: return _class(o)->_udsize; case OT_CLASS: return _class(o)->_udsize;
default: default:
@ -852,7 +855,7 @@ void sq_poptop(HRABBITVM v)
void sq_remove(HRABBITVM v, int64_t idx) void sq_remove(HRABBITVM v, int64_t idx)
{ {
v->Remove(idx); v->remove(idx);
} }
int64_t sq_cmp(HRABBITVM v) int64_t sq_cmp(HRABBITVM v)
@ -867,9 +870,9 @@ SQRESULT sq_newslot(HRABBITVM v, int64_t idx, SQBool bstatic)
sq_aux_paramscheck(v, 3); sq_aux_paramscheck(v, 3);
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
if(sq_type(self) == OT_TABLE || sq_type(self) == OT_CLASS) { if(sq_type(self) == OT_TABLE || sq_type(self) == OT_CLASS) {
SQObjectPtr &key = v->GetUp(-2); SQObjectPtr &key = v->getUp(-2);
if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null is not a valid key")); if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null is not a valid key"));
v->NewSlot(self, key, v->GetUp(-1),bstatic?true:false); v->NewSlot(self, key, v->getUp(-1),bstatic?true:false);
v->Pop(2); v->Pop(2);
} }
return SQ_OK; return SQ_OK;
@ -880,14 +883,14 @@ SQRESULT sq_deleteslot(HRABBITVM v,int64_t idx,SQBool pushval)
sq_aux_paramscheck(v, 2); sq_aux_paramscheck(v, 2);
SQObjectPtr *self; SQObjectPtr *self;
_GETSAFE_OBJ(v, idx, OT_TABLE,self); _GETSAFE_OBJ(v, idx, OT_TABLE,self);
SQObjectPtr &key = v->GetUp(-1); SQObjectPtr &key = v->getUp(-1);
if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null is not a valid key")); if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null is not a valid key"));
SQObjectPtr res; SQObjectPtr res;
if(!v->DeleteSlot(*self, key, res)){ if(!v->DeleteSlot(*self, key, res)){
v->Pop(); v->Pop();
return SQ_ERROR; return SQ_ERROR;
} }
if(pushval) v->GetUp(-1) = res; if(pushval) v->getUp(-1) = res;
else v->Pop(); else v->Pop();
return SQ_OK; return SQ_OK;
} }
@ -895,7 +898,7 @@ SQRESULT sq_deleteslot(HRABBITVM v,int64_t idx,SQBool pushval)
SQRESULT sq_set(HRABBITVM v,int64_t idx) SQRESULT sq_set(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
if(v->Set(self, v->GetUp(-2), v->GetUp(-1),DONT_FALL_BACK)) { if(v->set(self, v->getUp(-2), v->getUp(-1),DONT_FALL_BACK)) {
v->Pop(2); v->Pop(2);
return SQ_OK; return SQ_OK;
} }
@ -905,30 +908,30 @@ SQRESULT sq_set(HRABBITVM v,int64_t idx)
SQRESULT sq_rawset(HRABBITVM v,int64_t idx) SQRESULT sq_rawset(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
SQObjectPtr &key = v->GetUp(-2); SQObjectPtr &key = v->getUp(-2);
if(sq_type(key) == OT_NULL) { if(sq_type(key) == OT_NULL) {
v->Pop(2); v->Pop(2);
return sq_throwerror(v, _SC("null key")); return sq_throwerror(v, _SC("null key"));
} }
switch(sq_type(self)) { switch(sq_type(self)) {
case OT_TABLE: case OT_TABLE:
_table(self)->NewSlot(key, v->GetUp(-1)); _table(self)->NewSlot(key, v->getUp(-1));
v->Pop(2); v->Pop(2);
return SQ_OK; return SQ_OK;
break; break;
case OT_CLASS: case OT_CLASS:
_class(self)->NewSlot(_ss(v), key, v->GetUp(-1),false); _class(self)->NewSlot(_ss(v), key, v->getUp(-1),false);
v->Pop(2); v->Pop(2);
return SQ_OK; return SQ_OK;
break; break;
case OT_INSTANCE: case OT_INSTANCE:
if(_instance(self)->Set(key, v->GetUp(-1))) { if(_instance(self)->set(key, v->getUp(-1))) {
v->Pop(2); v->Pop(2);
return SQ_OK; return SQ_OK;
} }
break; break;
case OT_ARRAY: case OT_ARRAY:
if(v->Set(self, key, v->GetUp(-1),false)) { if(v->set(self, key, v->getUp(-1),false)) {
v->Pop(2); v->Pop(2);
return SQ_OK; return SQ_OK;
} }
@ -937,16 +940,16 @@ SQRESULT sq_rawset(HRABBITVM v,int64_t idx)
v->Pop(2); v->Pop(2);
return sq_throwerror(v, _SC("rawset works only on array/table/class and instance")); return sq_throwerror(v, _SC("rawset works only on array/table/class and instance"));
} }
v->Raise_IdxError(v->GetUp(-2));return SQ_ERROR; v->Raise_IdxError(v->getUp(-2));return SQ_ERROR;
} }
SQRESULT sq_newmember(HRABBITVM v,int64_t idx,SQBool bstatic) SQRESULT sq_newmember(HRABBITVM v,int64_t idx,SQBool bstatic)
{ {
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
if(sq_type(self) != OT_CLASS) return sq_throwerror(v, _SC("new member only works with classes")); if(sq_type(self) != OT_CLASS) return sq_throwerror(v, _SC("new member only works with classes"));
SQObjectPtr &key = v->GetUp(-3); SQObjectPtr &key = v->getUp(-3);
if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null key")); if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null key"));
if(!v->NewSlotA(self,key,v->GetUp(-2),v->GetUp(-1),bstatic?true:false,false)) { if(!v->NewSlotA(self,key,v->getUp(-2),v->getUp(-1),bstatic?true:false,false)) {
v->Pop(3); v->Pop(3);
return SQ_ERROR; return SQ_ERROR;
} }
@ -958,9 +961,9 @@ SQRESULT sq_rawnewmember(HRABBITVM v,int64_t idx,SQBool bstatic)
{ {
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
if(sq_type(self) != OT_CLASS) return sq_throwerror(v, _SC("new member only works with classes")); if(sq_type(self) != OT_CLASS) return sq_throwerror(v, _SC("new member only works with classes"));
SQObjectPtr &key = v->GetUp(-3); SQObjectPtr &key = v->getUp(-3);
if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null key")); if(sq_type(key) == OT_NULL) return sq_throwerror(v, _SC("null key"));
if(!v->NewSlotA(self,key,v->GetUp(-2),v->GetUp(-1),bstatic?true:false,true)) { if(!v->NewSlotA(self,key,v->getUp(-2),v->getUp(-1),bstatic?true:false,true)) {
v->Pop(3); v->Pop(3);
return SQ_ERROR; return SQ_ERROR;
} }
@ -971,25 +974,25 @@ SQRESULT sq_rawnewmember(HRABBITVM v,int64_t idx,SQBool bstatic)
SQRESULT sq_setdelegate(HRABBITVM v,int64_t idx) SQRESULT sq_setdelegate(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &self = stack_get(v, idx); SQObjectPtr &self = stack_get(v, idx);
SQObjectPtr &mt = v->GetUp(-1); SQObjectPtr &mt = v->getUp(-1);
SQObjectType type = sq_type(self); SQObjectType type = sq_type(self);
switch(type) { switch(type) {
case OT_TABLE: case OT_TABLE:
if(sq_type(mt) == OT_TABLE) { if(sq_type(mt) == OT_TABLE) {
if(!_table(self)->SetDelegate(_table(mt))) { if(!_table(self)->setDelegate(_table(mt))) {
return sq_throwerror(v, _SC("delagate cycle")); return sq_throwerror(v, _SC("delagate cycle"));
} }
v->Pop(); v->Pop();
} }
else if(sq_type(mt)==OT_NULL) { else if(sq_type(mt)==OT_NULL) {
_table(self)->SetDelegate(NULL); v->Pop(); } _table(self)->setDelegate(NULL); v->Pop(); }
else return sq_aux_invalidtype(v,type); else return sq_aux_invalidtype(v,type);
break; break;
case OT_USERDATA: case OT_USERDATA:
if(sq_type(mt)==OT_TABLE) { if(sq_type(mt)==OT_TABLE) {
_userdata(self)->SetDelegate(_table(mt)); v->Pop(); } _userdata(self)->setDelegate(_table(mt)); v->Pop(); }
else if(sq_type(mt)==OT_NULL) { else if(sq_type(mt)==OT_NULL) {
_userdata(self)->SetDelegate(NULL); v->Pop(); } _userdata(self)->setDelegate(NULL); v->Pop(); }
else return sq_aux_invalidtype(v, type); else return sq_aux_invalidtype(v, type);
break; break;
default: default:
@ -1004,13 +1007,13 @@ SQRESULT sq_rawdeleteslot(HRABBITVM v,int64_t idx,SQBool pushval)
sq_aux_paramscheck(v, 2); sq_aux_paramscheck(v, 2);
SQObjectPtr *self; SQObjectPtr *self;
_GETSAFE_OBJ(v, idx, OT_TABLE,self); _GETSAFE_OBJ(v, idx, OT_TABLE,self);
SQObjectPtr &key = v->GetUp(-1); SQObjectPtr &key = v->getUp(-1);
SQObjectPtr t; SQObjectPtr t;
if(_table(*self)->Get(key,t)) { if(_table(*self)->get(key,t)) {
_table(*self)->Remove(key); _table(*self)->remove(key);
} }
if(pushval != 0) if(pushval != 0)
v->GetUp(-1) = t; v->getUp(-1) = t;
else else
v->Pop(); v->Pop();
return SQ_OK; return SQ_OK;
@ -1037,8 +1040,8 @@ SQRESULT sq_getdelegate(HRABBITVM v,int64_t idx)
SQRESULT sq_get(HRABBITVM v,int64_t idx) SQRESULT sq_get(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &self=stack_get(v,idx); SQObjectPtr &self=stack_get(v,idx);
SQObjectPtr &obj = v->GetUp(-1); SQObjectPtr &obj = v->getUp(-1);
if(v->Get(self,obj,obj,false,DONT_FALL_BACK)) if(v->get(self,obj,obj,false,DONT_FALL_BACK))
return SQ_OK; return SQ_OK;
v->Pop(); v->Pop();
return SQ_ERROR; return SQ_ERROR;
@ -1047,23 +1050,23 @@ SQRESULT sq_get(HRABBITVM v,int64_t idx)
SQRESULT sq_rawget(HRABBITVM v,int64_t idx) SQRESULT sq_rawget(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr &self=stack_get(v,idx); SQObjectPtr &self=stack_get(v,idx);
SQObjectPtr &obj = v->GetUp(-1); SQObjectPtr &obj = v->getUp(-1);
switch(sq_type(self)) { switch(sq_type(self)) {
case OT_TABLE: case OT_TABLE:
if(_table(self)->Get(obj,obj)) if(_table(self)->get(obj,obj))
return SQ_OK; return SQ_OK;
break; break;
case OT_CLASS: case OT_CLASS:
if(_class(self)->Get(obj,obj)) if(_class(self)->get(obj,obj))
return SQ_OK; return SQ_OK;
break; break;
case OT_INSTANCE: case OT_INSTANCE:
if(_instance(self)->Get(obj,obj)) if(_instance(self)->get(obj,obj))
return SQ_OK; return SQ_OK;
break; break;
case OT_ARRAY:{ case OT_ARRAY:{
if(sq_isnumeric(obj)){ if(sq_isnumeric(obj)){
if(_array(self)->Get(tointeger(obj),obj)) { if(_array(self)->get(tointeger(obj),obj)) {
return SQ_OK; return SQ_OK;
} }
} }
@ -1107,7 +1110,7 @@ const SQChar *sq_getlocal(HRABBITVM v,uint64_t level,uint64_t idx)
return _stringval(func->_outervalues[idx]._name); return _stringval(func->_outervalues[idx]._name);
} }
idx -= func->_noutervalues; idx -= func->_noutervalues;
return func->GetLocal(v,stackbase,idx,(int64_t)(ci._ip-func->_instructions)-1); return func->getLocal(v,stackbase,idx,(int64_t)(ci._ip-func->_instructions)-1);
} }
return NULL; return NULL;
} }
@ -1124,13 +1127,13 @@ void sq_resetobject(HSQOBJECT *po)
SQRESULT sq_throwerror(HRABBITVM v,const SQChar *err) SQRESULT sq_throwerror(HRABBITVM v,const SQChar *err)
{ {
v->_lasterror=SQString::Create(_ss(v),err); v->_lasterror=SQString::create(_ss(v),err);
return SQ_ERROR; return SQ_ERROR;
} }
SQRESULT sq_throwobject(HRABBITVM v) SQRESULT sq_throwobject(HRABBITVM v)
{ {
v->_lasterror = v->GetUp(-1); v->_lasterror = v->getUp(-1);
v->Pop(); v->Pop();
return SQ_ERROR; return SQ_ERROR;
} }
@ -1159,10 +1162,10 @@ SQRESULT sq_reservestack(HRABBITVM v,int64_t nsize)
SQRESULT sq_resume(HRABBITVM v,SQBool retval,SQBool raiseerror) SQRESULT sq_resume(HRABBITVM v,SQBool retval,SQBool raiseerror)
{ {
if (sq_type(v->GetUp(-1)) == OT_GENERATOR) if (sq_type(v->getUp(-1)) == OT_GENERATOR)
{ {
v->PushNull(); //retval v->PushNull(); //retval
if (!v->Execute(v->GetUp(-2), 0, v->_top, v->GetUp(-1), raiseerror, SQVM::ET_RESUME_GENERATOR)) if (!v->Execute(v->getUp(-2), 0, v->_top, v->getUp(-1), raiseerror, SQVM::ET_RESUME_GENERATOR))
{v->Raise_Error(v->_lasterror); return SQ_ERROR;} {v->Raise_Error(v->_lasterror); return SQ_ERROR;}
if(!retval) if(!retval)
v->Pop(); v->Pop();
@ -1174,7 +1177,7 @@ SQRESULT sq_resume(HRABBITVM v,SQBool retval,SQBool raiseerror)
SQRESULT sq_call(HRABBITVM v,int64_t params,SQBool retval,SQBool raiseerror) SQRESULT sq_call(HRABBITVM v,int64_t params,SQBool retval,SQBool raiseerror)
{ {
SQObjectPtr res; SQObjectPtr res;
if(v->Call(v->GetUp(-(params+1)),params,v->_top-params,res,raiseerror?true:false)){ if(v->Call(v->getUp(-(params+1)),params,v->_top-params,res,raiseerror?true:false)){
if(!v->_suspended) { if(!v->_suspended) {
v->Pop(params);//pop args v->Pop(params);//pop args
@ -1195,7 +1198,7 @@ SQRESULT sq_call(HRABBITVM v,int64_t params,SQBool retval,SQBool raiseerror)
SQRESULT sq_tailcall(HRABBITVM v, int64_t nparams) SQRESULT sq_tailcall(HRABBITVM v, int64_t nparams)
{ {
SQObjectPtr &res = v->GetUp(-(nparams + 1)); SQObjectPtr &res = v->getUp(-(nparams + 1));
if (sq_type(res) != OT_CLOSURE) { if (sq_type(res) != OT_CLOSURE) {
return sq_throwerror(v, _SC("only closure can be tail called")); return sq_throwerror(v, _SC("only closure can be tail called"));
} }
@ -1225,10 +1228,10 @@ SQRESULT sq_wakeupvm(HRABBITVM v,SQBool wakeupret,SQBool retval,SQBool raiseerro
int64_t target = v->_suspended_target; int64_t target = v->_suspended_target;
if(wakeupret) { if(wakeupret) {
if(target != -1) { if(target != -1) {
v->GetAt(v->_stackbase+v->_suspended_target)=v->GetUp(-1); //retval v->getAt(v->_stackbase+v->_suspended_target)=v->getUp(-1); //retval
} }
v->Pop(); v->Pop();
} else if(target != -1) { v->GetAt(v->_stackbase+v->_suspended_target).Null(); } } else if(target != -1) { v->getAt(v->_stackbase+v->_suspended_target).Null(); }
SQObjectPtr dummy; SQObjectPtr dummy;
if(!v->Execute(dummy,-1,-1,ret,raiseerror,throwerror?SQVM::ET_RESUME_THROW_VM : SQVM::ET_RESUME_VM)) { if(!v->Execute(dummy,-1,-1,ret,raiseerror,throwerror?SQVM::ET_RESUME_THROW_VM : SQVM::ET_RESUME_VM)) {
return SQ_ERROR; return SQ_ERROR;
@ -1311,7 +1314,7 @@ SQRESULT sq_readclosure(HRABBITVM v,SQREADFUNC r,SQUserPointer up)
SQChar *sq_getscratchpad(HRABBITVM v,int64_t minsize) SQChar *sq_getscratchpad(HRABBITVM v,int64_t minsize)
{ {
return _ss(v)->GetScratchPad(minsize); return _ss(v)->getScratchPad(minsize);
} }
SQRESULT sq_resurrectunreachable(HRABBITVM v) SQRESULT sq_resurrectunreachable(HRABBITVM v)
@ -1319,7 +1322,7 @@ SQRESULT sq_resurrectunreachable(HRABBITVM v)
return sq_throwerror(v,_SC("sq_resurrectunreachable requires a garbage collector build")); return sq_throwerror(v,_SC("sq_resurrectunreachable requires a garbage collector build"));
} }
// TODO: Remove this... // TODO: remove this...
int64_t sq_collectgarbage(HRABBITVM v) int64_t sq_collectgarbage(HRABBITVM v)
{ {
return -1; return -1;
@ -1403,8 +1406,8 @@ SQRESULT sq_setattributes(HRABBITVM v,int64_t idx)
v->Pop(2); v->Pop(2);
v->Push(attrs); v->Push(attrs);
return SQ_OK; return SQ_OK;
}else if(_class(*o)->GetAttributes(key,attrs)) { }else if(_class(*o)->getAttributes(key,attrs)) {
_class(*o)->SetAttributes(key,val); _class(*o)->setAttributes(key,val);
v->Pop(2); v->Pop(2);
v->Push(attrs); v->Push(attrs);
return SQ_OK; return SQ_OK;
@ -1424,7 +1427,7 @@ SQRESULT sq_getattributes(HRABBITVM v,int64_t idx)
v->Push(attrs); v->Push(attrs);
return SQ_OK; return SQ_OK;
} }
else if(_class(*o)->GetAttributes(key,attrs)) { else if(_class(*o)->getAttributes(key,attrs)) {
v->Pop(); v->Pop();
v->Push(attrs); v->Push(attrs);
return SQ_OK; return SQ_OK;
@ -1439,7 +1442,7 @@ SQRESULT sq_getmemberhandle(HRABBITVM v,int64_t idx,HSQMEMBERHANDLE *handle)
SQObjectPtr &key = stack_get(v,-1); SQObjectPtr &key = stack_get(v,-1);
SQTable *m = _class(*o)->_members; SQTable *m = _class(*o)->_members;
SQObjectPtr val; SQObjectPtr val;
if(m->Get(key,val)) { if(m->get(key,val)) {
handle->_static = _isfield(val) ? SQFalse : SQTrue; handle->_static = _isfield(val) ? SQFalse : SQTrue;
handle->_index = _member_idx(val); handle->_index = _member_idx(val);
v->Pop(); v->Pop();
@ -1526,7 +1529,7 @@ SQRESULT sq_createinstance(HRABBITVM v,int64_t idx)
{ {
SQObjectPtr *o = NULL; SQObjectPtr *o = NULL;
_GETSAFE_OBJ(v, idx, OT_CLASS,o); _GETSAFE_OBJ(v, idx, OT_CLASS,o);
v->Push(_class(*o)->CreateInstance()); v->Push(_class(*o)->createInstance());
return SQ_OK; return SQ_OK;
} }
@ -1534,7 +1537,7 @@ void sq_weakref(HRABBITVM v,int64_t idx)
{ {
SQObject &o=stack_get(v,idx); SQObject &o=stack_get(v,idx);
if(ISREFCOUNTED(sq_type(o))) { if(ISREFCOUNTED(sq_type(o))) {
v->Push(_refcounted(o)->GetWeakRef(sq_type(o))); v->Push(_refcounted(o)->getWeakRef(sq_type(o)));
return; return;
} }
v->Push(o); v->Push(o);

View File

@ -1,97 +0,0 @@
/**
* @author Alberto DEMICHELIS
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @copyright 2003-2017, Alberto DEMICHELIS, all right reserved
* @license MPL-2 (see license file)
*/
#pragma once
struct SQArray : public SQRefCounted
{
private:
SQArray(SQSharedState *ss,int64_t nsize) {
_values.resize(nsize);
}
~SQArray()
{
}
public:
static SQArray* Create(SQSharedState *ss,int64_t nInitialSize){
SQArray *newarray=(SQArray*)SQ_MALLOC(sizeof(SQArray));
new (newarray) SQArray(ss,nInitialSize);
return newarray;
}
void Finalize(){
_values.resize(0);
}
bool Get(const int64_t nidx,SQObjectPtr &val)
{
if(nidx>=0 && nidx<(int64_t)_values.size()){
SQObjectPtr &o = _values[nidx];
val = _realval(o);
return true;
}
else return false;
}
bool Set(const int64_t nidx,const SQObjectPtr &val)
{
if(nidx>=0 && nidx<(int64_t)_values.size()){
_values[nidx]=val;
return true;
}
else return false;
}
int64_t Next(const SQObjectPtr &refpos,SQObjectPtr &outkey,SQObjectPtr &outval)
{
uint64_t idx=TranslateIndex(refpos);
while(idx<_values.size()){
//first found
outkey=(int64_t)idx;
SQObjectPtr &o = _values[idx];
outval = _realval(o);
//return idx for the next iteration
return ++idx;
}
//nothing to iterate anymore
return -1;
}
SQArray *Clone(){SQArray *anew=Create(NULL,0); anew->_values.copy(_values); return anew; }
int64_t Size() const {return _values.size();}
void Resize(int64_t size)
{
SQObjectPtr _null;
Resize(size,_null);
}
void Resize(int64_t size,SQObjectPtr &fill) { _values.resize(size,fill); ShrinkIfNeeded(); }
void Reserve(int64_t size) { _values.reserve(size); }
void Append(const SQObject &o){_values.push_back(o);}
void Extend(const SQArray *a);
SQObjectPtr &Top(){return _values.top();}
void Pop(){_values.pop_back(); ShrinkIfNeeded(); }
bool Insert(int64_t idx,const SQObject &val){
if(idx < 0 || idx > (int64_t)_values.size())
return false;
_values.insert(idx,val);
return true;
}
void ShrinkIfNeeded() {
if(_values.size() <= _values.capacity()>>2) //shrink the array
_values.shrinktofit();
}
bool Remove(int64_t idx){
if(idx < 0 || idx >= (int64_t)_values.size())
return false;
_values.remove(idx);
ShrinkIfNeeded();
return true;
}
void Release()
{
sq_delete(this,SQArray);
}
SQObjectPtrVec _values;
};

View File

@ -9,7 +9,7 @@
#include <rabbit/sqvm.hpp> #include <rabbit/sqvm.hpp>
#include <rabbit/sqstring.hpp> #include <rabbit/sqstring.hpp>
#include <rabbit/sqtable.hpp> #include <rabbit/sqtable.hpp>
#include <rabbit/sqarray.hpp> #include <rabbit/Array.hpp>
#include <rabbit/sqfuncproto.hpp> #include <rabbit/sqfuncproto.hpp>
#include <rabbit/sqclosure.hpp> #include <rabbit/sqclosure.hpp>
#include <rabbit/sqclass.hpp> #include <rabbit/sqclass.hpp>
@ -241,14 +241,14 @@ static int64_t base_suspend(HRABBITVM v)
static int64_t base_array(HRABBITVM v) static int64_t base_array(HRABBITVM v)
{ {
SQArray *a; rabbit::Array *a;
SQObject &size = stack_get(v,2); SQObject &size = stack_get(v,2);
if(sq_gettop(v) > 2) { if(sq_gettop(v) > 2) {
a = SQArray::Create(_ss(v),0); a = rabbit::Array::create(_ss(v),0);
a->Resize(tointeger(size),stack_get(v,3)); a->resize(tointeger(size),stack_get(v,3));
} }
else { else {
a = SQArray::Create(_ss(v),tointeger(size)); a = rabbit::Array::create(_ss(v),tointeger(size));
} }
v->Push(a); v->Push(a);
return 1; return 1;
@ -257,7 +257,7 @@ static int64_t base_array(HRABBITVM v)
static int64_t base_type(HRABBITVM v) static int64_t base_type(HRABBITVM v)
{ {
SQObjectPtr &o = stack_get(v,2); SQObjectPtr &o = stack_get(v,2);
v->Push(SQString::Create(_ss(v),GetTypeName(o),-1)); v->Push(SQString::create(_ss(v),getTypeName(o),-1));
return 1; return 1;
} }
@ -408,7 +408,7 @@ static int64_t number_delegate_tochar(HRABBITVM v)
{ {
SQObject &o=stack_get(v,1); SQObject &o=stack_get(v,1);
SQChar c = (SQChar)tointeger(o); SQChar c = (SQChar)tointeger(o);
v->Push(SQString::Create(_ss(v),(const SQChar *)&c,1)); v->Push(SQString::create(_ss(v),(const SQChar *)&c,1));
return 1; return 1;
} }
@ -463,11 +463,11 @@ static int64_t table_filter(HRABBITVM v)
{ {
SQObject &o = stack_get(v,1); SQObject &o = stack_get(v,1);
SQTable *tbl = _table(o); SQTable *tbl = _table(o);
SQObjectPtr ret = SQTable::Create(_ss(v),0); SQObjectPtr ret = SQTable::create(_ss(v),0);
SQObjectPtr itr, key, val; SQObjectPtr itr, key, val;
int64_t nitr; int64_t nitr;
while((nitr = tbl->Next(false, itr, key, val)) != -1) { while((nitr = tbl->next(false, itr, key, val)) != -1) {
itr = (int64_t)nitr; itr = (int64_t)nitr;
v->Push(o); v->Push(o);
@ -476,7 +476,7 @@ static int64_t table_filter(HRABBITVM v)
if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) { if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) {
return SQ_ERROR; return SQ_ERROR;
} }
if(!SQVM::IsFalse(v->GetUp(-1))) { if(!SQVM::IsFalse(v->getUp(-1))) {
_table(ret)->NewSlot(key, val); _table(ret)->NewSlot(key, val);
} }
v->Pop(); v->Pop();
@ -511,7 +511,7 @@ static int64_t array_append(HRABBITVM v)
static int64_t array_extend(HRABBITVM v) static int64_t array_extend(HRABBITVM v)
{ {
_array(stack_get(v,1))->Extend(_array(stack_get(v,2))); _array(stack_get(v,1))->extend(_array(stack_get(v,2)));
sq_pop(v,1); sq_pop(v,1);
return 1; return 1;
} }
@ -529,8 +529,8 @@ static int64_t array_pop(HRABBITVM v)
static int64_t array_top(HRABBITVM v) static int64_t array_top(HRABBITVM v)
{ {
SQObject &o=stack_get(v,1); SQObject &o=stack_get(v,1);
if(_array(o)->Size()>0){ if(_array(o)->size()>0){
v->Push(_array(o)->Top()); v->Push(_array(o)->top());
return 1; return 1;
} }
else return sq_throwerror(v,_SC("top() on a empty array")); else return sq_throwerror(v,_SC("top() on a empty array"));
@ -541,7 +541,7 @@ static int64_t array_insert(HRABBITVM v)
SQObject &o=stack_get(v,1); SQObject &o=stack_get(v,1);
SQObject &idx=stack_get(v,2); SQObject &idx=stack_get(v,2);
SQObject &val=stack_get(v,3); SQObject &val=stack_get(v,3);
if(!_array(o)->Insert(tointeger(idx),val)) if(!_array(o)->insert(tointeger(idx),val))
return sq_throwerror(v,_SC("index out of range")); return sq_throwerror(v,_SC("index out of range"));
sq_pop(v,2); sq_pop(v,2);
return 1; return 1;
@ -553,8 +553,8 @@ static int64_t array_remove(HRABBITVM v)
SQObject &idx = stack_get(v, 2); SQObject &idx = stack_get(v, 2);
if(!sq_isnumeric(idx)) return sq_throwerror(v, _SC("wrong type")); if(!sq_isnumeric(idx)) return sq_throwerror(v, _SC("wrong type"));
SQObjectPtr val; SQObjectPtr val;
if(_array(o)->Get(tointeger(idx), val)) { if(_array(o)->get(tointeger(idx), val)) {
_array(o)->Remove(tointeger(idx)); _array(o)->remove(tointeger(idx));
v->Push(val); v->Push(val);
return 1; return 1;
} }
@ -573,24 +573,24 @@ static int64_t array_resize(HRABBITVM v)
if(sq_gettop(v) > 2) if(sq_gettop(v) > 2)
fill = stack_get(v, 3); fill = stack_get(v, 3);
_array(o)->Resize(sz,fill); _array(o)->resize(sz,fill);
sq_settop(v, 1); sq_settop(v, 1);
return 1; return 1;
} }
return sq_throwerror(v, _SC("size must be a number")); return sq_throwerror(v, _SC("size must be a number"));
} }
static int64_t __map_array(SQArray *dest,SQArray *src,HRABBITVM v) { static int64_t __map_array(rabbit::Array *dest,rabbit::Array *src,HRABBITVM v) {
SQObjectPtr temp; SQObjectPtr temp;
int64_t size = src->Size(); int64_t size = src->size();
for(int64_t n = 0; n < size; n++) { for(int64_t n = 0; n < size; n++) {
src->Get(n,temp); src->get(n,temp);
v->Push(src); v->Push(src);
v->Push(temp); v->Push(temp);
if(SQ_FAILED(sq_call(v,2,SQTrue,SQFalse))) { if(SQ_FAILED(sq_call(v,2,SQTrue,SQFalse))) {
return SQ_ERROR; return SQ_ERROR;
} }
dest->Set(n,v->GetUp(-1)); dest->set(n,v->getUp(-1));
v->Pop(); v->Pop();
} }
return 0; return 0;
@ -599,8 +599,8 @@ static int64_t __map_array(SQArray *dest,SQArray *src,HRABBITVM v) {
static int64_t array_map(HRABBITVM v) static int64_t array_map(HRABBITVM v)
{ {
SQObject &o = stack_get(v,1); SQObject &o = stack_get(v,1);
int64_t size = _array(o)->Size(); int64_t size = _array(o)->size();
SQObjectPtr ret = SQArray::Create(_ss(v),size); SQObjectPtr ret = rabbit::Array::create(_ss(v),size);
if(SQ_FAILED(__map_array(_array(ret),_array(o),v))) if(SQ_FAILED(__map_array(_array(ret),_array(o),v)))
return SQ_ERROR; return SQ_ERROR;
v->Push(ret); v->Push(ret);
@ -619,24 +619,24 @@ static int64_t array_apply(HRABBITVM v)
static int64_t array_reduce(HRABBITVM v) static int64_t array_reduce(HRABBITVM v)
{ {
SQObject &o = stack_get(v,1); SQObject &o = stack_get(v,1);
SQArray *a = _array(o); rabbit::Array *a = _array(o);
int64_t size = a->Size(); int64_t size = a->size();
if(size == 0) { if(size == 0) {
return 0; return 0;
} }
SQObjectPtr res; SQObjectPtr res;
a->Get(0,res); a->get(0,res);
if(size > 1) { if(size > 1) {
SQObjectPtr other; SQObjectPtr other;
for(int64_t n = 1; n < size; n++) { for(int64_t n = 1; n < size; n++) {
a->Get(n,other); a->get(n,other);
v->Push(o); v->Push(o);
v->Push(res); v->Push(res);
v->Push(other); v->Push(other);
if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) { if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) {
return SQ_ERROR; return SQ_ERROR;
} }
res = v->GetUp(-1); res = v->getUp(-1);
v->Pop(); v->Pop();
} }
} }
@ -647,20 +647,20 @@ static int64_t array_reduce(HRABBITVM v)
static int64_t array_filter(HRABBITVM v) static int64_t array_filter(HRABBITVM v)
{ {
SQObject &o = stack_get(v,1); SQObject &o = stack_get(v,1);
SQArray *a = _array(o); rabbit::Array *a = _array(o);
SQObjectPtr ret = SQArray::Create(_ss(v),0); SQObjectPtr ret = rabbit::Array::create(_ss(v),0);
int64_t size = a->Size(); int64_t size = a->size();
SQObjectPtr val; SQObjectPtr val;
for(int64_t n = 0; n < size; n++) { for(int64_t n = 0; n < size; n++) {
a->Get(n,val); a->get(n,val);
v->Push(o); v->Push(o);
v->Push(n); v->Push(n);
v->Push(val); v->Push(val);
if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) { if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) {
return SQ_ERROR; return SQ_ERROR;
} }
if(!SQVM::IsFalse(v->GetUp(-1))) { if(!SQVM::IsFalse(v->getUp(-1))) {
_array(ret)->Append(val); _array(ret)->append(val);
} }
v->Pop(); v->Pop();
} }
@ -672,12 +672,12 @@ static int64_t array_find(HRABBITVM v)
{ {
SQObject &o = stack_get(v,1); SQObject &o = stack_get(v,1);
SQObjectPtr &val = stack_get(v,2); SQObjectPtr &val = stack_get(v,2);
SQArray *a = _array(o); rabbit::Array *a = _array(o);
int64_t size = a->Size(); int64_t size = a->size();
SQObjectPtr temp; SQObjectPtr temp;
for(int64_t n = 0; n < size; n++) { for(int64_t n = 0; n < size; n++) {
bool res = false; bool res = false;
a->Get(n,temp); a->get(n,temp);
if(SQVM::IsEqual(temp,val,res) && res) { if(SQVM::IsEqual(temp,val,res) && res) {
v->Push(n); v->Push(n);
return 1; return 1;
@ -713,7 +713,7 @@ static bool _sort_compare(HRABBITVM v,SQObjectPtr &a,SQObjectPtr &b,int64_t func
return true; return true;
} }
static bool _hsort_sift_down(HRABBITVM v,SQArray *arr, int64_t root, int64_t bottom, int64_t func) static bool _hsort_sift_down(HRABBITVM v,rabbit::Array *arr, int64_t root, int64_t bottom, int64_t func)
{ {
int64_t maxChild; int64_t maxChild;
int64_t done = 0; int64_t done = 0;
@ -725,7 +725,7 @@ static bool _hsort_sift_down(HRABBITVM v,SQArray *arr, int64_t root, int64_t bot
maxChild = root2; maxChild = root2;
} }
else { else {
if(!_sort_compare(v,arr->_values[root2],arr->_values[root2 + 1],func,ret)) if(!_sort_compare(v,(*arr)[root2],(*arr)[root2 + 1],func,ret))
return false; return false;
if (ret > 0) { if (ret > 0) {
maxChild = root2; maxChild = root2;
@ -735,7 +735,7 @@ static bool _hsort_sift_down(HRABBITVM v,SQArray *arr, int64_t root, int64_t bot
} }
} }
if(!_sort_compare(v,arr->_values[root],arr->_values[maxChild],func,ret)) if(!_sort_compare(v,(*arr)[root],(*arr)[maxChild],func,ret))
return false; return false;
if (ret < 0) { if (ret < 0) {
if (root == maxChild) { if (root == maxChild) {
@ -743,7 +743,7 @@ static bool _hsort_sift_down(HRABBITVM v,SQArray *arr, int64_t root, int64_t bot
return false; // We'd be swapping ourselve. The compare function is incorrect return false; // We'd be swapping ourselve. The compare function is incorrect
} }
_Swap(arr->_values[root],arr->_values[maxChild]); _Swap((*arr)[root], (*arr)[maxChild]);
root = maxChild; root = maxChild;
} }
else { else {
@ -755,16 +755,16 @@ static bool _hsort_sift_down(HRABBITVM v,SQArray *arr, int64_t root, int64_t bot
static bool _hsort(HRABBITVM v,SQObjectPtr &arr, int64_t SQ_UNUSED_ARG(l), int64_t SQ_UNUSED_ARG(r),int64_t func) static bool _hsort(HRABBITVM v,SQObjectPtr &arr, int64_t SQ_UNUSED_ARG(l), int64_t SQ_UNUSED_ARG(r),int64_t func)
{ {
SQArray *a = _array(arr); rabbit::Array *a = _array(arr);
int64_t i; int64_t i;
int64_t array_size = a->Size(); int64_t array_size = a->size();
for (i = (array_size / 2); i >= 0; i--) { for (i = (array_size / 2); i >= 0; i--) {
if(!_hsort_sift_down(v,a, i, array_size - 1,func)) return false; if(!_hsort_sift_down(v,a, i, array_size - 1,func)) return false;
} }
for (i = array_size-1; i >= 1; i--) for (i = array_size-1; i >= 1; i--)
{ {
_Swap(a->_values[0],a->_values[i]); _Swap((*a)[0],(*a)[i]);
if(!_hsort_sift_down(v,a, 0, i-1,func)) return false; if(!_hsort_sift_down(v,a, 0, i-1,func)) return false;
} }
return true; return true;
@ -774,9 +774,9 @@ static int64_t array_sort(HRABBITVM v)
{ {
int64_t func = -1; int64_t func = -1;
SQObjectPtr &o = stack_get(v,1); SQObjectPtr &o = stack_get(v,1);
if(_array(o)->Size() > 1) { if(_array(o)->size() > 1) {
if(sq_gettop(v) == 2) func = 2; if(sq_gettop(v) == 2) func = 2;
if(!_hsort(v, o, 0, _array(o)->Size()-1, func)) if(!_hsort(v, o, 0, _array(o)->size()-1, func))
return SQ_ERROR; return SQ_ERROR;
} }
@ -789,17 +789,17 @@ static int64_t array_slice(HRABBITVM v)
int64_t sidx,eidx; int64_t sidx,eidx;
SQObjectPtr o; SQObjectPtr o;
if(get_slice_params(v,sidx,eidx,o)==-1)return -1; if(get_slice_params(v,sidx,eidx,o)==-1)return -1;
int64_t alen = _array(o)->Size(); int64_t alen = _array(o)->size();
if(sidx < 0)sidx = alen + sidx; if(sidx < 0)sidx = alen + sidx;
if(eidx < 0)eidx = alen + eidx; if(eidx < 0)eidx = alen + eidx;
if(eidx < sidx)return sq_throwerror(v,_SC("wrong indexes")); if(eidx < sidx)return sq_throwerror(v,_SC("wrong indexes"));
if(eidx > alen || sidx < 0)return sq_throwerror(v, _SC("slice out of range")); if(eidx > alen || sidx < 0)return sq_throwerror(v, _SC("slice out of range"));
SQArray *arr=SQArray::Create(_ss(v),eidx-sidx); rabbit::Array *arr=rabbit::Array::create(_ss(v),eidx-sidx);
SQObjectPtr t; SQObjectPtr t;
int64_t count=0; int64_t count=0;
for(int64_t i=sidx;i<eidx;i++){ for(int64_t i=sidx;i<eidx;i++){
_array(o)->Get(i,t); _array(o)->get(i,t);
arr->Set(count++,t); arr->set(count++,t);
} }
v->Push(arr); v->Push(arr);
return 1; return 1;
@ -841,7 +841,7 @@ static int64_t string_slice(HRABBITVM v)
if(eidx < 0)eidx = slen + eidx; if(eidx < 0)eidx = slen + eidx;
if(eidx < sidx) return sq_throwerror(v,_SC("wrong indexes")); if(eidx < sidx) return sq_throwerror(v,_SC("wrong indexes"));
if(eidx > slen || sidx < 0) return sq_throwerror(v, _SC("slice out of range")); if(eidx > slen || sidx < 0) return sq_throwerror(v, _SC("slice out of range"));
v->Push(SQString::Create(_ss(v),&_stringval(o)[sidx],eidx-sidx)); v->Push(SQString::create(_ss(v),&_stringval(o)[sidx],eidx-sidx));
return 1; return 1;
} }
@ -875,10 +875,10 @@ static int64_t string_find(HRABBITVM v)
if(eidx > slen || sidx < 0) return sq_throwerror(v,_SC("slice out of range")); \ if(eidx > slen || sidx < 0) return sq_throwerror(v,_SC("slice out of range")); \
int64_t len=_string(str)->_len; \ int64_t len=_string(str)->_len; \
const SQChar *sthis=_stringval(str); \ const SQChar *sthis=_stringval(str); \
SQChar *snew=(_ss(v)->GetScratchPad(sq_rsl(len))); \ SQChar *snew=(_ss(v)->getScratchPad(sq_rsl(len))); \
memcpy(snew,sthis,sq_rsl(len));\ memcpy(snew,sthis,sq_rsl(len));\
for(int64_t i=sidx;i<eidx;i++) snew[i] = func(sthis[i]); \ for(int64_t i=sidx;i<eidx;i++) snew[i] = func(sthis[i]); \
v->Push(SQString::Create(_ss(v),snew,len)); \ v->Push(SQString::create(_ss(v),snew,len)); \
return 1; \ return 1; \
} }
@ -927,10 +927,10 @@ static int64_t closure_call(HRABBITVM v)
static int64_t _closure_acall(HRABBITVM v,SQBool raiseerror) static int64_t _closure_acall(HRABBITVM v,SQBool raiseerror)
{ {
SQArray *aparams=_array(stack_get(v,2)); rabbit::Array *aparams=_array(stack_get(v,2));
int64_t nparams=aparams->Size(); int64_t nparams=aparams->size();
v->Push(stack_get(v,1)); v->Push(stack_get(v,1));
for(int64_t i=0;i<nparams;i++)v->Push(aparams->_values[i]); for(int64_t i=0;i<nparams;i++)v->Push((*aparams)[i]);
return SQ_SUCCEEDED(sq_call(v,nparams,SQTrue,raiseerror))?1:SQ_ERROR; return SQ_SUCCEEDED(sq_call(v,nparams,SQTrue,raiseerror))?1:SQ_ERROR;
} }
@ -967,42 +967,42 @@ static int64_t closure_setroot(HRABBITVM v)
static int64_t closure_getinfos(HRABBITVM v) { static int64_t closure_getinfos(HRABBITVM v) {
SQObject o = stack_get(v,1); SQObject o = stack_get(v,1);
SQTable *res = SQTable::Create(_ss(v),4); SQTable *res = SQTable::create(_ss(v),4);
if(sq_type(o) == OT_CLOSURE) { if(sq_type(o) == OT_CLOSURE) {
SQFunctionProto *f = _closure(o)->_function; SQFunctionProto *f = _closure(o)->_function;
int64_t nparams = f->_nparameters + (f->_varparams?1:0); int64_t nparams = f->_nparameters + (f->_varparams?1:0);
SQObjectPtr params = SQArray::Create(_ss(v),nparams); SQObjectPtr params = rabbit::Array::create(_ss(v),nparams);
SQObjectPtr defparams = SQArray::Create(_ss(v),f->_ndefaultparams); SQObjectPtr defparams = rabbit::Array::create(_ss(v),f->_ndefaultparams);
for(int64_t n = 0; n<f->_nparameters; n++) { for(int64_t n = 0; n<f->_nparameters; n++) {
_array(params)->Set((int64_t)n,f->_parameters[n]); _array(params)->set((int64_t)n,f->_parameters[n]);
} }
for(int64_t j = 0; j<f->_ndefaultparams; j++) { for(int64_t j = 0; j<f->_ndefaultparams; j++) {
_array(defparams)->Set((int64_t)j,_closure(o)->_defaultparams[j]); _array(defparams)->set((int64_t)j,_closure(o)->_defaultparams[j]);
} }
if(f->_varparams) { if(f->_varparams) {
_array(params)->Set(nparams-1,SQString::Create(_ss(v),_SC("..."),-1)); _array(params)->set(nparams-1,SQString::create(_ss(v),_SC("..."),-1));
} }
res->NewSlot(SQString::Create(_ss(v),_SC("native"),-1),false); res->NewSlot(SQString::create(_ss(v),_SC("native"),-1),false);
res->NewSlot(SQString::Create(_ss(v),_SC("name"),-1),f->_name); res->NewSlot(SQString::create(_ss(v),_SC("name"),-1),f->_name);
res->NewSlot(SQString::Create(_ss(v),_SC("src"),-1),f->_sourcename); res->NewSlot(SQString::create(_ss(v),_SC("src"),-1),f->_sourcename);
res->NewSlot(SQString::Create(_ss(v),_SC("parameters"),-1),params); res->NewSlot(SQString::create(_ss(v),_SC("parameters"),-1),params);
res->NewSlot(SQString::Create(_ss(v),_SC("varargs"),-1),f->_varparams); res->NewSlot(SQString::create(_ss(v),_SC("varargs"),-1),f->_varparams);
res->NewSlot(SQString::Create(_ss(v),_SC("defparams"),-1),defparams); res->NewSlot(SQString::create(_ss(v),_SC("defparams"),-1),defparams);
} }
else { //OT_NATIVECLOSURE else { //OT_NATIVECLOSURE
SQNativeClosure *nc = _nativeclosure(o); SQNativeClosure *nc = _nativeclosure(o);
res->NewSlot(SQString::Create(_ss(v),_SC("native"),-1),true); res->NewSlot(SQString::create(_ss(v),_SC("native"),-1),true);
res->NewSlot(SQString::Create(_ss(v),_SC("name"),-1),nc->_name); res->NewSlot(SQString::create(_ss(v),_SC("name"),-1),nc->_name);
res->NewSlot(SQString::Create(_ss(v),_SC("paramscheck"),-1),nc->_nparamscheck); res->NewSlot(SQString::create(_ss(v),_SC("paramscheck"),-1),nc->_nparamscheck);
SQObjectPtr typecheck; SQObjectPtr typecheck;
if(nc->_typecheck.size() > 0) { if(nc->_typecheck.size() > 0) {
typecheck = typecheck =
SQArray::Create(_ss(v), nc->_typecheck.size()); rabbit::Array::create(_ss(v), nc->_typecheck.size());
for(uint64_t n = 0; n<nc->_typecheck.size(); n++) { for(uint64_t n = 0; n<nc->_typecheck.size(); n++) {
_array(typecheck)->Set((int64_t)n,nc->_typecheck[n]); _array(typecheck)->set((int64_t)n,nc->_typecheck[n]);
} }
} }
res->NewSlot(SQString::Create(_ss(v),_SC("typecheck"),-1),typecheck); res->NewSlot(SQString::create(_ss(v),_SC("typecheck"),-1),typecheck);
} }
v->Push(res); v->Push(res);
return 1; return 1;
@ -1029,9 +1029,9 @@ static int64_t generator_getstatus(HRABBITVM v)
{ {
SQObject &o=stack_get(v,1); SQObject &o=stack_get(v,1);
switch(_generator(o)->_state){ switch(_generator(o)->_state){
case SQGenerator::eSuspended:v->Push(SQString::Create(_ss(v),_SC("suspended")));break; case SQGenerator::eSuspended:v->Push(SQString::create(_ss(v),_SC("suspended")));break;
case SQGenerator::eRunning:v->Push(SQString::Create(_ss(v),_SC("running")));break; case SQGenerator::eRunning:v->Push(SQString::create(_ss(v),_SC("running")));break;
case SQGenerator::eDead:v->Push(SQString::Create(_ss(v),_SC("dead")));break; case SQGenerator::eDead:v->Push(SQString::create(_ss(v),_SC("dead")));break;
} }
return 1; return 1;
} }

View File

@ -30,7 +30,7 @@ SQClass::SQClass(SQSharedState *ss,SQClass *base)
_COPY_VECTOR(_metamethods,base->_metamethods,MT_LAST); _COPY_VECTOR(_metamethods,base->_metamethods,MT_LAST);
__ObjAddRef(_base); __ObjAddRef(_base);
} }
_members = base?base->_members->Clone() : SQTable::Create(ss,0); _members = base?base->_members->clone() : SQTable::create(ss,0);
__ObjAddRef(_members); __ObjAddRef(_members);
} }
@ -39,9 +39,9 @@ void SQClass::Finalize() {
_NULL_SQOBJECT_VECTOR(_defaultvalues,_defaultvalues.size()); _NULL_SQOBJECT_VECTOR(_defaultvalues,_defaultvalues.size());
_methods.resize(0); _methods.resize(0);
_NULL_SQOBJECT_VECTOR(_metamethods,MT_LAST); _NULL_SQOBJECT_VECTOR(_metamethods,MT_LAST);
__ObjRelease(_members); __Objrelease(_members);
if(_base) { if(_base) {
__ObjRelease(_base); __Objrelease(_base);
} }
} }
@ -56,7 +56,7 @@ bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr
bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic; bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;
if(_locked && !belongs_to_static_table) if(_locked && !belongs_to_static_table)
return false; //the class already has an instance so cannot be modified return false; //the class already has an instance so cannot be modified
if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value if(_members->get(key,temp) && _isfield(temp)) //overrides the default value
{ {
_defaultvalues[_member_idx(temp)].val = val; _defaultvalues[_member_idx(temp)].val = val;
return true; return true;
@ -64,13 +64,13 @@ bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr
if(belongs_to_static_table) { if(belongs_to_static_table) {
int64_t mmidx; int64_t mmidx;
if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) && if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&
(mmidx = ss->GetMetaMethodIdxByName(key)) != -1) { (mmidx = ss->getMetaMethodIdxByName(key)) != -1) {
_metamethods[mmidx] = val; _metamethods[mmidx] = val;
} }
else { else {
SQObjectPtr theval = val; SQObjectPtr theval = val;
if(_base && sq_type(val) == OT_CLOSURE) { if(_base && sq_type(val) == OT_CLOSURE) {
theval = _closure(val)->Clone(); theval = _closure(val)->clone();
_closure(theval)->_base = _base; _closure(theval)->_base = _base;
__ObjAddRef(_base); //ref for the closure __ObjAddRef(_base); //ref for the closure
} }
@ -98,16 +98,16 @@ bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr
return true; return true;
} }
SQInstance *SQClass::CreateInstance() SQInstance *SQClass::createInstance()
{ {
if(!_locked) Lock(); if(!_locked) Lock();
return SQInstance::Create(NULL,this); return SQInstance::create(NULL,this);
} }
int64_t SQClass::Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval) int64_t SQClass::next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval)
{ {
SQObjectPtr oval; SQObjectPtr oval;
int64_t idx = _members->Next(false,refpos,outkey,oval); int64_t idx = _members->next(false,refpos,outkey,oval);
if(idx != -1) { if(idx != -1) {
if(_ismethod(oval)) { if(_ismethod(oval)) {
outval = _methods[_member_idx(oval)].val; outval = _methods[_member_idx(oval)].val;
@ -120,10 +120,10 @@ int64_t SQClass::Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPt
return idx; return idx;
} }
bool SQClass::SetAttributes(const SQObjectPtr &key,const SQObjectPtr &val) bool SQClass::setAttributes(const SQObjectPtr &key,const SQObjectPtr &val)
{ {
SQObjectPtr idx; SQObjectPtr idx;
if(_members->Get(key,idx)) { if(_members->get(key,idx)) {
if(_isfield(idx)) if(_isfield(idx))
_defaultvalues[_member_idx(idx)].attrs = val; _defaultvalues[_member_idx(idx)].attrs = val;
else else
@ -133,10 +133,10 @@ bool SQClass::SetAttributes(const SQObjectPtr &key,const SQObjectPtr &val)
return false; return false;
} }
bool SQClass::GetAttributes(const SQObjectPtr &key,SQObjectPtr &outval) bool SQClass::getAttributes(const SQObjectPtr &key,SQObjectPtr &outval)
{ {
SQObjectPtr idx; SQObjectPtr idx;
if(_members->Get(key,idx)) { if(_members->get(key,idx)) {
outval = (_isfield(idx)?_defaultvalues[_member_idx(idx)].attrs:_methods[_member_idx(idx)].attrs); outval = (_isfield(idx)?_defaultvalues[_member_idx(idx)].attrs:_methods[_member_idx(idx)].attrs);
return true; return true;
} }
@ -177,7 +177,7 @@ SQInstance::SQInstance(SQSharedState *ss, SQInstance *i, int64_t memsize)
void SQInstance::Finalize() void SQInstance::Finalize()
{ {
uint64_t nvalues = _class->_defaultvalues.size(); uint64_t nvalues = _class->_defaultvalues.size();
__ObjRelease(_class); __Objrelease(_class);
_NULL_SQOBJECT_VECTOR(_values,nvalues); _NULL_SQOBJECT_VECTOR(_values,nvalues);
} }
@ -186,7 +186,7 @@ SQInstance::~SQInstance()
if(_class){ Finalize(); } //if _class is null it was already finalized by the GC if(_class){ Finalize(); } //if _class is null it was already finalized by the GC
} }
bool SQInstance::GetMetaMethod(SQVM* SQ_UNUSED_ARG(v),SQMetaMethod mm,SQObjectPtr &res) bool SQInstance::getMetaMethod(SQVM* SQ_UNUSED_ARG(v),SQMetaMethod mm,SQObjectPtr &res)
{ {
if(sq_type(_class->_metamethods[mm]) != OT_NULL) { if(sq_type(_class->_metamethods[mm]) != OT_NULL) {
res = _class->_metamethods[mm]; res = _class->_metamethods[mm];

View File

@ -30,19 +30,19 @@ typedef sqvector<SQClassMember> SQClassMemberVec;
#define _member_type(o) (_integer(o)&0xFF000000) #define _member_type(o) (_integer(o)&0xFF000000)
#define _member_idx(o) (_integer(o)&0x00FFFFFF) #define _member_idx(o) (_integer(o)&0x00FFFFFF)
struct SQClass : public SQRefCounted struct SQClass : public rabbit::RefCounted
{ {
SQClass(SQSharedState *ss,SQClass *base); SQClass(SQSharedState *ss,SQClass *base);
public: public:
static SQClass* Create(SQSharedState *ss,SQClass *base) { static SQClass* create(SQSharedState *ss,SQClass *base) {
SQClass *newclass = (SQClass *)SQ_MALLOC(sizeof(SQClass)); SQClass *newclass = (SQClass *)SQ_MALLOC(sizeof(SQClass));
new (newclass) SQClass(ss, base); new (newclass) SQClass(ss, base);
return newclass; return newclass;
} }
~SQClass(); ~SQClass();
bool NewSlot(SQSharedState *ss, const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic); bool NewSlot(SQSharedState *ss, const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic);
bool Get(const SQObjectPtr &key,SQObjectPtr &val) { bool get(const SQObjectPtr &key,SQObjectPtr &val) {
if(_members->Get(key,val)) { if(_members->get(key,val)) {
if(_isfield(val)) { if(_isfield(val)) {
SQObjectPtr &o = _defaultvalues[_member_idx(val)].val; SQObjectPtr &o = _defaultvalues[_member_idx(val)].val;
val = _realval(o); val = _realval(o);
@ -54,7 +54,7 @@ public:
} }
return false; return false;
} }
bool GetConstructor(SQObjectPtr &ctor) bool getConstructor(SQObjectPtr &ctor)
{ {
if(_constructoridx != -1) { if(_constructoridx != -1) {
ctor = _methods[_constructoridx].val; ctor = _methods[_constructoridx].val;
@ -62,16 +62,16 @@ public:
} }
return false; return false;
} }
bool SetAttributes(const SQObjectPtr &key,const SQObjectPtr &val); bool setAttributes(const SQObjectPtr &key,const SQObjectPtr &val);
bool GetAttributes(const SQObjectPtr &key,SQObjectPtr &outval); bool getAttributes(const SQObjectPtr &key,SQObjectPtr &outval);
void Lock() { _locked = true; if(_base) _base->Lock(); } void Lock() { _locked = true; if(_base) _base->Lock(); }
void Release() { void release() {
if (_hook) { _hook(_typetag,0);} if (_hook) { _hook(_typetag,0);}
sq_delete(this, SQClass); sq_delete(this, SQClass);
} }
void Finalize(); void Finalize();
int64_t Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval); int64_t next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval);
SQInstance *CreateInstance(); SQInstance *createInstance();
SQTable *_members; SQTable *_members;
SQClass *_base; SQClass *_base;
SQClassMemberVec _defaultvalues; SQClassMemberVec _defaultvalues;
@ -94,7 +94,7 @@ struct SQInstance : public SQDelegable
SQInstance(SQSharedState *ss, SQClass *c, int64_t memsize); SQInstance(SQSharedState *ss, SQClass *c, int64_t memsize);
SQInstance(SQSharedState *ss, SQInstance *c, int64_t memsize); SQInstance(SQSharedState *ss, SQInstance *c, int64_t memsize);
public: public:
static SQInstance* Create(SQSharedState *ss,SQClass *theclass) { static SQInstance* create(SQSharedState *ss,SQClass *theclass) {
int64_t size = calcinstancesize(theclass); int64_t size = calcinstancesize(theclass);
SQInstance *newinst = (SQInstance *)SQ_MALLOC(size); SQInstance *newinst = (SQInstance *)SQ_MALLOC(size);
@ -104,7 +104,7 @@ public:
} }
return newinst; return newinst;
} }
SQInstance *Clone(SQSharedState *ss) SQInstance *clone(SQSharedState *ss)
{ {
int64_t size = calcinstancesize(_class); int64_t size = calcinstancesize(_class);
SQInstance *newinst = (SQInstance *)SQ_MALLOC(size); SQInstance *newinst = (SQInstance *)SQ_MALLOC(size);
@ -115,8 +115,8 @@ public:
return newinst; return newinst;
} }
~SQInstance(); ~SQInstance();
bool Get(const SQObjectPtr &key,SQObjectPtr &val) { bool get(const SQObjectPtr &key,SQObjectPtr &val) {
if(_class->_members->Get(key,val)) { if(_class->_members->get(key,val)) {
if(_isfield(val)) { if(_isfield(val)) {
SQObjectPtr &o = _values[_member_idx(val)]; SQObjectPtr &o = _values[_member_idx(val)];
val = _realval(o); val = _realval(o);
@ -128,15 +128,15 @@ public:
} }
return false; return false;
} }
bool Set(const SQObjectPtr &key,const SQObjectPtr &val) { bool set(const SQObjectPtr &key,const SQObjectPtr &val) {
SQObjectPtr idx; SQObjectPtr idx;
if(_class->_members->Get(key,idx) && _isfield(idx)) { if(_class->_members->get(key,idx) && _isfield(idx)) {
_values[_member_idx(idx)] = val; _values[_member_idx(idx)] = val;
return true; return true;
} }
return false; return false;
} }
void Release() { void release() {
_uiRef++; _uiRef++;
if (_hook) { _hook(_userpointer,0);} if (_hook) { _hook(_userpointer,0);}
_uiRef--; _uiRef--;
@ -147,7 +147,7 @@ public:
} }
void Finalize(); void Finalize();
bool InstanceOf(SQClass *trg); bool InstanceOf(SQClass *trg);
bool GetMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res); bool getMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res);
SQClass *_class; SQClass *_class;
SQUserPointer _userpointer; SQUserPointer _userpointer;

View File

@ -11,7 +11,7 @@
struct SQFunctionProto; struct SQFunctionProto;
struct SQClass; struct SQClass;
struct SQClosure : public SQRefCounted struct SQClosure : public rabbit::RefCounted
{ {
private: private:
SQClosure(SQSharedState *ss,SQFunctionProto *func){ SQClosure(SQSharedState *ss,SQFunctionProto *func){
@ -21,7 +21,7 @@ private:
_root=NULL; _root=NULL;
} }
public: public:
static SQClosure *Create(SQSharedState *ss,SQFunctionProto *func,SQWeakRef *root){ static SQClosure *create(SQSharedState *ss,SQFunctionProto *func,rabbit::WeakRef *root){
int64_t size = _CALC_CLOSURE_SIZE(func); int64_t size = _CALC_CLOSURE_SIZE(func);
SQClosure *nc=(SQClosure*)SQ_MALLOC(size); SQClosure *nc=(SQClosure*)SQ_MALLOC(size);
new (nc) SQClosure(ss,func); new (nc) SQClosure(ss,func);
@ -33,25 +33,25 @@ public:
_CONSTRUCT_VECTOR(SQObjectPtr,func->_ndefaultparams,nc->_defaultparams); _CONSTRUCT_VECTOR(SQObjectPtr,func->_ndefaultparams,nc->_defaultparams);
return nc; return nc;
} }
void Release(){ void release(){
SQFunctionProto *f = _function; SQFunctionProto *f = _function;
int64_t size = _CALC_CLOSURE_SIZE(f); int64_t size = _CALC_CLOSURE_SIZE(f);
_DESTRUCT_VECTOR(SQObjectPtr,f->_noutervalues,_outervalues); _DESTRUCT_VECTOR(SQObjectPtr,f->_noutervalues,_outervalues);
_DESTRUCT_VECTOR(SQObjectPtr,f->_ndefaultparams,_defaultparams); _DESTRUCT_VECTOR(SQObjectPtr,f->_ndefaultparams,_defaultparams);
__ObjRelease(_function); __Objrelease(_function);
this->~SQClosure(); this->~SQClosure();
sq_vm_free(this,size); sq_vm_free(this,size);
} }
void SetRoot(SQWeakRef *r) void setRoot(rabbit::WeakRef *r)
{ {
__ObjRelease(_root); __Objrelease(_root);
_root = r; _root = r;
__ObjAddRef(_root); __ObjAddRef(_root);
} }
SQClosure *Clone() SQClosure *clone()
{ {
SQFunctionProto *f = _function; SQFunctionProto *f = _function;
SQClosure * ret = SQClosure::Create(NULL,f,_root); SQClosure * ret = SQClosure::create(NULL,f,_root);
ret->_env = _env; ret->_env = _env;
if(ret->_env) __ObjAddRef(ret->_env); if(ret->_env) __ObjAddRef(ret->_env);
_COPY_VECTOR(ret->_outervalues,_outervalues,f->_noutervalues); _COPY_VECTOR(ret->_outervalues,_outervalues,f->_noutervalues);
@ -62,8 +62,8 @@ public:
bool Save(SQVM *v,SQUserPointer up,SQWRITEFUNC write); bool Save(SQVM *v,SQUserPointer up,SQWRITEFUNC write);
static bool Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &ret); static bool Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &ret);
SQWeakRef *_env; rabbit::WeakRef *_env;
SQWeakRef *_root; rabbit::WeakRef *_root;
SQClass *_base; SQClass *_base;
SQFunctionProto *_function; SQFunctionProto *_function;
SQObjectPtr *_outervalues; SQObjectPtr *_outervalues;
@ -71,7 +71,7 @@ public:
}; };
////////////////////////////////////////////// //////////////////////////////////////////////
struct SQOuter : public SQRefCounted struct SQOuter : public rabbit::RefCounted
{ {
private: private:
@ -81,7 +81,7 @@ private:
} }
public: public:
static SQOuter *Create(SQSharedState *ss, SQObjectPtr *outer) static SQOuter *create(SQSharedState *ss, SQObjectPtr *outer)
{ {
SQOuter *nc = (SQOuter*)SQ_MALLOC(sizeof(SQOuter)); SQOuter *nc = (SQOuter*)SQ_MALLOC(sizeof(SQOuter));
new (nc) SQOuter(ss, outer); new (nc) SQOuter(ss, outer);
@ -91,7 +91,7 @@ public:
} }
void Release() void release()
{ {
this->~SQOuter(); this->~SQOuter();
sq_vm_free(this,sizeof(SQOuter)); sq_vm_free(this,sizeof(SQOuter));
@ -104,7 +104,7 @@ public:
}; };
////////////////////////////////////////////// //////////////////////////////////////////////
struct SQGenerator : public SQRefCounted struct SQGenerator : public rabbit::RefCounted
{ {
enum SQGeneratorState{eRunning,eSuspended,eDead}; enum SQGeneratorState{eRunning,eSuspended,eDead};
private: private:
@ -114,7 +114,7 @@ private:
_ci._generator=NULL; _ci._generator=NULL;
} }
public: public:
static SQGenerator *Create(SQSharedState *ss,SQClosure *closure){ static SQGenerator *create(SQSharedState *ss,SQClosure *closure){
SQGenerator *nc=(SQGenerator*)SQ_MALLOC(sizeof(SQGenerator)); SQGenerator *nc=(SQGenerator*)SQ_MALLOC(sizeof(SQGenerator));
new (nc) SQGenerator(ss,closure); new (nc) SQGenerator(ss,closure);
return nc; return nc;
@ -127,7 +127,7 @@ public:
_state=eDead; _state=eDead;
_stack.resize(0); _stack.resize(0);
_closure.Null();} _closure.Null();}
void Release(){ void release(){
sq_delete(this,SQGenerator); sq_delete(this,SQGenerator);
} }
@ -142,7 +142,7 @@ public:
#define _CALC_NATVIVECLOSURE_SIZE(noutervalues) (sizeof(SQNativeClosure) + (noutervalues*sizeof(SQObjectPtr))) #define _CALC_NATVIVECLOSURE_SIZE(noutervalues) (sizeof(SQNativeClosure) + (noutervalues*sizeof(SQObjectPtr)))
struct SQNativeClosure : public SQRefCounted struct SQNativeClosure : public rabbit::RefCounted
{ {
private: private:
SQNativeClosure(SQSharedState *ss,SQFUNCTION func){ SQNativeClosure(SQSharedState *ss,SQFUNCTION func){
@ -150,7 +150,7 @@ private:
_env = NULL; _env = NULL;
} }
public: public:
static SQNativeClosure *Create(SQSharedState *ss,SQFUNCTION func,int64_t nouters) static SQNativeClosure *create(SQSharedState *ss,SQFUNCTION func,int64_t nouters)
{ {
int64_t size = _CALC_NATVIVECLOSURE_SIZE(nouters); int64_t size = _CALC_NATVIVECLOSURE_SIZE(nouters);
SQNativeClosure *nc=(SQNativeClosure*)SQ_MALLOC(size); SQNativeClosure *nc=(SQNativeClosure*)SQ_MALLOC(size);
@ -160,9 +160,9 @@ public:
_CONSTRUCT_VECTOR(SQObjectPtr,nc->_noutervalues,nc->_outervalues); _CONSTRUCT_VECTOR(SQObjectPtr,nc->_noutervalues,nc->_outervalues);
return nc; return nc;
} }
SQNativeClosure *Clone() SQNativeClosure *clone()
{ {
SQNativeClosure * ret = SQNativeClosure::Create(NULL,_function,_noutervalues); SQNativeClosure * ret = SQNativeClosure::create(NULL,_function,_noutervalues);
ret->_env = _env; ret->_env = _env;
if(ret->_env) __ObjAddRef(ret->_env); if(ret->_env) __ObjAddRef(ret->_env);
ret->_name = _name; ret->_name = _name;
@ -173,9 +173,9 @@ public:
} }
~SQNativeClosure() ~SQNativeClosure()
{ {
__ObjRelease(_env); __Objrelease(_env);
} }
void Release(){ void release(){
int64_t size = _CALC_NATVIVECLOSURE_SIZE(_noutervalues); int64_t size = _CALC_NATVIVECLOSURE_SIZE(_noutervalues);
_DESTRUCT_VECTOR(SQObjectPtr,_noutervalues,_outervalues); _DESTRUCT_VECTOR(SQObjectPtr,_noutervalues,_outervalues);
this->~SQNativeClosure(); this->~SQNativeClosure();
@ -186,7 +186,7 @@ public:
SQIntVec _typecheck; SQIntVec _typecheck;
SQObjectPtr *_outervalues; SQObjectPtr *_outervalues;
uint64_t _noutervalues; uint64_t _noutervalues;
SQWeakRef *_env; rabbit::WeakRef *_env;
SQFUNCTION _function; SQFUNCTION _function;
SQObjectPtr _name; SQObjectPtr _name;
}; };

View File

@ -39,23 +39,23 @@ struct SQScope {
#define BEGIN_SCOPE() SQScope __oldscope__ = _scope; \ #define BEGIN_SCOPE() SQScope __oldscope__ = _scope; \
_scope.outers = _fs->_outers; \ _scope.outers = _fs->_outers; \
_scope.stacksize = _fs->GetStackSize(); _scope.stacksize = _fs->getStacksize();
#define RESOLVE_OUTERS() if(_fs->GetStackSize() != _scope.stacksize) { \ #define RESOLVE_OUTERS() if(_fs->getStacksize() != _scope.stacksize) { \
if(_fs->CountOuters(_scope.stacksize)) { \ if(_fs->CountOuters(_scope.stacksize)) { \
_fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \ _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
} \ } \
} }
#define END_SCOPE_NO_CLOSE() { if(_fs->GetStackSize() != _scope.stacksize) { \ #define END_SCOPE_NO_CLOSE() { if(_fs->getStacksize() != _scope.stacksize) { \
_fs->SetStackSize(_scope.stacksize); \ _fs->setStacksize(_scope.stacksize); \
} \ } \
_scope = __oldscope__; \ _scope = __oldscope__; \
} }
#define END_SCOPE() { int64_t oldouters = _fs->_outers;\ #define END_SCOPE() { int64_t oldouters = _fs->_outers;\
if(_fs->GetStackSize() != _scope.stacksize) { \ if(_fs->getStacksize() != _scope.stacksize) { \
_fs->SetStackSize(_scope.stacksize); \ _fs->setStacksize(_scope.stacksize); \
if(oldouters != _fs->_outers) { \ if(oldouters != _fs->_outers) { \
_fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \ _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
} \ } \
@ -80,7 +80,7 @@ public:
{ {
_vm=v; _vm=v;
_lex.Init(_ss(v), rg, up,ThrowError,this); _lex.Init(_ss(v), rg, up,ThrowError,this);
_sourcename = SQString::Create(_ss(v), sourcename); _sourcename = SQString::create(_ss(v), sourcename);
_lineinfo = lineinfo;_raiseerror = raiseerror; _lineinfo = lineinfo;_raiseerror = raiseerror;
_scope.outers = 0; _scope.outers = 0;
_scope.stacksize = 0; _scope.stacksize = 0;
@ -135,10 +135,10 @@ public:
switch(tok) switch(tok)
{ {
case TK_IDENTIFIER: case TK_IDENTIFIER:
ret = _fs->CreateString(_lex._svalue); ret = _fs->createString(_lex._svalue);
break; break;
case TK_STRING_LITERAL: case TK_STRING_LITERAL:
ret = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1); ret = _fs->createString(_lex._svalue,_lex._longstr.size()-1);
break; break;
case TK_INTEGER: case TK_INTEGER:
ret = SQObjectPtr(_lex._nvalue); ret = SQObjectPtr(_lex._nvalue);
@ -159,7 +159,7 @@ public:
} }
} }
void MoveIfCurrentTargetIsLocal() { void MoveIfCurrentTargetIsLocal() {
int64_t trg = _fs->TopTarget(); int64_t trg = _fs->topTarget();
if(_fs->IsLocal(trg)) { if(_fs->IsLocal(trg)) {
trg = _fs->PopTarget(); //pops the target and moves it trg = _fs->PopTarget(); //pops the target and moves it
_fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), trg); _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), trg);
@ -171,23 +171,23 @@ public:
_debugop = 0; _debugop = 0;
SQFuncState funcstate(_ss(_vm), NULL,ThrowError,this); SQFuncState funcstate(_ss(_vm), NULL,ThrowError,this);
funcstate._name = SQString::Create(_ss(_vm), _SC("main")); funcstate._name = SQString::create(_ss(_vm), _SC("main"));
_fs = &funcstate; _fs = &funcstate;
_fs->AddParameter(_fs->CreateString(_SC("this"))); _fs->AddParameter(_fs->createString(_SC("this")));
_fs->AddParameter(_fs->CreateString(_SC("vargv"))); _fs->AddParameter(_fs->createString(_SC("vargv")));
_fs->_varparams = true; _fs->_varparams = true;
_fs->_sourcename = _sourcename; _fs->_sourcename = _sourcename;
int64_t stacksize = _fs->GetStackSize(); int64_t stacksize = _fs->getStacksize();
if(setjmp(_errorjmp) == 0) { if(setjmp(_errorjmp) == 0) {
Lex(); Lex();
while(_token > 0){ while(_token > 0){
Statement(); Statement();
if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon(); if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon();
} }
_fs->SetStackSize(stacksize); _fs->setStacksize(stacksize);
_fs->AddLineInfos(_lex._currentline, _lineinfo, true); _fs->AddLineInfos(_lex._currentline, _lineinfo, true);
_fs->AddInstruction(_OP_RETURN, 0xFF); _fs->AddInstruction(_OP_RETURN, 0xFF);
_fs->SetStackSize(0); _fs->setStacksize(0);
o =_fs->BuildProto(); o =_fs->BuildProto();
#ifdef _DEBUG_DUMP #ifdef _DEBUG_DUMP
_fs->Dump(_funcproto(o)); _fs->Dump(_funcproto(o));
@ -198,7 +198,7 @@ public:
_ss(_vm)->_compilererrorhandler(_vm, _compilererror, sq_type(_sourcename) == OT_STRING?_stringval(_sourcename):_SC("unknown"), _ss(_vm)->_compilererrorhandler(_vm, _compilererror, sq_type(_sourcename) == OT_STRING?_stringval(_sourcename):_SC("unknown"),
_lex._currentline, _lex._currentcolumn); _lex._currentline, _lex._currentcolumn);
} }
_vm->_lasterror = SQString::Create(_ss(_vm), _compilererror, -1); _vm->_lasterror = SQString::create(_ss(_vm), _compilererror, -1);
return false; return false;
} }
return true; return true;
@ -234,18 +234,18 @@ public:
} }
Lex(); Lex();
if(!IsEndOfStatement()) { if(!IsEndOfStatement()) {
int64_t retexp = _fs->GetCurrentPos()+1; int64_t retexp = _fs->getCurrentPos()+1;
CommaExpr(); CommaExpr();
if(op == _OP_RETURN && _fs->_traps > 0) if(op == _OP_RETURN && _fs->_traps > 0)
_fs->AddInstruction(_OP_POPTRAP, _fs->_traps, 0); _fs->AddInstruction(_OP_POPTRAP, _fs->_traps, 0);
_fs->_returnexp = retexp; _fs->_returnexp = retexp;
_fs->AddInstruction(op, 1, _fs->PopTarget(),_fs->GetStackSize()); _fs->AddInstruction(op, 1, _fs->PopTarget(),_fs->getStacksize());
} }
else{ else{
if(op == _OP_RETURN && _fs->_traps > 0) if(op == _OP_RETURN && _fs->_traps > 0)
_fs->AddInstruction(_OP_POPTRAP, _fs->_traps ,0); _fs->AddInstruction(_OP_POPTRAP, _fs->_traps ,0);
_fs->_returnexp = -1; _fs->_returnexp = -1;
_fs->AddInstruction(op, 0xFF,0,_fs->GetStackSize()); _fs->AddInstruction(op, 0xFF,0,_fs->getStacksize());
} }
break;} break;}
case TK_BREAK: case TK_BREAK:
@ -255,7 +255,7 @@ public:
} }
RESOLVE_OUTERS(); RESOLVE_OUTERS();
_fs->AddInstruction(_OP_JMP, 0, -1234); _fs->AddInstruction(_OP_JMP, 0, -1234);
_fs->_unresolvedbreaks.push_back(_fs->GetCurrentPos()); _fs->_unresolvedbreaks.push_back(_fs->getCurrentPos());
Lex(); Lex();
break; break;
case TK_CONTINUE: case TK_CONTINUE:
@ -265,7 +265,7 @@ public:
} }
RESOLVE_OUTERS(); RESOLVE_OUTERS();
_fs->AddInstruction(_OP_JMP, 0, -1234); _fs->AddInstruction(_OP_JMP, 0, -1234);
_fs->_unresolvedcontinues.push_back(_fs->GetCurrentPos()); _fs->_unresolvedcontinues.push_back(_fs->getCurrentPos());
Lex(); Lex();
break; break;
case TK_FUNCTION: case TK_FUNCTION:
@ -357,7 +357,7 @@ public:
break; break;
case OUTER: case OUTER:
{ {
int64_t val = _fs->TopTarget(); int64_t val = _fs->topTarget();
int64_t tmp = _fs->PushTarget(); int64_t tmp = _fs->PushTarget();
_fs->AddInstruction(_OP_GETOUTER, tmp, pos); _fs->AddInstruction(_OP_GETOUTER, tmp, pos);
_fs->AddInstruction(ChooseArithOpByToken(tok), tmp, val, tmp, 0); _fs->AddInstruction(ChooseArithOpByToken(tok), tmp, val, tmp, 0);
@ -406,7 +406,7 @@ public:
case LOCAL: case LOCAL:
{ {
int64_t src = _fs->PopTarget(); int64_t src = _fs->PopTarget();
int64_t dst = _fs->TopTarget(); int64_t dst = _fs->topTarget();
_fs->AddInstruction(_OP_MOVE, dst, src); _fs->AddInstruction(_OP_MOVE, dst, src);
} }
break; break;
@ -435,20 +435,20 @@ public:
case _SC('?'): { case _SC('?'): {
Lex(); Lex();
_fs->AddInstruction(_OP_JZ, _fs->PopTarget()); _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
int64_t jzpos = _fs->GetCurrentPos(); int64_t jzpos = _fs->getCurrentPos();
int64_t trg = _fs->PushTarget(); int64_t trg = _fs->PushTarget();
Expression(); Expression();
int64_t first_exp = _fs->PopTarget(); int64_t first_exp = _fs->PopTarget();
if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
int64_t endfirstexp = _fs->GetCurrentPos(); int64_t endfirstexp = _fs->getCurrentPos();
_fs->AddInstruction(_OP_JMP, 0, 0); _fs->AddInstruction(_OP_JMP, 0, 0);
Expect(_SC(':')); Expect(_SC(':'));
int64_t jmppos = _fs->GetCurrentPos(); int64_t jmppos = _fs->getCurrentPos();
Expression(); Expression();
int64_t second_exp = _fs->PopTarget(); int64_t second_exp = _fs->PopTarget();
if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
_fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos); _fs->setIntructionParam(jmppos, 1, _fs->getCurrentPos() - jmppos);
_fs->SetIntructionParam(jzpos, 1, endfirstexp - jzpos + 1); _fs->setIntructionParam(jzpos, 1, endfirstexp - jzpos + 1);
_fs->SnoozeOpt(); _fs->SnoozeOpt();
} }
break; break;
@ -479,14 +479,14 @@ public:
int64_t first_exp = _fs->PopTarget(); int64_t first_exp = _fs->PopTarget();
int64_t trg = _fs->PushTarget(); int64_t trg = _fs->PushTarget();
_fs->AddInstruction(_OP_OR, trg, 0, first_exp, 0); _fs->AddInstruction(_OP_OR, trg, 0, first_exp, 0);
int64_t jpos = _fs->GetCurrentPos(); int64_t jpos = _fs->getCurrentPos();
if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
Lex(); INVOKE_EXP(&SQCompiler::LogicalOrExp); Lex(); INVOKE_EXP(&SQCompiler::LogicalOrExp);
_fs->SnoozeOpt(); _fs->SnoozeOpt();
int64_t second_exp = _fs->PopTarget(); int64_t second_exp = _fs->PopTarget();
if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
_fs->SnoozeOpt(); _fs->SnoozeOpt();
_fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos)); _fs->setIntructionParam(jpos, 1, (_fs->getCurrentPos() - jpos));
_es.etype = EXPR; _es.etype = EXPR;
break; break;
}else return; }else return;
@ -499,14 +499,14 @@ public:
int64_t first_exp = _fs->PopTarget(); int64_t first_exp = _fs->PopTarget();
int64_t trg = _fs->PushTarget(); int64_t trg = _fs->PushTarget();
_fs->AddInstruction(_OP_AND, trg, 0, first_exp, 0); _fs->AddInstruction(_OP_AND, trg, 0, first_exp, 0);
int64_t jpos = _fs->GetCurrentPos(); int64_t jpos = _fs->getCurrentPos();
if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
Lex(); INVOKE_EXP(&SQCompiler::LogicalAndExp); Lex(); INVOKE_EXP(&SQCompiler::LogicalAndExp);
_fs->SnoozeOpt(); _fs->SnoozeOpt();
int64_t second_exp = _fs->PopTarget(); int64_t second_exp = _fs->PopTarget();
if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
_fs->SnoozeOpt(); _fs->SnoozeOpt();
_fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos)); _fs->setIntructionParam(jpos, 1, (_fs->getCurrentPos() - jpos));
_es.etype = EXPR; _es.etype = EXPR;
break; break;
} }
@ -624,15 +624,15 @@ public:
pos = -1; pos = -1;
Lex(); Lex();
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER))); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(Expect(TK_IDENTIFIER)));
if(_es.etype==BASE) { if(_es.etype==BASE) {
Emit2ArgsOP(_OP_GET); Emit2ArgsOP(_OP_GET);
pos = _fs->TopTarget(); pos = _fs->topTarget();
_es.etype = EXPR; _es.etype = EXPR;
_es.epos = pos; _es.epos = pos;
} }
else { else {
if(NeedGet()) { if(Needget()) {
Emit2ArgsOP(_OP_GET); Emit2ArgsOP(_OP_GET);
} }
_es.etype = OBJECT; _es.etype = OBJECT;
@ -644,12 +644,12 @@ public:
pos = -1; pos = -1;
if(_es.etype==BASE) { if(_es.etype==BASE) {
Emit2ArgsOP(_OP_GET); Emit2ArgsOP(_OP_GET);
pos = _fs->TopTarget(); pos = _fs->topTarget();
_es.etype = EXPR; _es.etype = EXPR;
_es.epos = pos; _es.epos = pos;
} }
else { else {
if(NeedGet()) { if(Needget()) {
Emit2ArgsOP(_OP_GET); Emit2ArgsOP(_OP_GET);
} }
_es.etype = OBJECT; _es.etype = OBJECT;
@ -721,14 +721,14 @@ public:
switch(_token) switch(_token)
{ {
case TK_STRING_LITERAL: case TK_STRING_LITERAL:
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->CreateString(_lex._svalue,_lex._longstr.size()-1))); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(_fs->createString(_lex._svalue,_lex._longstr.size()-1)));
Lex(); Lex();
break; break;
case TK_BASE: case TK_BASE:
Lex(); Lex();
_fs->AddInstruction(_OP_GETBASE, _fs->PushTarget()); _fs->AddInstruction(_OP_GETBASE, _fs->PushTarget());
_es.etype = BASE; _es.etype = BASE;
_es.epos = _fs->TopTarget(); _es.epos = _fs->topTarget();
return (_es.epos); return (_es.epos);
break; break;
case TK_IDENTIFIER: case TK_IDENTIFIER:
@ -738,23 +738,23 @@ public:
SQObject constant; SQObject constant;
switch(_token) { switch(_token) {
case TK_IDENTIFIER: id = _fs->CreateString(_lex._svalue); break; case TK_IDENTIFIER: id = _fs->createString(_lex._svalue); break;
case TK_THIS: id = _fs->CreateString(_SC("this"),4); break; case TK_THIS: id = _fs->createString(_SC("this"),4); break;
case TK_CONSTRUCTOR: id = _fs->CreateString(_SC("constructor"),11); break; case TK_CONSTRUCTOR: id = _fs->createString(_SC("constructor"),11); break;
} }
int64_t pos = -1; int64_t pos = -1;
Lex(); Lex();
if((pos = _fs->GetLocalVariable(id)) != -1) { if((pos = _fs->getLocalVariable(id)) != -1) {
/* Handle a local variable (includes 'this') */ /* Handle a local variable (includes 'this') */
_fs->PushTarget(pos); _fs->PushTarget(pos);
_es.etype = LOCAL; _es.etype = LOCAL;
_es.epos = pos; _es.epos = pos;
} }
else if((pos = _fs->GetOuterVariable(id)) != -1) { else if((pos = _fs->getOuterVariable(id)) != -1) {
/* Handle a free var */ /* Handle a free var */
if(NeedGet()) { if(Needget()) {
_es.epos = _fs->PushTarget(); _es.epos = _fs->PushTarget();
_fs->AddInstruction(_OP_GETOUTER, _es.epos, pos); _fs->AddInstruction(_OP_GETOUTER, _es.epos, pos);
/* _es.etype = EXPR; already default value */ /* _es.etype = EXPR; already default value */
@ -772,7 +772,7 @@ public:
if(sq_type(constant) == OT_TABLE) { if(sq_type(constant) == OT_TABLE) {
Expect('.'); Expect('.');
constid = Expect(TK_IDENTIFIER); constid = Expect(TK_IDENTIFIER);
if(!_table(constant)->Get(constid, constval)) { if(!_table(constant)->get(constid, constval)) {
constval.Null(); constval.Null();
Error(_SC("invalid constant [%s.%s]"), _stringval(id), _stringval(constid)); Error(_SC("invalid constant [%s.%s]"), _stringval(id), _stringval(constid));
} }
@ -788,7 +788,7 @@ public:
case OT_INTEGER: EmitLoadConstInt(_integer(constval),_es.epos); break; case OT_INTEGER: EmitLoadConstInt(_integer(constval),_es.epos); break;
case OT_FLOAT: EmitLoadConstFloat(_float(constval),_es.epos); break; case OT_FLOAT: EmitLoadConstFloat(_float(constval),_es.epos); break;
case OT_BOOL: _fs->AddInstruction(_OP_LOADBOOL, _es.epos, _integer(constval)); break; case OT_BOOL: _fs->AddInstruction(_OP_LOADBOOL, _es.epos, _integer(constval)); break;
default: _fs->AddInstruction(_OP_LOAD,_es.epos,_fs->GetConstant(constval)); break; default: _fs->AddInstruction(_OP_LOAD,_es.epos,_fs->getConstant(constval)); break;
} }
_es.etype = EXPR; _es.etype = EXPR;
} }
@ -800,8 +800,8 @@ public:
* the _OP_GET instruction. * the _OP_GET instruction.
*/ */
_fs->PushTarget(0); _fs->PushTarget(0);
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id)); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(id));
if(NeedGet()) { if(Needget()) {
Emit2ArgsOP(_OP_GET); Emit2ArgsOP(_OP_GET);
} }
_es.etype = OBJECT; _es.etype = OBJECT;
@ -828,17 +828,17 @@ public:
break; break;
case _SC('['): { case _SC('['): {
_fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,0,NOT_ARRAY); _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,0,NOT_ARRAY);
int64_t apos = _fs->GetCurrentPos(),key = 0; int64_t apos = _fs->getCurrentPos(),key = 0;
Lex(); Lex();
while(_token != _SC(']')) { while(_token != _SC(']')) {
Expression(); Expression();
if(_token == _SC(',')) Lex(); if(_token == _SC(',')) Lex();
int64_t val = _fs->PopTarget(); int64_t val = _fs->PopTarget();
int64_t array = _fs->TopTarget(); int64_t array = _fs->topTarget();
_fs->AddInstruction(_OP_APPENDARRAY, array, val, AAT_STACK); _fs->AddInstruction(_OP_APPENDARRAY, array, val, AAT_STACK);
key++; key++;
} }
_fs->SetIntructionParam(apos, 1, key); _fs->setIntructionParam(apos, 1, key);
Lex(); Lex();
} }
break; break;
@ -873,7 +873,7 @@ public:
case _SC('('): Lex(); CommaExpr(); Expect(_SC(')')); case _SC('('): Lex(); CommaExpr(); Expect(_SC(')'));
break; break;
case TK___LINE__: EmitLoadConstInt(_lex._currentline,-1); Lex(); break; case TK___LINE__: EmitLoadConstInt(_lex._currentline,-1); Lex(); break;
case TK___FILE__: _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_sourcename)); Lex(); break; case TK___FILE__: _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(_sourcename)); Lex(); break;
default: Error(_SC("expression expected")); default: Error(_SC("expression expected"));
} }
_es.etype = EXPR; _es.etype = EXPR;
@ -888,7 +888,7 @@ public:
_fs->AddInstruction(_OP_LOADINT, target,value); _fs->AddInstruction(_OP_LOADINT, target,value);
} }
else { else {
_fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value)); _fs->AddInstruction(_OP_LOAD, target, _fs->getNumericConstant(value));
} }
} }
void EmitLoadConstFloat(float_t value,int64_t target) void EmitLoadConstFloat(float_t value,int64_t target)
@ -900,7 +900,7 @@ public:
_fs->AddInstruction(_OP_LOADFLOAT, target,*((int32_t *)&value)); _fs->AddInstruction(_OP_LOADFLOAT, target,*((int32_t *)&value));
} }
else { else {
_fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value)); _fs->AddInstruction(_OP_LOAD, target, _fs->getNumericConstant(value));
} }
} }
void UnaryOP(SQOpcode op) void UnaryOP(SQOpcode op)
@ -909,7 +909,7 @@ public:
int64_t src = _fs->PopTarget(); int64_t src = _fs->PopTarget();
_fs->AddInstruction(op, _fs->PushTarget(), src); _fs->AddInstruction(op, _fs->PushTarget(), src);
} }
bool NeedGet() bool Needget()
{ {
switch(_token) { switch(_token) {
case _SC('='): case _SC('('): case TK_NEWSLOT: case TK_MODEQ: case TK_MULEQ: case _SC('='): case _SC('('): case TK_NEWSLOT: case TK_MODEQ: case TK_MULEQ:
@ -947,7 +947,7 @@ public:
} }
void ParseTableOrClass(int64_t separator,int64_t terminator) void ParseTableOrClass(int64_t separator,int64_t terminator)
{ {
int64_t tpos = _fs->GetCurrentPos(),nkeys = 0; int64_t tpos = _fs->getCurrentPos(),nkeys = 0;
while(_token != terminator) { while(_token != terminator) {
bool hasattrs = false; bool hasattrs = false;
bool isstatic = false; bool isstatic = false;
@ -968,10 +968,10 @@ public:
case TK_CONSTRUCTOR:{ case TK_CONSTRUCTOR:{
int64_t tk = _token; int64_t tk = _token;
Lex(); Lex();
SQObject id = tk == TK_FUNCTION ? Expect(TK_IDENTIFIER) : _fs->CreateString(_SC("constructor")); SQObject id = tk == TK_FUNCTION ? Expect(TK_IDENTIFIER) : _fs->createString(_SC("constructor"));
Expect(_SC('(')); Expect(_SC('('));
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id)); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(id));
CreateFunction(id); createFunction(id);
_fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0); _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
} }
break; break;
@ -981,12 +981,12 @@ public:
break; break;
case TK_STRING_LITERAL: //JSON case TK_STRING_LITERAL: //JSON
if(separator == ',') { //only works for tables if(separator == ',') { //only works for tables
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_STRING_LITERAL))); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(Expect(TK_STRING_LITERAL)));
Expect(_SC(':')); Expression(); Expect(_SC(':')); Expression();
break; break;
} }
default : default :
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER))); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(Expect(TK_IDENTIFIER)));
Expect(_SC('=')); Expression(); Expect(_SC('=')); Expression();
} }
if(_token == separator) Lex();//optional comma/semicolon if(_token == separator) Lex();//optional comma/semicolon
@ -997,7 +997,7 @@ public:
((void)attrs); ((void)attrs);
assert((hasattrs && (attrs == key-1)) || !hasattrs); assert((hasattrs && (attrs == key-1)) || !hasattrs);
unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0); unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0);
int64_t table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE int64_t table = _fs->topTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
if(separator == _SC(',')) { //hack recognizes a table from the separator if(separator == _SC(',')) { //hack recognizes a table from the separator
_fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val); _fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
} }
@ -1006,7 +1006,7 @@ public:
} }
} }
if(separator == _SC(',')) //hack recognizes a table from the separator if(separator == _SC(',')) //hack recognizes a table from the separator
_fs->SetIntructionParam(tpos, 1, nkeys); _fs->setIntructionParam(tpos, 1, nkeys);
Lex(); Lex();
} }
void LocalDeclStatement() void LocalDeclStatement()
@ -1017,7 +1017,7 @@ public:
Lex(); Lex();
varname = Expect(TK_IDENTIFIER); varname = Expect(TK_IDENTIFIER);
Expect(_SC('(')); Expect(_SC('('));
CreateFunction(varname,false); createFunction(varname,false);
_fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0); _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
_fs->PopTarget(); _fs->PopTarget();
_fs->PushLocalVariable(varname); _fs->PushLocalVariable(varname);
@ -1068,7 +1068,7 @@ public:
bool haselse = false; bool haselse = false;
Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')')); Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
_fs->AddInstruction(_OP_JZ, _fs->PopTarget()); _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
int64_t jnepos = _fs->GetCurrentPos(); int64_t jnepos = _fs->getCurrentPos();
@ -1086,52 +1086,52 @@ public:
}*/ }*/
int64_t endifblock = _fs->GetCurrentPos(); int64_t endifblock = _fs->getCurrentPos();
if(_token == TK_ELSE){ if(_token == TK_ELSE){
haselse = true; haselse = true;
//BEGIN_SCOPE(); //BEGIN_SCOPE();
_fs->AddInstruction(_OP_JMP); _fs->AddInstruction(_OP_JMP);
jmppos = _fs->GetCurrentPos(); jmppos = _fs->getCurrentPos();
Lex(); Lex();
//Statement(); if(_lex._prevtoken != _SC('}')) OptionalSemicolon(); //Statement(); if(_lex._prevtoken != _SC('}')) OptionalSemicolon();
IfBlock(); IfBlock();
//END_SCOPE(); //END_SCOPE();
_fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos); _fs->setIntructionParam(jmppos, 1, _fs->getCurrentPos() - jmppos);
} }
_fs->SetIntructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0)); _fs->setIntructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0));
} }
void WhileStatement() void WhileStatement()
{ {
int64_t jzpos, jmppos; int64_t jzpos, jmppos;
jmppos = _fs->GetCurrentPos(); jmppos = _fs->getCurrentPos();
Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')')); Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
BEGIN_BREAKBLE_BLOCK(); BEGIN_BREAKBLE_BLOCK();
_fs->AddInstruction(_OP_JZ, _fs->PopTarget()); _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
jzpos = _fs->GetCurrentPos(); jzpos = _fs->getCurrentPos();
BEGIN_SCOPE(); BEGIN_SCOPE();
Statement(); Statement();
END_SCOPE(); END_SCOPE();
_fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1); _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->getCurrentPos() - 1);
_fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos); _fs->setIntructionParam(jzpos, 1, _fs->getCurrentPos() - jzpos);
END_BREAKBLE_BLOCK(jmppos); END_BREAKBLE_BLOCK(jmppos);
} }
void DoWhileStatement() void DoWhileStatement()
{ {
Lex(); Lex();
int64_t jmptrg = _fs->GetCurrentPos(); int64_t jmptrg = _fs->getCurrentPos();
BEGIN_BREAKBLE_BLOCK() BEGIN_BREAKBLE_BLOCK()
BEGIN_SCOPE(); BEGIN_SCOPE();
Statement(); Statement();
END_SCOPE(); END_SCOPE();
Expect(TK_WHILE); Expect(TK_WHILE);
int64_t continuetrg = _fs->GetCurrentPos(); int64_t continuetrg = _fs->getCurrentPos();
Expect(_SC('(')); CommaExpr(); Expect(_SC(')')); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
_fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1); _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
_fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1); _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->getCurrentPos() - 1);
END_BREAKBLE_BLOCK(continuetrg); END_BREAKBLE_BLOCK(continuetrg);
} }
void ForStatement() void ForStatement()
@ -1146,35 +1146,35 @@ public:
} }
Expect(_SC(';')); Expect(_SC(';'));
_fs->SnoozeOpt(); _fs->SnoozeOpt();
int64_t jmppos = _fs->GetCurrentPos(); int64_t jmppos = _fs->getCurrentPos();
int64_t jzpos = -1; int64_t jzpos = -1;
if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->GetCurrentPos(); } if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->getCurrentPos(); }
Expect(_SC(';')); Expect(_SC(';'));
_fs->SnoozeOpt(); _fs->SnoozeOpt();
int64_t expstart = _fs->GetCurrentPos() + 1; int64_t expstart = _fs->getCurrentPos() + 1;
if(_token != _SC(')')) { if(_token != _SC(')')) {
CommaExpr(); CommaExpr();
_fs->PopTarget(); _fs->PopTarget();
} }
Expect(_SC(')')); Expect(_SC(')'));
_fs->SnoozeOpt(); _fs->SnoozeOpt();
int64_t expend = _fs->GetCurrentPos(); int64_t expend = _fs->getCurrentPos();
int64_t expsize = (expend - expstart) + 1; int64_t expsize = (expend - expstart) + 1;
SQInstructionVec exp; SQInstructionVec exp;
if(expsize > 0) { if(expsize > 0) {
for(int64_t i = 0; i < expsize; i++) for(int64_t i = 0; i < expsize; i++)
exp.push_back(_fs->GetInstruction(expstart + i)); exp.push_back(_fs->getInstruction(expstart + i));
_fs->PopInstructions(expsize); _fs->PopInstructions(expsize);
} }
BEGIN_BREAKBLE_BLOCK() BEGIN_BREAKBLE_BLOCK()
Statement(); Statement();
int64_t continuetrg = _fs->GetCurrentPos(); int64_t continuetrg = _fs->getCurrentPos();
if(expsize > 0) { if(expsize > 0) {
for(int64_t i = 0; i < expsize; i++) for(int64_t i = 0; i < expsize; i++)
_fs->AddInstruction(exp[i]); _fs->AddInstruction(exp[i]);
} }
_fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0); _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->getCurrentPos() - 1, 0);
if(jzpos> 0) _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos); if(jzpos> 0) _fs->setIntructionParam(jzpos, 1, _fs->getCurrentPos() - jzpos);
END_BREAKBLE_BLOCK(continuetrg); END_BREAKBLE_BLOCK(continuetrg);
@ -1189,7 +1189,7 @@ public:
Lex(); valname = Expect(TK_IDENTIFIER); Lex(); valname = Expect(TK_IDENTIFIER);
} }
else{ else{
idxname = _fs->CreateString(_SC("@INDEX@")); idxname = _fs->createString(_SC("@INDEX@"));
} }
Expect(TK_IN); Expect(TK_IN);
@ -1197,7 +1197,7 @@ public:
BEGIN_SCOPE(); BEGIN_SCOPE();
//put the table in the stack(evaluate the table expression) //put the table in the stack(evaluate the table expression)
Expression(); Expect(_SC(')')); Expression(); Expect(_SC(')'));
int64_t container = _fs->TopTarget(); int64_t container = _fs->topTarget();
//push the index local var //push the index local var
int64_t indexpos = _fs->PushLocalVariable(idxname); int64_t indexpos = _fs->PushLocalVariable(idxname);
_fs->AddInstruction(_OP_LOADNULLS, indexpos,1); _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
@ -1205,18 +1205,18 @@ public:
int64_t valuepos = _fs->PushLocalVariable(valname); int64_t valuepos = _fs->PushLocalVariable(valname);
_fs->AddInstruction(_OP_LOADNULLS, valuepos,1); _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
//push reference index //push reference index
int64_t itrpos = _fs->PushLocalVariable(_fs->CreateString(_SC("@ITERATOR@"))); //use invalid id to make it inaccessible int64_t itrpos = _fs->PushLocalVariable(_fs->createString(_SC("@ITERATOR@"))); //use invalid id to make it inaccessible
_fs->AddInstruction(_OP_LOADNULLS, itrpos,1); _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
int64_t jmppos = _fs->GetCurrentPos(); int64_t jmppos = _fs->getCurrentPos();
_fs->AddInstruction(_OP_FOREACH, container, 0, indexpos); _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
int64_t foreachpos = _fs->GetCurrentPos(); int64_t foreachpos = _fs->getCurrentPos();
_fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos); _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
//generate the statement code //generate the statement code
BEGIN_BREAKBLE_BLOCK() BEGIN_BREAKBLE_BLOCK()
Statement(); Statement();
_fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1); _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->getCurrentPos() - 1);
_fs->SetIntructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos); _fs->setIntructionParam(foreachpos, 1, _fs->getCurrentPos() - foreachpos);
_fs->SetIntructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos); _fs->setIntructionParam(foreachpos + 1, 1, _fs->getCurrentPos() - foreachpos);
END_BREAKBLE_BLOCK(foreachpos - 1); END_BREAKBLE_BLOCK(foreachpos - 1);
//restore the local variable stack(remove index,val and ref idx) //restore the local variable stack(remove index,val and ref idx)
_fs->PopTarget(); _fs->PopTarget();
@ -1226,7 +1226,7 @@ public:
{ {
Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')')); Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
Expect(_SC('{')); Expect(_SC('{'));
int64_t expr = _fs->TopTarget(); int64_t expr = _fs->topTarget();
bool bfirst = true; bool bfirst = true;
int64_t tonextcondjmp = -1; int64_t tonextcondjmp = -1;
int64_t skipcondjmp = -1; int64_t skipcondjmp = -1;
@ -1235,8 +1235,8 @@ public:
while(_token == TK_CASE) { while(_token == TK_CASE) {
if(!bfirst) { if(!bfirst) {
_fs->AddInstruction(_OP_JMP, 0, 0); _fs->AddInstruction(_OP_JMP, 0, 0);
skipcondjmp = _fs->GetCurrentPos(); skipcondjmp = _fs->getCurrentPos();
_fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp); _fs->setIntructionParam(tonextcondjmp, 1, _fs->getCurrentPos() - tonextcondjmp);
} }
//condition //condition
Lex(); Expression(); Expect(_SC(':')); Lex(); Expression(); Expect(_SC(':'));
@ -1254,16 +1254,16 @@ public:
//end condition //end condition
if(skipcondjmp != -1) { if(skipcondjmp != -1) {
_fs->SetIntructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp)); _fs->setIntructionParam(skipcondjmp, 1, (_fs->getCurrentPos() - skipcondjmp));
} }
tonextcondjmp = _fs->GetCurrentPos(); tonextcondjmp = _fs->getCurrentPos();
BEGIN_SCOPE(); BEGIN_SCOPE();
Statements(); Statements();
END_SCOPE(); END_SCOPE();
bfirst = false; bfirst = false;
} }
if(tonextcondjmp != -1) if(tonextcondjmp != -1)
_fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp); _fs->setIntructionParam(tonextcondjmp, 1, _fs->getCurrentPos() - tonextcondjmp);
if(_token == TK_DEFAULT) { if(_token == TK_DEFAULT) {
Lex(); Expect(_SC(':')); Lex(); Expect(_SC(':'));
BEGIN_SCOPE(); BEGIN_SCOPE();
@ -1281,17 +1281,17 @@ public:
SQObject id; SQObject id;
Lex(); id = Expect(TK_IDENTIFIER); Lex(); id = Expect(TK_IDENTIFIER);
_fs->PushTarget(0); _fs->PushTarget(0);
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id)); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(id));
if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET); if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
while(_token == TK_DOUBLE_COLON) { while(_token == TK_DOUBLE_COLON) {
Lex(); Lex();
id = Expect(TK_IDENTIFIER); id = Expect(TK_IDENTIFIER);
_fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id)); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->getConstant(id));
if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET); if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
} }
Expect(_SC('(')); Expect(_SC('('));
CreateFunction(id); createFunction(id);
_fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0); _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
EmitDerefOp(_OP_NEWSLOT); EmitDerefOp(_OP_NEWSLOT);
_fs->PopTarget(); _fs->PopTarget();
@ -1330,7 +1330,7 @@ public:
val._unVal.fFloat = _lex._fvalue; val._unVal.fFloat = _lex._fvalue;
break; break;
case TK_STRING_LITERAL: case TK_STRING_LITERAL:
val = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1); val = _fs->createString(_lex._svalue,_lex._longstr.size()-1);
break; break;
case TK_TRUE: case TK_TRUE:
case TK_FALSE: case TK_FALSE:
@ -1365,7 +1365,7 @@ public:
SQObject id = Expect(TK_IDENTIFIER); SQObject id = Expect(TK_IDENTIFIER);
Expect(_SC('{')); Expect(_SC('{'));
SQObject table = _fs->CreateTable(); SQObject table = _fs->createTable();
int64_t nval = 0; int64_t nval = 0;
while(_token != _SC('}')) { while(_token != _SC('}')) {
SQObject key = Expect(TK_IDENTIFIER); SQObject key = Expect(TK_IDENTIFIER);
@ -1395,7 +1395,7 @@ public:
_fs->_traps++; _fs->_traps++;
if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++; if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++; if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
int64_t trappos = _fs->GetCurrentPos(); int64_t trappos = _fs->getCurrentPos();
{ {
BEGIN_SCOPE(); BEGIN_SCOPE();
Statement(); Statement();
@ -1406,15 +1406,15 @@ public:
if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--; if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--; if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
_fs->AddInstruction(_OP_JMP, 0, 0); _fs->AddInstruction(_OP_JMP, 0, 0);
int64_t jmppos = _fs->GetCurrentPos(); int64_t jmppos = _fs->getCurrentPos();
_fs->SetIntructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos)); _fs->setIntructionParam(trappos, 1, (_fs->getCurrentPos() - trappos));
Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')')); Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')'));
{ {
BEGIN_SCOPE(); BEGIN_SCOPE();
int64_t ex_target = _fs->PushLocalVariable(exid); int64_t ex_target = _fs->PushLocalVariable(exid);
_fs->SetIntructionParam(trappos, 0, ex_target); _fs->setIntructionParam(trappos, 0, ex_target);
Statement(); Statement();
_fs->SetIntructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0); _fs->setIntructionParams(jmppos, 0, (_fs->getCurrentPos() - jmppos), 0);
END_SCOPE(); END_SCOPE();
} }
} }
@ -1422,7 +1422,7 @@ public:
{ {
Lex(); Expect(_SC('(')); Lex(); Expect(_SC('('));
SQObjectPtr dummy; SQObjectPtr dummy;
CreateFunction(dummy,lambda); createFunction(dummy,lambda);
_fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1); _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
} }
void ClassExp() void ClassExp()
@ -1431,13 +1431,13 @@ public:
int64_t attrs = -1; int64_t attrs = -1;
if(_token == TK_EXTENDS) { if(_token == TK_EXTENDS) {
Lex(); Expression(); Lex(); Expression();
base = _fs->TopTarget(); base = _fs->topTarget();
} }
if(_token == TK_ATTR_OPEN) { if(_token == TK_ATTR_OPEN) {
Lex(); Lex();
_fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE); _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
ParseTableOrClass(_SC(','),TK_ATTR_CLOSE); ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
attrs = _fs->TopTarget(); attrs = _fs->topTarget();
} }
Expect(_SC('{')); Expect(_SC('{'));
if(attrs != -1) _fs->PopTarget(); if(attrs != -1) _fs->PopTarget();
@ -1476,7 +1476,7 @@ public:
Emit2ArgsOP(_OP_INC, diff); Emit2ArgsOP(_OP_INC, diff);
} }
else if(_es.etype==LOCAL) { else if(_es.etype==LOCAL) {
int64_t src = _fs->TopTarget(); int64_t src = _fs->topTarget();
_fs->AddInstruction(_OP_INCL, src, src, 0, diff); _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
} }
@ -1488,18 +1488,18 @@ public:
} }
_es = es; _es = es;
} }
void CreateFunction(SQObject &name,bool lambda = false) void createFunction(SQObject &name,bool lambda = false)
{ {
SQFuncState *funcstate = _fs->PushChildState(_ss(_vm)); SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
funcstate->_name = name; funcstate->_name = name;
SQObject paramname; SQObject paramname;
funcstate->AddParameter(_fs->CreateString(_SC("this"))); funcstate->AddParameter(_fs->createString(_SC("this")));
funcstate->_sourcename = _sourcename; funcstate->_sourcename = _sourcename;
int64_t defparams = 0; int64_t defparams = 0;
while(_token!=_SC(')')) { while(_token!=_SC(')')) {
if(_token == TK_VARPARAMS) { if(_token == TK_VARPARAMS) {
if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters")); if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
funcstate->AddParameter(_fs->CreateString(_SC("vargv"))); funcstate->AddParameter(_fs->createString(_SC("vargv")));
funcstate->_varparams = true; funcstate->_varparams = true;
Lex(); Lex();
if(_token != _SC(')')) Error(_SC("expected ')'")); if(_token != _SC(')')) Error(_SC("expected ')'"));
@ -1511,7 +1511,7 @@ public:
if(_token == _SC('=')) { if(_token == _SC('=')) {
Lex(); Lex();
Expression(); Expression();
funcstate->AddDefaultParam(_fs->TopTarget()); funcstate->AddDefaultParam(_fs->topTarget());
defparams++; defparams++;
} }
else { else {
@ -1536,7 +1536,7 @@ public:
} }
funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true); funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true);
funcstate->AddInstruction(_OP_RETURN, -1); funcstate->AddInstruction(_OP_RETURN, -1);
funcstate->SetStackSize(0); funcstate->setStacksize(0);
SQFunctionProto *func = funcstate->BuildProto(); SQFunctionProto *func = funcstate->BuildProto();
#ifdef _DEBUG_DUMP #ifdef _DEBUG_DUMP
@ -1552,7 +1552,7 @@ public:
int64_t pos = funcstate->_unresolvedbreaks.back(); int64_t pos = funcstate->_unresolvedbreaks.back();
funcstate->_unresolvedbreaks.pop_back(); funcstate->_unresolvedbreaks.pop_back();
//set the jmp instruction //set the jmp instruction
funcstate->SetIntructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0); funcstate->setIntructionParams(pos, 0, funcstate->getCurrentPos() - pos, 0);
ntoresolve--; ntoresolve--;
} }
} }
@ -1562,7 +1562,7 @@ public:
int64_t pos = funcstate->_unresolvedcontinues.back(); int64_t pos = funcstate->_unresolvedcontinues.back();
funcstate->_unresolvedcontinues.pop_back(); funcstate->_unresolvedcontinues.pop_back();
//set the jmp instruction //set the jmp instruction
funcstate->SetIntructionParams(pos, 0, targetpos - pos, 0); funcstate->setIntructionParams(pos, 0, targetpos - pos, 0);
ntoresolve--; ntoresolve--;
} }
} }

View File

@ -44,7 +44,7 @@ SQRESULT sq_stackinfos(HRABBITVM v, int64_t level, SQStackInfos *si)
si->funcname = _stringval(func->_name); si->funcname = _stringval(func->_name);
if (sq_type(func->_sourcename) == OT_STRING) if (sq_type(func->_sourcename) == OT_STRING)
si->source = _stringval(func->_sourcename); si->source = _stringval(func->_sourcename);
si->line = func->GetLine(ci._ip); si->line = func->getLine(ci._ip);
} }
break; break;
case OT_NATIVECLOSURE: case OT_NATIVECLOSURE:
@ -68,7 +68,7 @@ void SQVM::Raise_Error(const SQChar *s, ...)
int64_t buffersize = (int64_t)scstrlen(s)+(NUMBER_MAX_CHAR*2); int64_t buffersize = (int64_t)scstrlen(s)+(NUMBER_MAX_CHAR*2);
scvsprintf(_sp(sq_rsl(buffersize)),buffersize, s, vl); scvsprintf(_sp(sq_rsl(buffersize)),buffersize, s, vl);
va_end(vl); va_end(vl);
_lasterror = SQString::Create(_ss(this),_spval,-1); _lasterror = SQString::create(_ss(this),_spval,-1);
} }
void SQVM::Raise_Error(const SQObjectPtr &desc) void SQVM::Raise_Error(const SQObjectPtr &desc)
@ -82,14 +82,14 @@ SQString *SQVM::PrintObjVal(const SQObjectPtr &o)
case OT_STRING: return _string(o); case OT_STRING: return _string(o);
case OT_INTEGER: case OT_INTEGER:
scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)),sq_rsl(NUMBER_MAX_CHAR), _PRINT_INT_FMT, _integer(o)); scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)),sq_rsl(NUMBER_MAX_CHAR), _PRINT_INT_FMT, _integer(o));
return SQString::Create(_ss(this), _spval); return SQString::create(_ss(this), _spval);
break; break;
case OT_FLOAT: case OT_FLOAT:
scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)), sq_rsl(NUMBER_MAX_CHAR), _SC("%.14g"), _float(o)); scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)), sq_rsl(NUMBER_MAX_CHAR), _SC("%.14g"), _float(o));
return SQString::Create(_ss(this), _spval); return SQString::create(_ss(this), _spval);
break; break;
default: default:
return SQString::Create(_ss(this), GetTypeName(o)); return SQString::create(_ss(this), getTypeName(o));
} }
} }
@ -108,15 +108,15 @@ void SQVM::Raise_CompareError(const SQObject &o1, const SQObject &o2)
void SQVM::Raise_ParamTypeError(int64_t nparam,int64_t typemask,int64_t type) void SQVM::Raise_ParamTypeError(int64_t nparam,int64_t typemask,int64_t type)
{ {
SQObjectPtr exptypes = SQString::Create(_ss(this), _SC(""), -1); SQObjectPtr exptypes = SQString::create(_ss(this), _SC(""), -1);
int64_t found = 0; int64_t found = 0;
for(int64_t i=0; i<16; i++) for(int64_t i=0; i<16; i++)
{ {
int64_t mask = ((int64_t)1) << i; int64_t mask = ((int64_t)1) << i;
if(typemask & (mask)) { if(typemask & (mask)) {
if(found>0) StringCat(exptypes,SQString::Create(_ss(this), _SC("|"), -1), exptypes); if(found>0) StringCat(exptypes,SQString::create(_ss(this), _SC("|"), -1), exptypes);
found ++; found ++;
StringCat(exptypes,SQString::Create(_ss(this), IdType2Name((SQObjectType)mask), -1), exptypes); StringCat(exptypes,SQString::create(_ss(this), IdType2Name((SQObjectType)mask), -1), exptypes);
} }
} }
Raise_Error(_SC("parameter %d has an invalid type '%s' ; expected: '%s'"), nparam, IdType2Name((SQObjectType)type), _stringval(exptypes)); Raise_Error(_SC("parameter %d has an invalid type '%s' ; expected: '%s'"), nparam, IdType2Name((SQObjectType)type), _stringval(exptypes));

View File

@ -64,14 +64,14 @@ typedef sqvector<SQLineInfo> SQLineInfoVec;
+(localinf*sizeof(SQLocalVarInfo))+(defparams*sizeof(int64_t))) +(localinf*sizeof(SQLocalVarInfo))+(defparams*sizeof(int64_t)))
struct SQFunctionProto : public SQRefCounted struct SQFunctionProto : public rabbit::RefCounted
{ {
private: private:
SQFunctionProto(SQSharedState *ss); SQFunctionProto(SQSharedState *ss);
~SQFunctionProto(); ~SQFunctionProto();
public: public:
static SQFunctionProto *Create(SQSharedState *ss,int64_t ninstructions, static SQFunctionProto *create(SQSharedState *ss,int64_t ninstructions,
int64_t nliterals,int64_t nparameters, int64_t nliterals,int64_t nparameters,
int64_t nfunctions,int64_t noutervalues, int64_t nfunctions,int64_t noutervalues,
int64_t nlineinfos,int64_t nlocalvarinfos,int64_t ndefaultparams) int64_t nlineinfos,int64_t nlocalvarinfos,int64_t ndefaultparams)
@ -104,7 +104,7 @@ public:
_CONSTRUCT_VECTOR(SQLocalVarInfo,f->_nlocalvarinfos,f->_localvarinfos); _CONSTRUCT_VECTOR(SQLocalVarInfo,f->_nlocalvarinfos,f->_localvarinfos);
return f; return f;
} }
void Release(){ void release(){
_DESTRUCT_VECTOR(SQObjectPtr,_nliterals,_literals); _DESTRUCT_VECTOR(SQObjectPtr,_nliterals,_literals);
_DESTRUCT_VECTOR(SQObjectPtr,_nparameters,_parameters); _DESTRUCT_VECTOR(SQObjectPtr,_nparameters,_parameters);
_DESTRUCT_VECTOR(SQObjectPtr,_nfunctions,_functions); _DESTRUCT_VECTOR(SQObjectPtr,_nfunctions,_functions);
@ -116,8 +116,8 @@ public:
sq_vm_free(this,size); sq_vm_free(this,size);
} }
const SQChar* GetLocal(SQVM *v,uint64_t stackbase,uint64_t nseq,uint64_t nop); const SQChar* getLocal(SQVM *v,uint64_t stackbase,uint64_t nseq,uint64_t nop);
int64_t GetLine(SQInstruction *curr); int64_t getLine(SQInstruction *curr);
bool Save(SQVM *v,SQUserPointer up,SQWRITEFUNC write); bool Save(SQVM *v,SQUserPointer up,SQWRITEFUNC write);
static bool Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &ret); static bool Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &ret);
SQObjectPtr _sourcename; SQObjectPtr _sourcename;

View File

@ -87,15 +87,15 @@ void DumpLiteral(SQObjectPtr &o)
case OT_FLOAT: scprintf(_SC("{%f}"),_float(o));break; case OT_FLOAT: scprintf(_SC("{%f}"),_float(o));break;
case OT_INTEGER: scprintf(_SC("{") _PRINT_INT_FMT _SC("}"),_integer(o));break; case OT_INTEGER: scprintf(_SC("{") _PRINT_INT_FMT _SC("}"),_integer(o));break;
case OT_BOOL: scprintf(_SC("%s"),_integer(o)?_SC("true"):_SC("false"));break; case OT_BOOL: scprintf(_SC("%s"),_integer(o)?_SC("true"):_SC("false"));break;
default: scprintf(_SC("(%s %p)"),GetTypeName(o),(void*)_rawval(o));break; break; //shut up compiler default: scprintf(_SC("(%s %p)"),getTypeName(o),(void*)_rawval(o));break; break; //shut up compiler
} }
} }
SQFuncState::SQFuncState(SQSharedState *ss,SQFuncState *parent,CompilerErrorFunc efunc,void *ed) SQFuncState::SQFuncState(SQSharedState *ss,SQFuncState *parent,CompilerErrorFunc efunc,void *ed)
{ {
_nliterals = 0; _nliterals = 0;
_literals = SQTable::Create(ss,0); _literals = SQTable::create(ss,0);
_strings = SQTable::Create(ss,0); _strings = SQTable::create(ss,0);
_sharedstate = ss; _sharedstate = ss;
_lastline = 0; _lastline = 0;
_optimization = true; _optimization = true;
@ -131,7 +131,7 @@ void SQFuncState::Dump(SQFunctionProto *func)
int64_t idx; int64_t idx;
SQObjectPtrVec templiterals; SQObjectPtrVec templiterals;
templiterals.resize(_nliterals); templiterals.resize(_nliterals);
while((idx=_table(_literals)->Next(false,refidx,key,val))!=-1) { while((idx=_table(_literals)->next(false,refidx,key,val))!=-1) {
refidx=idx; refidx=idx;
templiterals[_integer(val)]=key; templiterals[_integer(val)]=key;
} }
@ -176,7 +176,7 @@ void SQFuncState::Dump(SQFunctionProto *func)
else { else {
int64_t refidx; int64_t refidx;
SQObjectPtr val,key,refo; SQObjectPtr val,key,refo;
while(((refidx=_table(_literals)->Next(false,refo,key,val))!= -1) && (_integer(val) != lidx)) { while(((refidx=_table(_literals)->next(false,refo,key,val))!= -1) && (_integer(val) != lidx)) {
refo = refidx; refo = refidx;
} }
DumpLiteral(key); DumpLiteral(key);
@ -192,7 +192,7 @@ void SQFuncState::Dump(SQFunctionProto *func)
else { else {
int64_t refidx; int64_t refidx;
SQObjectPtr val,key,refo; SQObjectPtr val,key,refo;
while(((refidx=_table(_literals)->Next(false,refo,key,val))!= -1) && (_integer(val) != lidx)) { while(((refidx=_table(_literals)->next(false,refo,key,val))!= -1) && (_integer(val) != lidx)) {
refo = refidx; refo = refidx;
} }
DumpLiteral(key); DumpLiteral(key);
@ -217,20 +217,20 @@ void SQFuncState::Dump(SQFunctionProto *func)
} }
#endif #endif
int64_t SQFuncState::GetNumericConstant(const int64_t cons) int64_t SQFuncState::getNumericConstant(const int64_t cons)
{ {
return GetConstant(SQObjectPtr(cons)); return getConstant(SQObjectPtr(cons));
} }
int64_t SQFuncState::GetNumericConstant(const float_t cons) int64_t SQFuncState::getNumericConstant(const float_t cons)
{ {
return GetConstant(SQObjectPtr(cons)); return getConstant(SQObjectPtr(cons));
} }
int64_t SQFuncState::GetConstant(const SQObject &cons) int64_t SQFuncState::getConstant(const SQObject &cons)
{ {
SQObjectPtr val; SQObjectPtr val;
if(!_table(_literals)->Get(cons,val)) if(!_table(_literals)->get(cons,val))
{ {
val = _nliterals; val = _nliterals;
_table(_literals)->NewSlot(cons,val); _table(_literals)->NewSlot(cons,val);
@ -243,7 +243,7 @@ int64_t SQFuncState::GetConstant(const SQObject &cons)
return _integer(val); return _integer(val);
} }
void SQFuncState::SetIntructionParams(int64_t pos,int64_t arg0,int64_t arg1,int64_t arg2,int64_t arg3) void SQFuncState::setIntructionParams(int64_t pos,int64_t arg0,int64_t arg1,int64_t arg2,int64_t arg3)
{ {
_instructions[pos]._arg0=(unsigned char)*((uint64_t *)&arg0); _instructions[pos]._arg0=(unsigned char)*((uint64_t *)&arg0);
_instructions[pos]._arg1=(int32_t)*((uint64_t *)&arg1); _instructions[pos]._arg1=(int32_t)*((uint64_t *)&arg1);
@ -251,7 +251,7 @@ void SQFuncState::SetIntructionParams(int64_t pos,int64_t arg0,int64_t arg1,int6
_instructions[pos]._arg3=(unsigned char)*((uint64_t *)&arg3); _instructions[pos]._arg3=(unsigned char)*((uint64_t *)&arg3);
} }
void SQFuncState::SetIntructionParam(int64_t pos,int64_t arg,int64_t val) void SQFuncState::setIntructionParam(int64_t pos,int64_t arg,int64_t val)
{ {
switch(arg){ switch(arg){
case 0:_instructions[pos]._arg0=(unsigned char)*((uint64_t *)&val);break; case 0:_instructions[pos]._arg0=(unsigned char)*((uint64_t *)&val);break;
@ -283,11 +283,11 @@ int64_t SQFuncState::PushTarget(int64_t n)
return n; return n;
} }
int64_t SQFuncState::GetUpTarget(int64_t n){ int64_t SQFuncState::getUpTarget(int64_t n){
return _targetstack[((_targetstack.size()-1)-n)]; return _targetstack[((_targetstack.size()-1)-n)];
} }
int64_t SQFuncState::TopTarget(){ int64_t SQFuncState::topTarget(){
return _targetstack.back(); return _targetstack.back();
} }
int64_t SQFuncState::PopTarget() int64_t SQFuncState::PopTarget()
@ -302,7 +302,7 @@ int64_t SQFuncState::PopTarget()
return npos; return npos;
} }
int64_t SQFuncState::GetStackSize() int64_t SQFuncState::getStacksize()
{ {
return _vlocals.size(); return _vlocals.size();
} }
@ -321,7 +321,7 @@ int64_t SQFuncState::CountOuters(int64_t stacksize)
return outers; return outers;
} }
void SQFuncState::SetStackSize(int64_t n) void SQFuncState::setStacksize(int64_t n)
{ {
int64_t size=_vlocals.size(); int64_t size=_vlocals.size();
while(size>n){ while(size>n){
@ -331,7 +331,7 @@ void SQFuncState::SetStackSize(int64_t n)
if(lvi._end_op == UINT_MINUS_ONE) { //this means is an outer if(lvi._end_op == UINT_MINUS_ONE) { //this means is an outer
_outers--; _outers--;
} }
lvi._end_op = GetCurrentPos(); lvi._end_op = getCurrentPos();
_localvarinfos.push_back(lvi); _localvarinfos.push_back(lvi);
} }
_vlocals.pop_back(); _vlocals.pop_back();
@ -341,7 +341,7 @@ void SQFuncState::SetStackSize(int64_t n)
bool SQFuncState::IsConstant(const SQObject &name,SQObject &e) bool SQFuncState::IsConstant(const SQObject &name,SQObject &e)
{ {
SQObjectPtr val; SQObjectPtr val;
if(_table(_sharedstate->_consts)->Get(name,val)) { if(_table(_sharedstate->_consts)->get(name,val)) {
e = val; e = val;
return true; return true;
} }
@ -360,7 +360,7 @@ int64_t SQFuncState::PushLocalVariable(const SQObject &name)
int64_t pos=_vlocals.size(); int64_t pos=_vlocals.size();
SQLocalVarInfo lvi; SQLocalVarInfo lvi;
lvi._name=name; lvi._name=name;
lvi._start_op=GetCurrentPos()+1; lvi._start_op=getCurrentPos()+1;
lvi._pos=_vlocals.size(); lvi._pos=_vlocals.size();
_vlocals.push_back(lvi); _vlocals.push_back(lvi);
if(_vlocals.size()>((uint64_t)_stacksize))_stacksize=_vlocals.size(); if(_vlocals.size()>((uint64_t)_stacksize))_stacksize=_vlocals.size();
@ -369,7 +369,7 @@ int64_t SQFuncState::PushLocalVariable(const SQObject &name)
int64_t SQFuncState::GetLocalVariable(const SQObject &name) int64_t SQFuncState::getLocalVariable(const SQObject &name)
{ {
int64_t locals=_vlocals.size(); int64_t locals=_vlocals.size();
while(locals>=1){ while(locals>=1){
@ -389,7 +389,7 @@ void SQFuncState::MarkLocalAsOuter(int64_t pos)
_outers++; _outers++;
} }
int64_t SQFuncState::GetOuterVariable(const SQObject &name) int64_t SQFuncState::getOuterVariable(const SQObject &name)
{ {
int64_t outers = _outervalues.size(); int64_t outers = _outervalues.size();
for(int64_t i = 0; i<outers; i++) { for(int64_t i = 0; i<outers; i++) {
@ -398,9 +398,9 @@ int64_t SQFuncState::GetOuterVariable(const SQObject &name)
} }
int64_t pos=-1; int64_t pos=-1;
if(_parent) { if(_parent) {
pos = _parent->GetLocalVariable(name); pos = _parent->getLocalVariable(name);
if(pos == -1) { if(pos == -1) {
pos = _parent->GetOuterVariable(name); pos = _parent->getOuterVariable(name);
if(pos != -1) { if(pos != -1) {
_outervalues.push_back(SQOuterVar(name,SQObjectPtr(int64_t(pos)),otOUTER)); //local _outervalues.push_back(SQOuterVar(name,SQObjectPtr(int64_t(pos)),otOUTER)); //local
return _outervalues.size() - 1; return _outervalues.size() - 1;
@ -427,7 +427,7 @@ void SQFuncState::AddLineInfos(int64_t line,bool lineop,bool force)
{ {
if(_lastline!=line || force){ if(_lastline!=line || force){
SQLineInfo li; SQLineInfo li;
li._line=line;li._op=(GetCurrentPos()+1); li._line=line;li._op=(getCurrentPos()+1);
if(lineop)AddInstruction(_OP_LINE,0,line); if(lineop)AddInstruction(_OP_LINE,0,line);
if(_lastline!=line) { if(_lastline!=line) {
_lineinfos.push_back(li); _lineinfos.push_back(li);
@ -584,16 +584,16 @@ void SQFuncState::AddInstruction(SQInstruction &i)
_instructions.push_back(i); _instructions.push_back(i);
} }
SQObject SQFuncState::CreateString(const SQChar *s,int64_t len) SQObject SQFuncState::createString(const SQChar *s,int64_t len)
{ {
SQObjectPtr ns(SQString::Create(_sharedstate,s,len)); SQObjectPtr ns(SQString::create(_sharedstate,s,len));
_table(_strings)->NewSlot(ns,(int64_t)1); _table(_strings)->NewSlot(ns,(int64_t)1);
return ns; return ns;
} }
SQObject SQFuncState::CreateTable() SQObject SQFuncState::createTable()
{ {
SQObjectPtr nt(SQTable::Create(_sharedstate,0)); SQObjectPtr nt(SQTable::create(_sharedstate,0));
_table(_strings)->NewSlot(nt,(int64_t)1); _table(_strings)->NewSlot(nt,(int64_t)1);
return nt; return nt;
} }
@ -601,7 +601,7 @@ SQObject SQFuncState::CreateTable()
SQFunctionProto *SQFuncState::BuildProto() SQFunctionProto *SQFuncState::BuildProto()
{ {
SQFunctionProto *f=SQFunctionProto::Create(_ss,_instructions.size(), SQFunctionProto *f=SQFunctionProto::create(_ss,_instructions.size(),
_nliterals,_parameters.size(),_functions.size(),_outervalues.size(), _nliterals,_parameters.size(),_functions.size(),_outervalues.size(),
_lineinfos.size(),_localvarinfos.size(),_defaultparams.size()); _lineinfos.size(),_localvarinfos.size(),_defaultparams.size());
@ -613,7 +613,7 @@ SQFunctionProto *SQFuncState::BuildProto()
f->_bgenerator = _bgenerator; f->_bgenerator = _bgenerator;
f->_name = _name; f->_name = _name;
while((idx=_table(_literals)->Next(false,refidx,key,val))!=-1) { while((idx=_table(_literals)->next(false,refidx,key,val))!=-1) {
f->_literals[_integer(val)]=key; f->_literals[_integer(val)]=key;
refidx=idx; refidx=idx;
} }

View File

@ -21,38 +21,38 @@ struct SQFuncState
void PopChildState(); void PopChildState();
void AddInstruction(SQOpcode _op,int64_t arg0=0,int64_t arg1=0,int64_t arg2=0,int64_t arg3=0){SQInstruction i(_op,arg0,arg1,arg2,arg3);AddInstruction(i);} void AddInstruction(SQOpcode _op,int64_t arg0=0,int64_t arg1=0,int64_t arg2=0,int64_t arg3=0){SQInstruction i(_op,arg0,arg1,arg2,arg3);AddInstruction(i);}
void AddInstruction(SQInstruction &i); void AddInstruction(SQInstruction &i);
void SetIntructionParams(int64_t pos,int64_t arg0,int64_t arg1,int64_t arg2=0,int64_t arg3=0); void setIntructionParams(int64_t pos,int64_t arg0,int64_t arg1,int64_t arg2=0,int64_t arg3=0);
void SetIntructionParam(int64_t pos,int64_t arg,int64_t val); void setIntructionParam(int64_t pos,int64_t arg,int64_t val);
SQInstruction &GetInstruction(int64_t pos){return _instructions[pos];} SQInstruction &getInstruction(int64_t pos){return _instructions[pos];}
void PopInstructions(int64_t size){for(int64_t i=0;i<size;i++)_instructions.pop_back();} void PopInstructions(int64_t size){for(int64_t i=0;i<size;i++)_instructions.pop_back();}
void SetStackSize(int64_t n); void setStacksize(int64_t n);
int64_t CountOuters(int64_t stacksize); int64_t CountOuters(int64_t stacksize);
void SnoozeOpt(){_optimization=false;} void SnoozeOpt(){_optimization=false;}
void AddDefaultParam(int64_t trg) { _defaultparams.push_back(trg); } void AddDefaultParam(int64_t trg) { _defaultparams.push_back(trg); }
int64_t GetDefaultParamCount() { return _defaultparams.size(); } int64_t getDefaultParamCount() { return _defaultparams.size(); }
int64_t GetCurrentPos(){return _instructions.size()-1;} int64_t getCurrentPos(){return _instructions.size()-1;}
int64_t GetNumericConstant(const int64_t cons); int64_t getNumericConstant(const int64_t cons);
int64_t GetNumericConstant(const float_t cons); int64_t getNumericConstant(const float_t cons);
int64_t PushLocalVariable(const SQObject &name); int64_t PushLocalVariable(const SQObject &name);
void AddParameter(const SQObject &name); void AddParameter(const SQObject &name);
//void AddOuterValue(const SQObject &name); //void AddOuterValue(const SQObject &name);
int64_t GetLocalVariable(const SQObject &name); int64_t getLocalVariable(const SQObject &name);
void MarkLocalAsOuter(int64_t pos); void MarkLocalAsOuter(int64_t pos);
int64_t GetOuterVariable(const SQObject &name); int64_t getOuterVariable(const SQObject &name);
int64_t GenerateCode(); int64_t GenerateCode();
int64_t GetStackSize(); int64_t getStacksize();
int64_t CalcStackFrameSize(); int64_t CalcStackFramesize();
void AddLineInfos(int64_t line,bool lineop,bool force=false); void AddLineInfos(int64_t line,bool lineop,bool force=false);
SQFunctionProto *BuildProto(); SQFunctionProto *BuildProto();
int64_t AllocStackPos(); int64_t AllocStackPos();
int64_t PushTarget(int64_t n=-1); int64_t PushTarget(int64_t n=-1);
int64_t PopTarget(); int64_t PopTarget();
int64_t TopTarget(); int64_t topTarget();
int64_t GetUpTarget(int64_t n); int64_t getUpTarget(int64_t n);
void DiscardTarget(); void DiscardTarget();
bool IsLocal(uint64_t stkpos); bool IsLocal(uint64_t stkpos);
SQObject CreateString(const SQChar *s,int64_t len = -1); SQObject createString(const SQChar *s,int64_t len = -1);
SQObject CreateTable(); SQObject createTable();
bool IsConstant(const SQObject &name,SQObject &e); bool IsConstant(const SQObject &name,SQObject &e);
int64_t _returnexp; int64_t _returnexp;
SQLocalVarInfoVec _vlocals; SQLocalVarInfoVec _vlocals;
@ -84,7 +84,7 @@ struct SQFuncState
bool _optimization; bool _optimization;
SQSharedState *_sharedstate; SQSharedState *_sharedstate;
sqvector<SQFuncState*> _childstates; sqvector<SQFuncState*> _childstates;
int64_t GetConstant(const SQObject &cons); int64_t getConstant(const SQObject &cons);
private: private:
CompilerErrorFunc _errfunc; CompilerErrorFunc _errfunc;
void *_errtarget; void *_errtarget;

View File

@ -17,16 +17,16 @@
#define CUR_CHAR (_currdata) #define CUR_CHAR (_currdata)
#define RETURN_TOKEN(t) { _prevtoken = _curtoken; _curtoken = t; return t;} #define RETURN_TOKEN(t) { _prevtoken = _curtoken; _curtoken = t; return t;}
#define IS_EOB() (CUR_CHAR <= RABBIT_EOB) #define IS_EOB() (CUR_CHAR <= RABBIT_EOB)
#define NEXT() {Next();_currentcolumn++;} #define NEXT() {next();_currentcolumn++;}
#define INIT_TEMP_STRING() { _longstr.resize(0);} #define INIT_TEMP_STRING() { _longstr.resize(0);}
#define APPEND_CHAR(c) { _longstr.push_back(c);} #define APPEND_CHAR(c) { _longstr.push_back(c);}
#define TERMINATE_BUFFER() {_longstr.push_back(_SC('\0'));} #define TERMINATE_BUFFER() {_longstr.push_back(_SC('\0'));}
#define ADD_KEYWORD(key,id) _keywords->NewSlot( SQString::Create(ss, _SC(#key)) ,int64_t(id)) #define ADD_KEYWORD(key,id) _keywords->NewSlot( SQString::create(ss, _SC(#key)) ,int64_t(id))
SQLexer::SQLexer(){} SQLexer::SQLexer(){}
SQLexer::~SQLexer() SQLexer::~SQLexer()
{ {
_keywords->Release(); _keywords->release();
} }
void SQLexer::Init(SQSharedState *ss, SQLEXREADFUNC rg, SQUserPointer up,CompilerErrorFunc efunc,void *ed) void SQLexer::Init(SQSharedState *ss, SQLEXREADFUNC rg, SQUserPointer up,CompilerErrorFunc efunc,void *ed)
@ -34,7 +34,7 @@ void SQLexer::Init(SQSharedState *ss, SQLEXREADFUNC rg, SQUserPointer up,Compile
_errfunc = efunc; _errfunc = efunc;
_errtarget = ed; _errtarget = ed;
_sharedstate = ss; _sharedstate = ss;
_keywords = SQTable::Create(ss, 37); _keywords = SQTable::create(ss, 37);
ADD_KEYWORD(while, TK_WHILE); ADD_KEYWORD(while, TK_WHILE);
ADD_KEYWORD(do, TK_DO); ADD_KEYWORD(do, TK_DO);
ADD_KEYWORD(if, TK_IF); ADD_KEYWORD(if, TK_IF);
@ -81,7 +81,7 @@ void SQLexer::Init(SQSharedState *ss, SQLEXREADFUNC rg, SQUserPointer up,Compile
_currentcolumn = 0; _currentcolumn = 0;
_prevtoken = -1; _prevtoken = -1;
_reached_eof = SQFalse; _reached_eof = SQFalse;
Next(); next();
} }
void SQLexer::Error(const SQChar *err) void SQLexer::Error(const SQChar *err)
@ -89,7 +89,7 @@ void SQLexer::Error(const SQChar *err)
_errfunc(_errtarget,err); _errfunc(_errtarget,err);
} }
void SQLexer::Next() void SQLexer::next()
{ {
int64_t t = _readf(_up); int64_t t = _readf(_up);
if(t > MAX_CHAR) Error(_SC("Invalid character")); if(t > MAX_CHAR) Error(_SC("Invalid character"));
@ -105,7 +105,7 @@ const SQChar *SQLexer::Tok2Str(int64_t tok)
{ {
SQObjectPtr itr, key, val; SQObjectPtr itr, key, val;
int64_t nitr; int64_t nitr;
while((nitr = _keywords->Next(false,itr, key, val)) != -1) { while((nitr = _keywords->next(false,itr, key, val)) != -1) {
itr = (int64_t)nitr; itr = (int64_t)nitr;
if(((int64_t)_integer(val)) == tok) if(((int64_t)_integer(val)) == tok)
return _stringval(key); return _stringval(key);
@ -285,10 +285,10 @@ int64_t SQLexer::Lex()
return 0; return 0;
} }
int64_t SQLexer::GetIDType(const SQChar *s,int64_t len) int64_t SQLexer::getIDType(const SQChar *s,int64_t len)
{ {
SQObjectPtr t; SQObjectPtr t;
if(_keywords->GetStr(s,len, t)) { if(_keywords->getStr(s,len, t)) {
return int64_t(_integer(t)); return int64_t(_integer(t));
} }
return TK_IDENTIFIER; return TK_IDENTIFIER;
@ -560,7 +560,7 @@ int64_t SQLexer::ReadID()
NEXT(); NEXT();
} while(scisalnum(CUR_CHAR) || CUR_CHAR == _SC('_')); } while(scisalnum(CUR_CHAR) || CUR_CHAR == _SC('_'));
TERMINATE_BUFFER(); TERMINATE_BUFFER();
res = GetIDType(&_longstr[0],_longstr.size() - 1); res = getIDType(&_longstr[0],_longstr.size() - 1);
if(res == TK_IDENTIFIER || res == TK_CONSTRUCTOR) { if(res == TK_IDENTIFIER || res == TK_CONSTRUCTOR) {
_svalue = &_longstr[0]; _svalue = &_longstr[0];
} }

View File

@ -22,13 +22,13 @@ struct SQLexer
int64_t Lex(); int64_t Lex();
const SQChar *Tok2Str(int64_t tok); const SQChar *Tok2Str(int64_t tok);
private: private:
int64_t GetIDType(const SQChar *s,int64_t len); int64_t getIDType(const SQChar *s,int64_t len);
int64_t ReadString(int64_t ndelim,bool verbatim); int64_t ReadString(int64_t ndelim,bool verbatim);
int64_t ReadNumber(); int64_t ReadNumber();
void LexBlockComment(); void LexBlockComment();
void LexLineComment(); void LexLineComment();
int64_t ReadID(); int64_t ReadID();
void Next(); void next();
#ifdef SQUNICODE #ifdef SQUNICODE
#if WCHAR_SIZE == 2 #if WCHAR_SIZE == 2
int64_t AddUTF16(uint64_t ch); int64_t AddUTF16(uint64_t ch);

View File

@ -8,7 +8,7 @@
#include <rabbit/sqpcheader.hpp> #include <rabbit/sqpcheader.hpp>
#include <rabbit/sqvm.hpp> #include <rabbit/sqvm.hpp>
#include <rabbit/sqstring.hpp> #include <rabbit/sqstring.hpp>
#include <rabbit/sqarray.hpp> #include <rabbit/Array.hpp>
#include <rabbit/sqtable.hpp> #include <rabbit/sqtable.hpp>
#include <rabbit/UserData.hpp> #include <rabbit/UserData.hpp>
#include <rabbit/sqfuncproto.hpp> #include <rabbit/sqfuncproto.hpp>
@ -45,25 +45,25 @@ const SQChar *IdType2Name(SQObjectType type)
} }
} }
const SQChar *GetTypeName(const SQObjectPtr &obj1) const SQChar *getTypeName(const SQObjectPtr &obj1)
{ {
return IdType2Name(sq_type(obj1)); return IdType2Name(sq_type(obj1));
} }
SQString *SQString::Create(SQSharedState *ss,const SQChar *s,int64_t len) SQString *SQString::create(SQSharedState *ss,const SQChar *s,int64_t len)
{ {
SQString *str=ADD_STRING(ss,s,len); SQString *str=ADD_STRING(ss,s,len);
return str; return str;
} }
void SQString::Release() void SQString::release()
{ {
REMOVE_STRING(_sharedstate,this); REMOVE_STRING(_sharedstate,this);
} }
int64_t SQString::Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval) int64_t SQString::next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval)
{ {
int64_t idx = (int64_t)TranslateIndex(refpos); int64_t idx = (int64_t)translateIndex(refpos);
while(idx < _len){ while(idx < _len){
outkey = (int64_t)idx; outkey = (int64_t)idx;
outval = (int64_t)((uint64_t)_val[idx]); outval = (int64_t)((uint64_t)_val[idx]);
@ -74,7 +74,7 @@ int64_t SQString::Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectP
return -1; return -1;
} }
uint64_t TranslateIndex(const SQObjectPtr &idx) uint64_t translateIndex(const SQObjectPtr &idx)
{ {
switch(sq_type(idx)){ switch(sq_type(idx)){
case OT_NULL: case OT_NULL:
@ -86,42 +86,16 @@ uint64_t TranslateIndex(const SQObjectPtr &idx)
return 0; return 0;
} }
SQWeakRef *SQRefCounted::GetWeakRef(SQObjectType type)
{
if(!_weakref) {
sq_new(_weakref,SQWeakRef);
#if defined(SQUSEDOUBLE) && !defined(_SQ64)
_weakref->_obj._unVal.raw = 0; //clean the whole union on 32 bits with double
#endif
_weakref->_obj._type = type;
_weakref->_obj._unVal.pRefCounted = this;
}
return _weakref;
}
SQRefCounted::~SQRefCounted()
{
if(_weakref) {
_weakref->_obj._type = OT_NULL;
_weakref->_obj._unVal.pRefCounted = NULL;
}
}
void SQWeakRef::Release() { bool SQDelegable::getMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res) {
if(ISREFCOUNTED(_obj._type)) {
_obj._unVal.pRefCounted->_weakref = NULL;
}
sq_delete(this,SQWeakRef);
}
bool SQDelegable::GetMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res) {
if(_delegate) { if(_delegate) {
return _delegate->Get((*_ss(v)->_metamethods)[mm],res); return _delegate->get((*_ss(v)->_metamethods)[mm],res);
} }
return false; return false;
} }
bool SQDelegable::SetDelegate(SQTable *mt) bool SQDelegable::setDelegate(SQTable *mt)
{ {
SQTable *temp = mt; SQTable *temp = mt;
if(temp == this) return false; if(temp == this) return false;
@ -130,7 +104,7 @@ bool SQDelegable::SetDelegate(SQTable *mt)
temp = temp->_delegate; temp = temp->_delegate;
} }
if (mt) __ObjAddRef(mt); if (mt) __ObjAddRef(mt);
__ObjRelease(_delegate); __Objrelease(_delegate);
_delegate = mt; _delegate = mt;
return true; return true;
} }
@ -143,7 +117,7 @@ bool SQGenerator::Yield(SQVM *v,int64_t target)
_stack.resize(size); _stack.resize(size);
SQObject _this = v->_stack[v->_stackbase]; SQObject _this = v->_stack[v->_stackbase];
_stack._vals[0] = ISREFCOUNTED(sq_type(_this)) ? SQObjectPtr(_refcounted(_this)->GetWeakRef(sq_type(_this))) : _this; _stack._vals[0] = ISREFCOUNTED(sq_type(_this)) ? SQObjectPtr(_refcounted(_this)->getWeakRef(sq_type(_this))) : _this;
for(int64_t n =1; n<target; n++) { for(int64_t n =1; n<target; n++) {
_stack._vals[n] = v->_stack[v->_stackbase+n]; _stack._vals[n] = v->_stack[v->_stackbase+n];
} }
@ -209,14 +183,14 @@ bool SQGenerator::Resume(SQVM *v,SQObjectPtr &dest)
return true; return true;
} }
void SQArray::Extend(const SQArray *a){ void rabbit::Array::extend(const rabbit::Array *a){
int64_t xlen; int64_t xlen;
if((xlen=a->Size())) if((xlen=a->size()))
for(int64_t i=0;i<xlen;i++) for(int64_t i=0;i<xlen;i++)
Append(a->_values[i]); append((*a)[i]);
} }
const SQChar* SQFunctionProto::GetLocal(SQVM *vm,uint64_t stackbase,uint64_t nseq,uint64_t nop) const SQChar* SQFunctionProto::getLocal(SQVM *vm,uint64_t stackbase,uint64_t nseq,uint64_t nop)
{ {
uint64_t nvars=_nlocalvarinfos; uint64_t nvars=_nlocalvarinfos;
const SQChar *res=NULL; const SQChar *res=NULL;
@ -237,7 +211,7 @@ const SQChar* SQFunctionProto::GetLocal(SQVM *vm,uint64_t stackbase,uint64_t nse
} }
int64_t SQFunctionProto::GetLine(SQInstruction *curr) int64_t SQFunctionProto::getLine(SQInstruction *curr)
{ {
int64_t op = (int64_t)(curr-_instructions); int64_t op = (int64_t)(curr-_instructions);
int64_t line=_lineinfos[0]._line; int64_t line=_lineinfos[0]._line;
@ -273,9 +247,9 @@ int64_t SQFunctionProto::GetLine(SQInstruction *curr)
SQClosure::~SQClosure() SQClosure::~SQClosure()
{ {
__ObjRelease(_root); __Objrelease(_root);
__ObjRelease(_env); __Objrelease(_env);
__ObjRelease(_base); __Objrelease(_base);
} }
#define _CHECK_IO(exp) { if(!exp)return false; } #define _CHECK_IO(exp) { if(!exp)return false; }
@ -330,7 +304,7 @@ bool WriteObject(HRABBITVM v,SQUserPointer up,SQWRITEFUNC write,SQObjectPtr &o)
case OT_NULL: case OT_NULL:
break; break;
default: default:
v->Raise_Error(_SC("cannot serialize a %s"),GetTypeName(o)); v->Raise_Error(_SC("cannot serialize a %s"),getTypeName(o));
return false; return false;
} }
return true; return true;
@ -345,8 +319,8 @@ bool ReadObject(HRABBITVM v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &o)
case OT_STRING:{ case OT_STRING:{
int64_t len; int64_t len;
_CHECK_IO(SafeRead(v,read,up,&len,sizeof(int64_t))); _CHECK_IO(SafeRead(v,read,up,&len,sizeof(int64_t)));
_CHECK_IO(SafeRead(v,read,up,_ss(v)->GetScratchPad(sq_rsl(len)),sq_rsl(len))); _CHECK_IO(SafeRead(v,read,up,_ss(v)->getScratchPad(sq_rsl(len)),sq_rsl(len)));
o=SQString::Create(_ss(v),_ss(v)->GetScratchPad(-1),len); o=SQString::create(_ss(v),_ss(v)->getScratchPad(-1),len);
} }
break; break;
case OT_INTEGER:{ case OT_INTEGER:{
@ -391,7 +365,7 @@ bool SQClosure::Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &ret)
SQObjectPtr func; SQObjectPtr func;
_CHECK_IO(SQFunctionProto::Load(v,up,read,func)); _CHECK_IO(SQFunctionProto::Load(v,up,read,func));
_CHECK_IO(CheckTag(v,read,up,SQ_CLOSURESTREAM_TAIL)); _CHECK_IO(CheckTag(v,read,up,SQ_CLOSURESTREAM_TAIL));
ret = SQClosure::Create(_ss(v),_funcproto(func),_table(v->_roottable)->GetWeakRef(OT_TABLE)); ret = SQClosure::create(_ss(v),_funcproto(func),_table(v->_roottable)->getWeakRef(OT_TABLE));
//FIXME: load an root for this closure //FIXME: load an root for this closure
return true; return true;
} }
@ -491,7 +465,7 @@ bool SQFunctionProto::Load(SQVM *v,SQUserPointer up,SQREADFUNC read,SQObjectPtr
_CHECK_IO(SafeRead(v,read,up, &nfunctions, sizeof(nfunctions))); _CHECK_IO(SafeRead(v,read,up, &nfunctions, sizeof(nfunctions)));
SQFunctionProto *f = SQFunctionProto::Create(NULL,ninstructions,nliterals,nparameters, SQFunctionProto *f = SQFunctionProto::create(NULL,ninstructions,nliterals,nparameters,
nfunctions,noutervalues,nlineinfos,nlocalvarinfos,ndefaultparams); nfunctions,noutervalues,nlineinfos,nlocalvarinfos,ndefaultparams);
SQObjectPtr proto = f; //gets a ref in case of failure SQObjectPtr proto = f; //gets a ref in case of failure
f->_sourcename = sourcename; f->_sourcename = sourcename;

View File

@ -8,6 +8,8 @@
#pragma once #pragma once
#include <rabbit/squtils.hpp> #include <rabbit/squtils.hpp>
#include <rabbit/RefCounted.hpp>
#include <rabbit/WeakRef.hpp>
#ifdef _SQ64 #ifdef _SQ64
#define UINT_MINUS_ONE (0xFFFFFFFFFFFFFFFF) #define UINT_MINUS_ONE (0xFFFFFFFFFFFFFFFF)
@ -89,22 +91,6 @@ enum SQMetaMethod{
#define MINPOWER2 4 #define MINPOWER2 4
struct SQRefCounted
{
uint64_t _uiRef;
struct SQWeakRef *_weakref;
SQRefCounted() { _uiRef = 0; _weakref = NULL; }
virtual ~SQRefCounted();
SQWeakRef *GetWeakRef(SQObjectType type);
virtual void Release()=0;
};
struct SQWeakRef : SQRefCounted
{
void Release();
SQObject _obj;
};
#define _realval(o) (sq_type((o)) != OT_WEAKREF?(SQObject)o:_weakref(o)->_obj) #define _realval(o) (sq_type((o)) != OT_WEAKREF?(SQObject)o:_weakref(o)->_obj)
@ -112,25 +98,26 @@ struct SQObjectPtr;
#define __AddRef(type,unval) if(ISREFCOUNTED(type)) \ #define __AddRef(type,unval) if(ISREFCOUNTED(type)) \
{ \ { \
unval.pRefCounted->_uiRef++; \ unval.pRefCounted->refCountIncrement(); \
} }
#define __Release(type,unval) if(ISREFCOUNTED(type) && ((--unval.pRefCounted->_uiRef)==0)) \ #define __release(type,unval) if(ISREFCOUNTED(type) && (unval.pRefCounted->refCountDecrement()==0)) \
{ \ { \
unval.pRefCounted->Release(); \ unval.pRefCounted->release(); \
} }
#define __ObjRelease(obj) { \ #define __Objrelease(obj) { \
if((obj)) { \ if((obj)) { \
(obj)->_uiRef--; \ auto val = (obj)->refCountDecrement(); \
if((obj)->_uiRef == 0) \ if(val == 0) { \
(obj)->Release(); \ (obj)->release(); \
} \
(obj) = NULL; \ (obj) = NULL; \
} \ } \
} }
#define __ObjAddRef(obj) { \ #define __ObjAddRef(obj) { \
(obj)->_uiRef++; \ (obj)->refCountIncrement(); \
} }
#define is_delegable(t) (sq_type(t)&SQOBJECT_DELEGABLE) #define is_delegable(t) (sq_type(t)&SQOBJECT_DELEGABLE)
@ -176,7 +163,7 @@ struct SQObjectPtr;
_type=type; \ _type=type; \
_unVal.sym = x; \ _unVal.sym = x; \
assert(_unVal.pTable); \ assert(_unVal.pTable); \
_unVal.pRefCounted->_uiRef++; \ _unVal.pRefCounted->refCountIncrement(); \
} \ } \
inline SQObjectPtr& operator=(_class *x) \ inline SQObjectPtr& operator=(_class *x) \
{ \ { \
@ -187,8 +174,8 @@ struct SQObjectPtr;
_type = type; \ _type = type; \
SQ_REFOBJECT_INIT() \ SQ_REFOBJECT_INIT() \
_unVal.sym = x; \ _unVal.sym = x; \
_unVal.pRefCounted->_uiRef++; \ _unVal.pRefCounted->refCountIncrement(); \
__Release(tOldType,unOldVal); \ __release(tOldType,unOldVal); \
return *this; \ return *this; \
} }
@ -201,7 +188,7 @@ struct SQObjectPtr;
} \ } \
inline SQObjectPtr& operator=(_class x) \ inline SQObjectPtr& operator=(_class x) \
{ \ { \
__Release(_type,_unVal); \ __release(_type,_unVal); \
_type = type; \ _type = type; \
SQ_OBJECT_RAWINIT() \ SQ_OBJECT_RAWINIT() \
_unVal.sym = x; \ _unVal.sym = x; \
@ -230,14 +217,14 @@ struct SQObjectPtr : public SQObject
_REF_TYPE_DECL(OT_TABLE,SQTable,pTable) _REF_TYPE_DECL(OT_TABLE,SQTable,pTable)
_REF_TYPE_DECL(OT_CLASS,SQClass,pClass) _REF_TYPE_DECL(OT_CLASS,SQClass,pClass)
_REF_TYPE_DECL(OT_INSTANCE,SQInstance,pInstance) _REF_TYPE_DECL(OT_INSTANCE,SQInstance,pInstance)
_REF_TYPE_DECL(OT_ARRAY,SQArray,pArray) _REF_TYPE_DECL(OT_ARRAY,rabbit::Array,pArray)
_REF_TYPE_DECL(OT_CLOSURE,SQClosure,pClosure) _REF_TYPE_DECL(OT_CLOSURE,SQClosure,pClosure)
_REF_TYPE_DECL(OT_NATIVECLOSURE,SQNativeClosure,pNativeClosure) _REF_TYPE_DECL(OT_NATIVECLOSURE,SQNativeClosure,pNativeClosure)
_REF_TYPE_DECL(OT_OUTER,SQOuter,pOuter) _REF_TYPE_DECL(OT_OUTER,SQOuter,pOuter)
_REF_TYPE_DECL(OT_GENERATOR,SQGenerator,pGenerator) _REF_TYPE_DECL(OT_GENERATOR,SQGenerator,pGenerator)
_REF_TYPE_DECL(OT_STRING,SQString,pString) _REF_TYPE_DECL(OT_STRING,SQString,pString)
_REF_TYPE_DECL(OT_USERDATA,rabbit::UserData,pUserData) _REF_TYPE_DECL(OT_USERDATA,rabbit::UserData,pUserData)
_REF_TYPE_DECL(OT_WEAKREF,SQWeakRef,pWeakRef) _REF_TYPE_DECL(OT_WEAKREF,rabbit::WeakRef,pWeakRef)
_REF_TYPE_DECL(OT_THREAD,SQVM,pThread) _REF_TYPE_DECL(OT_THREAD,SQVM,pThread)
_REF_TYPE_DECL(OT_FUNCPROTO,SQFunctionProto,pFunctionProto) _REF_TYPE_DECL(OT_FUNCPROTO,SQFunctionProto,pFunctionProto)
@ -253,7 +240,7 @@ struct SQObjectPtr : public SQObject
} }
inline SQObjectPtr& operator=(bool b) inline SQObjectPtr& operator=(bool b)
{ {
__Release(_type,_unVal); __release(_type,_unVal);
SQ_OBJECT_RAWINIT() SQ_OBJECT_RAWINIT()
_type = OT_BOOL; _type = OT_BOOL;
_unVal.nInteger = b?1:0; _unVal.nInteger = b?1:0;
@ -262,7 +249,7 @@ struct SQObjectPtr : public SQObject
~SQObjectPtr() ~SQObjectPtr()
{ {
__Release(_type,_unVal); __release(_type,_unVal);
} }
inline SQObjectPtr& operator=(const SQObjectPtr& obj) inline SQObjectPtr& operator=(const SQObjectPtr& obj)
@ -274,7 +261,7 @@ struct SQObjectPtr : public SQObject
_unVal = obj._unVal; _unVal = obj._unVal;
_type = obj._type; _type = obj._type;
__AddRef(_type,_unVal); __AddRef(_type,_unVal);
__Release(tOldType,unOldVal); __release(tOldType,unOldVal);
return *this; return *this;
} }
inline SQObjectPtr& operator=(const SQObject& obj) inline SQObjectPtr& operator=(const SQObject& obj)
@ -286,7 +273,7 @@ struct SQObjectPtr : public SQObject
_unVal = obj._unVal; _unVal = obj._unVal;
_type = obj._type; _type = obj._type;
__AddRef(_type,_unVal); __AddRef(_type,_unVal);
__Release(tOldType,unOldVal); __release(tOldType,unOldVal);
return *this; return *this;
} }
inline void Null() inline void Null()
@ -295,7 +282,7 @@ struct SQObjectPtr : public SQObject
SQObjectValue unOldVal = _unVal; SQObjectValue unOldVal = _unVal;
_type = OT_NULL; _type = OT_NULL;
_unVal.raw = (SQRawObjectVal)NULL; _unVal.raw = (SQRawObjectVal)NULL;
__Release(tOldType ,unOldVal); __release(tOldType ,unOldVal);
} }
private: private:
SQObjectPtr(const SQChar *){} //safety SQObjectPtr(const SQChar *){} //safety
@ -313,16 +300,16 @@ inline void _Swap(SQObject &a,SQObject &b)
} }
struct SQDelegable : public SQRefCounted { struct SQDelegable : public rabbit::RefCounted {
bool SetDelegate(SQTable *m); bool setDelegate(SQTable *m);
virtual bool GetMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res); virtual bool getMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res);
SQTable *_delegate; SQTable *_delegate;
}; };
uint64_t TranslateIndex(const SQObjectPtr &idx); uint64_t translateIndex(const SQObjectPtr &idx);
typedef sqvector<SQObjectPtr> SQObjectPtrVec; typedef sqvector<SQObjectPtr> SQObjectPtrVec;
typedef sqvector<int64_t> SQIntVec; typedef sqvector<int64_t> SQIntVec;
const SQChar *GetTypeName(const SQObjectPtr &obj1); const SQChar *getTypeName(const SQObjectPtr &obj1);
const SQChar *IdType2Name(SQObjectType type); const SQChar *IdType2Name(SQObjectType type);

View File

@ -33,7 +33,7 @@ enum NewObjectType {
NOT_CLASS = 2 NOT_CLASS = 2
}; };
enum AppendArrayType { enum appendArrayType {
AAT_STACK = 0, AAT_STACK = 0,
AAT_LITERAL = 1, AAT_LITERAL = 1,
AAT_INT = 2, AAT_INT = 2,

View File

@ -12,7 +12,7 @@
#include <rabbit/sqclosure.hpp> #include <rabbit/sqclosure.hpp>
#include <rabbit/sqstring.hpp> #include <rabbit/sqstring.hpp>
#include <rabbit/sqtable.hpp> #include <rabbit/sqtable.hpp>
#include <rabbit/sqarray.hpp> #include <rabbit/Array.hpp>
#include <rabbit/UserData.hpp> #include <rabbit/UserData.hpp>
#include <rabbit/sqclass.hpp> #include <rabbit/sqclass.hpp>
@ -28,11 +28,11 @@ SQSharedState::SQSharedState()
} }
#define newsysstring(s) { \ #define newsysstring(s) { \
_systemstrings->push_back(SQString::Create(this,s)); \ _systemstrings->push_back(SQString::create(this,s)); \
} }
#define newmetamethod(s) { \ #define newmetamethod(s) { \
_metamethods->push_back(SQString::Create(this,s)); \ _metamethods->push_back(SQString::create(this,s)); \
_table(_metamethodsmap)->NewSlot(_metamethods->back(),(int64_t)(_metamethods->size()-1)); \ _table(_metamethodsmap)->NewSlot(_metamethods->back(),(int64_t)(_metamethods->size()-1)); \
} }
@ -77,17 +77,17 @@ bool CompileTypemask(SQIntVec &res,const SQChar *typemask)
return true; return true;
} }
SQTable *CreateDefaultDelegate(SQSharedState *ss,const SQRegFunction *funcz) SQTable *createDefaultDelegate(SQSharedState *ss,const SQRegFunction *funcz)
{ {
int64_t i=0; int64_t i=0;
SQTable *t=SQTable::Create(ss,0); SQTable *t=SQTable::create(ss,0);
while(funcz[i].name!=0){ while(funcz[i].name!=0){
SQNativeClosure *nc = SQNativeClosure::Create(ss,funcz[i].f,0); SQNativeClosure *nc = SQNativeClosure::create(ss,funcz[i].f,0);
nc->_nparamscheck = funcz[i].nparamscheck; nc->_nparamscheck = funcz[i].nparamscheck;
nc->_name = SQString::Create(ss,funcz[i].name); nc->_name = SQString::create(ss,funcz[i].name);
if(funcz[i].typemask && !CompileTypemask(nc->_typecheck,funcz[i].typemask)) if(funcz[i].typemask && !CompileTypemask(nc->_typecheck,funcz[i].typemask))
return NULL; return NULL;
t->NewSlot(SQString::Create(ss,funcz[i].name),nc); t->NewSlot(SQString::create(ss,funcz[i].name),nc);
i++; i++;
} }
return t; return t;
@ -102,7 +102,7 @@ void SQSharedState::Init()
sq_new(_metamethods,SQObjectPtrVec); sq_new(_metamethods,SQObjectPtrVec);
sq_new(_systemstrings,SQObjectPtrVec); sq_new(_systemstrings,SQObjectPtrVec);
sq_new(_types,SQObjectPtrVec); sq_new(_types,SQObjectPtrVec);
_metamethodsmap = SQTable::Create(this,MT_LAST-1); _metamethodsmap = SQTable::create(this,MT_LAST-1);
//adding type strings to avoid memory trashing //adding type strings to avoid memory trashing
//types names //types names
newsysstring(_SC("null")); newsysstring(_SC("null"));
@ -140,19 +140,19 @@ void SQSharedState::Init()
newmetamethod(MM_NEWMEMBER); newmetamethod(MM_NEWMEMBER);
newmetamethod(MM_INHERITED); newmetamethod(MM_INHERITED);
_constructoridx = SQString::Create(this,_SC("constructor")); _constructoridx = SQString::create(this,_SC("constructor"));
_registry = SQTable::Create(this,0); _registry = SQTable::create(this,0);
_consts = SQTable::Create(this,0); _consts = SQTable::create(this,0);
_table_default_delegate = CreateDefaultDelegate(this,_table_default_delegate_funcz); _table_default_delegate = createDefaultDelegate(this,_table_default_delegate_funcz);
_array_default_delegate = CreateDefaultDelegate(this,_array_default_delegate_funcz); _array_default_delegate = createDefaultDelegate(this,_array_default_delegate_funcz);
_string_default_delegate = CreateDefaultDelegate(this,_string_default_delegate_funcz); _string_default_delegate = createDefaultDelegate(this,_string_default_delegate_funcz);
_number_default_delegate = CreateDefaultDelegate(this,_number_default_delegate_funcz); _number_default_delegate = createDefaultDelegate(this,_number_default_delegate_funcz);
_closure_default_delegate = CreateDefaultDelegate(this,_closure_default_delegate_funcz); _closure_default_delegate = createDefaultDelegate(this,_closure_default_delegate_funcz);
_generator_default_delegate = CreateDefaultDelegate(this,_generator_default_delegate_funcz); _generator_default_delegate = createDefaultDelegate(this,_generator_default_delegate_funcz);
_thread_default_delegate = CreateDefaultDelegate(this,_thread_default_delegate_funcz); _thread_default_delegate = createDefaultDelegate(this,_thread_default_delegate_funcz);
_class_default_delegate = CreateDefaultDelegate(this,_class_default_delegate_funcz); _class_default_delegate = createDefaultDelegate(this,_class_default_delegate_funcz);
_instance_default_delegate = CreateDefaultDelegate(this,_instance_default_delegate_funcz); _instance_default_delegate = createDefaultDelegate(this,_instance_default_delegate_funcz);
_weakref_default_delegate = CreateDefaultDelegate(this,_weakref_default_delegate_funcz); _weakref_default_delegate = createDefaultDelegate(this,_weakref_default_delegate_funcz);
} }
SQSharedState::~SQSharedState() SQSharedState::~SQSharedState()
@ -191,19 +191,19 @@ SQSharedState::~SQSharedState()
} }
int64_t SQSharedState::GetMetaMethodIdxByName(const SQObjectPtr &name) int64_t SQSharedState::getMetaMethodIdxByName(const SQObjectPtr &name)
{ {
if(sq_type(name) != OT_STRING) if(sq_type(name) != OT_STRING)
return -1; return -1;
SQObjectPtr ret; SQObjectPtr ret;
if(_table(_metamethodsmap)->Get(name,ret)) { if(_table(_metamethodsmap)->get(name,ret)) {
return _integer(ret); return _integer(ret);
} }
return -1; return -1;
} }
SQChar* SQSharedState::GetScratchPad(int64_t size) SQChar* SQSharedState::getScratchPad(int64_t size)
{ {
int64_t newsize; int64_t newsize;
if(size>0) { if(size>0) {
@ -245,24 +245,24 @@ void RefTable::AddRef(SQObject &obj)
{ {
SQHash mainpos; SQHash mainpos;
RefNode *prev; RefNode *prev;
RefNode *ref = Get(obj,mainpos,&prev,true); RefNode *ref = get(obj,mainpos,&prev,true);
ref->refs++; ref->refs++;
} }
uint64_t RefTable::GetRefCount(SQObject &obj) uint64_t RefTable::getRefCount(SQObject &obj)
{ {
SQHash mainpos; SQHash mainpos;
RefNode *prev; RefNode *prev;
RefNode *ref = Get(obj,mainpos,&prev,true); RefNode *ref = get(obj,mainpos,&prev,true);
return ref->refs; return ref->refs;
} }
SQBool RefTable::Release(SQObject &obj) SQBool RefTable::release(SQObject &obj)
{ {
SQHash mainpos; SQHash mainpos;
RefNode *prev; RefNode *prev;
RefNode *ref = Get(obj,mainpos,&prev,false); RefNode *ref = get(obj,mainpos,&prev,false);
if(ref) { if(ref) {
if(--ref->refs == 0) { if(--ref->refs == 0) {
SQObjectPtr o = ref->obj; SQObjectPtr o = ref->obj;
@ -286,7 +286,7 @@ SQBool RefTable::Release(SQObject &obj)
return SQFalse; return SQFalse;
} }
void RefTable::Resize(uint64_t size) void RefTable::resize(uint64_t size)
{ {
RefNode **oldbucks = _buckets; RefNode **oldbucks = _buckets;
RefNode *t = _nodes; RefNode *t = _nodes;
@ -322,7 +322,7 @@ RefTable::RefNode *RefTable::Add(SQHash mainpos,SQObject &obj)
return newnode; return newnode;
} }
RefTable::RefNode *RefTable::Get(SQObject &obj,SQHash &mainpos,RefNode **prev,bool add) RefTable::RefNode *RefTable::get(SQObject &obj,SQHash &mainpos,RefNode **prev,bool add)
{ {
RefNode *ref; RefNode *ref;
mainpos = ::HashObj(obj)&(_numofslots-1); mainpos = ::HashObj(obj)&(_numofslots-1);
@ -336,7 +336,7 @@ RefTable::RefNode *RefTable::Get(SQObject &obj,SQHash &mainpos,RefNode **prev,bo
if(ref == NULL && add) { if(ref == NULL && add) {
if(_numofslots == _slotused) { if(_numofslots == _slotused) {
assert(_freelist == 0); assert(_freelist == 0);
Resize(_numofslots*2); resize(_numofslots*2);
mainpos = ::HashObj(obj)&(_numofslots-1); mainpos = ::HashObj(obj)&(_numofslots-1);
} }
ref = Add(mainpos,obj); ref = Add(mainpos,obj);
@ -420,11 +420,11 @@ SQString *SQStringTable::Add(const SQChar *news,int64_t len)
_strings[h] = t; _strings[h] = t;
_slotused++; _slotused++;
if (_slotused > _numofslots) /* too crowded? */ if (_slotused > _numofslots) /* too crowded? */
Resize(_numofslots*2); resize(_numofslots*2);
return t; return t;
} }
void SQStringTable::Resize(int64_t size) void SQStringTable::resize(int64_t size)
{ {
int64_t oldsize=_numofslots; int64_t oldsize=_numofslots;
SQString **oldtable=_strings; SQString **oldtable=_strings;
@ -442,7 +442,7 @@ void SQStringTable::Resize(int64_t size)
SQ_FREE(oldtable,oldsize*sizeof(SQString*)); SQ_FREE(oldtable,oldsize*sizeof(SQString*));
} }
void SQStringTable::Remove(SQString *bs) void SQStringTable::remove(SQString *bs)
{ {
SQString *s; SQString *s;
SQString *prev=NULL; SQString *prev=NULL;

View File

@ -19,9 +19,9 @@ struct SQStringTable
SQStringTable(SQSharedState*ss); SQStringTable(SQSharedState*ss);
~SQStringTable(); ~SQStringTable();
SQString *Add(const SQChar *,int64_t len); SQString *Add(const SQChar *,int64_t len);
void Remove(SQString *); void remove(SQString *);
private: private:
void Resize(int64_t size); void resize(int64_t size);
void AllocNodes(int64_t size); void AllocNodes(int64_t size);
SQString **_strings; SQString **_strings;
uint64_t _numofslots; uint64_t _numofslots;
@ -38,13 +38,13 @@ struct RefTable {
RefTable(); RefTable();
~RefTable(); ~RefTable();
void AddRef(SQObject &obj); void AddRef(SQObject &obj);
SQBool Release(SQObject &obj); SQBool release(SQObject &obj);
uint64_t GetRefCount(SQObject &obj); uint64_t getRefCount(SQObject &obj);
void Finalize(); void Finalize();
private: private:
RefNode *Get(SQObject &obj,SQHash &mainpos,RefNode **prev,bool add); RefNode *get(SQObject &obj,SQHash &mainpos,RefNode **prev,bool add);
RefNode *Add(SQHash mainpos,SQObject &obj); RefNode *Add(SQHash mainpos,SQObject &obj);
void Resize(uint64_t size); void resize(uint64_t size);
void AllocNodes(uint64_t size); void AllocNodes(uint64_t size);
uint64_t _numofslots; uint64_t _numofslots;
uint64_t _slotused; uint64_t _slotused;
@ -54,7 +54,7 @@ private:
}; };
#define ADD_STRING(ss,str,len) ss->_stringtable->Add(str,len) #define ADD_STRING(ss,str,len) ss->_stringtable->Add(str,len)
#define REMOVE_STRING(ss,bstr) ss->_stringtable->Remove(bstr) #define REMOVE_STRING(ss,bstr) ss->_stringtable->remove(bstr)
struct SQObjectPtr; struct SQObjectPtr;
@ -64,8 +64,8 @@ struct SQSharedState
~SQSharedState(); ~SQSharedState();
void Init(); void Init();
public: public:
SQChar* GetScratchPad(int64_t size); SQChar* getScratchPad(int64_t size);
int64_t GetMetaMethodIdxByName(const SQObjectPtr &name); int64_t getMetaMethodIdxByName(const SQObjectPtr &name);
SQObjectPtrVec *_metamethods; SQObjectPtrVec *_metamethods;
SQObjectPtr _metamethodsmap; SQObjectPtr _metamethodsmap;
SQObjectPtrVec *_systemstrings; SQObjectPtrVec *_systemstrings;
@ -109,8 +109,8 @@ private:
int64_t _scratchpadsize; int64_t _scratchpadsize;
}; };
#define _sp(s) (_sharedstate->GetScratchPad(s)) #define _sp(s) (_sharedstate->getScratchPad(s))
#define _spval (_sharedstate->GetScratchPad(-1)) #define _spval (_sharedstate->getScratchPad(-1))
#define _table_ddel _table(_sharedstate->_table_default_delegate) #define _table_ddel _table(_sharedstate->_table_default_delegate)
#define _array_ddel _table(_sharedstate->_array_default_delegate) #define _array_ddel _table(_sharedstate->_array_default_delegate)

View File

@ -16,14 +16,14 @@ inline SQHash _hashstr (const SQChar *s, size_t l)
return h; return h;
} }
struct SQString : public SQRefCounted struct SQString : public rabbit::RefCounted
{ {
SQString(){} SQString(){}
~SQString(){} ~SQString(){}
public: public:
static SQString *Create(SQSharedState *ss, const SQChar *, int64_t len = -1 ); static SQString *create(SQSharedState *ss, const SQChar *, int64_t len = -1 );
int64_t Next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval); int64_t next(const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval);
void Release(); void release();
SQSharedState *_sharedstate; SQSharedState *_sharedstate;
SQString *_next; //chain for the string table SQString *_next; //chain for the string table
int64_t _len; int64_t _len;

View File

@ -12,19 +12,19 @@
#include <rabbit/sqfuncproto.hpp> #include <rabbit/sqfuncproto.hpp>
#include <rabbit/sqclosure.hpp> #include <rabbit/sqclosure.hpp>
SQTable::SQTable(SQSharedState *ss,int64_t nInitialSize) SQTable::SQTable(SQSharedState *ss,int64_t nInitialsize)
{ {
int64_t pow2size=MINPOWER2; int64_t pow2size=MINPOWER2;
while(nInitialSize>pow2size)pow2size=pow2size<<1; while(nInitialsize>pow2size)pow2size=pow2size<<1;
AllocNodes(pow2size); AllocNodes(pow2size);
_usednodes = 0; _usednodes = 0;
_delegate = NULL; _delegate = NULL;
} }
void SQTable::Remove(const SQObjectPtr &key) void SQTable::remove(const SQObjectPtr &key)
{ {
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1)); _HashNode *n = _get(key, HashObj(key) & (_numofnodes - 1));
if (n) { if (n) {
n->val.Null(); n->val.Null();
n->key.Null(); n->key.Null();
@ -33,15 +33,15 @@ void SQTable::Remove(const SQObjectPtr &key)
} }
} }
void SQTable::AllocNodes(int64_t nSize) void SQTable::AllocNodes(int64_t nsize)
{ {
_HashNode *nodes=(_HashNode *)SQ_MALLOC(sizeof(_HashNode)*nSize); _HashNode *nodes=(_HashNode *)SQ_MALLOC(sizeof(_HashNode)*nsize);
for(int64_t i=0;i<nSize;i++){ for(int64_t i=0;i<nsize;i++){
_HashNode &n = nodes[i]; _HashNode &n = nodes[i];
new (&n) _HashNode; new (&n) _HashNode;
n.next=NULL; n.next=NULL;
} }
_numofnodes=nSize; _numofnodes=nsize;
_nodes=nodes; _nodes=nodes;
_firstfree=&_nodes[_numofnodes-1]; _firstfree=&_nodes[_numofnodes-1];
} }
@ -73,9 +73,9 @@ void SQTable::Rehash(bool force)
SQ_FREE(nold,oldsize*sizeof(_HashNode)); SQ_FREE(nold,oldsize*sizeof(_HashNode));
} }
SQTable *SQTable::Clone() SQTable *SQTable::clone()
{ {
SQTable *nt=Create(NULL,_numofnodes); SQTable *nt=create(NULL,_numofnodes);
#ifdef _FAST_CLONE #ifdef _FAST_CLONE
_HashNode *basesrc = _nodes; _HashNode *basesrc = _nodes;
_HashNode *basedst = nt->_nodes; _HashNode *basedst = nt->_nodes;
@ -100,19 +100,19 @@ SQTable *SQTable::Clone()
#else #else
int64_t ridx=0; int64_t ridx=0;
SQObjectPtr key,val; SQObjectPtr key,val;
while((ridx=Next(true,ridx,key,val))!=-1){ while((ridx=next(true,ridx,key,val))!=-1){
nt->NewSlot(key,val); nt->NewSlot(key,val);
} }
#endif #endif
nt->SetDelegate(_delegate); nt->setDelegate(_delegate);
return nt; return nt;
} }
bool SQTable::Get(const SQObjectPtr &key,SQObjectPtr &val) bool SQTable::get(const SQObjectPtr &key,SQObjectPtr &val)
{ {
if(sq_type(key) == OT_NULL) if(sq_type(key) == OT_NULL)
return false; return false;
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1)); _HashNode *n = _get(key, HashObj(key) & (_numofnodes - 1));
if (n) { if (n) {
val = _realval(n->val); val = _realval(n->val);
return true; return true;
@ -123,7 +123,7 @@ bool SQTable::NewSlot(const SQObjectPtr &key,const SQObjectPtr &val)
{ {
assert(sq_type(key) != OT_NULL); assert(sq_type(key) != OT_NULL);
SQHash h = HashObj(key) & (_numofnodes - 1); SQHash h = HashObj(key) & (_numofnodes - 1);
_HashNode *n = _Get(key, h); _HashNode *n = _get(key, h);
if (n) { if (n) {
n->val = val; n->val = val;
return false; return false;
@ -176,9 +176,9 @@ bool SQTable::NewSlot(const SQObjectPtr &key,const SQObjectPtr &val)
return NewSlot(key, val); return NewSlot(key, val);
} }
int64_t SQTable::Next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval) int64_t SQTable::next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval)
{ {
int64_t idx = (int64_t)TranslateIndex(refpos); int64_t idx = (int64_t)translateIndex(refpos);
while (idx < _numofnodes) { while (idx < _numofnodes) {
if(sq_type(_nodes[idx].key) != OT_NULL) { if(sq_type(_nodes[idx].key) != OT_NULL) {
//first found //first found
@ -195,9 +195,9 @@ int64_t SQTable::Next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &o
} }
bool SQTable::Set(const SQObjectPtr &key, const SQObjectPtr &val) bool SQTable::set(const SQObjectPtr &key, const SQObjectPtr &val)
{ {
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1)); _HashNode *n = _get(key, HashObj(key) & (_numofnodes - 1));
if (n) { if (n) {
n->val = val; n->val = val;
return true; return true;
@ -213,7 +213,7 @@ void SQTable::_ClearNodes()
void SQTable::Finalize() void SQTable::Finalize()
{ {
_ClearNodes(); _ClearNodes();
SetDelegate(NULL); setDelegate(NULL);
} }
void SQTable::Clear() void SQTable::Clear()

View File

@ -44,27 +44,27 @@ private:
int64_t _usednodes; int64_t _usednodes;
/////////////////////////// ///////////////////////////
void AllocNodes(int64_t nSize); void AllocNodes(int64_t nsize);
void Rehash(bool force); void Rehash(bool force);
SQTable(SQSharedState *ss, int64_t nInitialSize); SQTable(SQSharedState *ss, int64_t nInitialsize);
void _ClearNodes(); void _ClearNodes();
public: public:
static SQTable* Create(SQSharedState *ss,int64_t nInitialSize) static SQTable* create(SQSharedState *ss,int64_t nInitialsize)
{ {
SQTable *newtable = (SQTable*)SQ_MALLOC(sizeof(SQTable)); SQTable *newtable = (SQTable*)SQ_MALLOC(sizeof(SQTable));
new (newtable) SQTable(ss, nInitialSize); new (newtable) SQTable(ss, nInitialsize);
newtable->_delegate = NULL; newtable->_delegate = NULL;
return newtable; return newtable;
} }
void Finalize(); void Finalize();
SQTable *Clone(); SQTable *clone();
~SQTable() ~SQTable()
{ {
SetDelegate(NULL); setDelegate(NULL);
for (int64_t i = 0; i < _numofnodes; i++) _nodes[i].~_HashNode(); for (int64_t i = 0; i < _numofnodes; i++) _nodes[i].~_HashNode();
SQ_FREE(_nodes, _numofnodes * sizeof(_HashNode)); SQ_FREE(_nodes, _numofnodes * sizeof(_HashNode));
} }
inline _HashNode *_Get(const SQObjectPtr &key,SQHash hash) inline _HashNode *_get(const SQObjectPtr &key,SQHash hash)
{ {
_HashNode *n = &_nodes[hash]; _HashNode *n = &_nodes[hash];
do{ do{
@ -75,7 +75,7 @@ public:
return NULL; return NULL;
} }
//for compiler use //for compiler use
inline bool GetStr(const SQChar* key,int64_t keylen,SQObjectPtr &val) inline bool getStr(const SQChar* key,int64_t keylen,SQObjectPtr &val)
{ {
SQHash hash = _hashstr(key,keylen); SQHash hash = _hashstr(key,keylen);
_HashNode *n = &_nodes[hash & (_numofnodes - 1)]; _HashNode *n = &_nodes[hash & (_numofnodes - 1)];
@ -92,16 +92,16 @@ public:
} }
return false; return false;
} }
bool Get(const SQObjectPtr &key,SQObjectPtr &val); bool get(const SQObjectPtr &key,SQObjectPtr &val);
void Remove(const SQObjectPtr &key); void remove(const SQObjectPtr &key);
bool Set(const SQObjectPtr &key, const SQObjectPtr &val); bool set(const SQObjectPtr &key, const SQObjectPtr &val);
//returns true if a new slot has been created false if it was already present //returns true if a new slot has been created false if it was already present
bool NewSlot(const SQObjectPtr &key,const SQObjectPtr &val); bool NewSlot(const SQObjectPtr &key,const SQObjectPtr &val);
int64_t Next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval); int64_t next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval);
int64_t CountUsed(){ return _usednodes;} int64_t CountUsed(){ return _usednodes;}
void Clear(); void Clear();
void Release() void release()
{ {
sq_delete(this, SQTable); sq_delete(this, SQTable);
} }

View File

@ -11,8 +11,9 @@ void *sq_vm_malloc(uint64_t size);
void *sq_vm_realloc(void *p,uint64_t oldsize,uint64_t size); void *sq_vm_realloc(void *p,uint64_t oldsize,uint64_t size);
void sq_vm_free(void *p,uint64_t size); void sq_vm_free(void *p,uint64_t size);
#define sq_new(__ptr,__type) {__ptr=(__type *)sq_vm_malloc(sizeof(__type));new (__ptr) __type;} #define sq_new(__ptr,__type) {__ptr=(__type *)sq_vm_malloc(sizeof(__type));new ((char*)__ptr) __type;}
#define sq_delete(__ptr,__type) {__ptr->~__type();sq_vm_free(__ptr,sizeof(__type));} #define sq_delete(__ptr,__type) {((__type*)__ptr)->~__type();sq_vm_free(__ptr,sizeof(__type));}
#define SQ_MALLOC(__size) sq_vm_malloc((__size)); #define SQ_MALLOC(__size) sq_vm_malloc((__size));
#define SQ_FREE(__ptr,__size) sq_vm_free((__ptr),(__size)); #define SQ_FREE(__ptr,__size) sq_vm_free((__ptr),(__size));
#define SQ_REALLOC(__ptr,__oldsize,__size) sq_vm_realloc((__ptr),(__oldsize),(__size)); #define SQ_REALLOC(__ptr,__oldsize,__size) sq_vm_realloc((__ptr),(__oldsize),(__size));

View File

@ -15,7 +15,7 @@
#include <rabbit/sqstring.hpp> #include <rabbit/sqstring.hpp>
#include <rabbit/sqtable.hpp> #include <rabbit/sqtable.hpp>
#include <rabbit/UserData.hpp> #include <rabbit/UserData.hpp>
#include <rabbit/sqarray.hpp> #include <rabbit/Array.hpp>
#include <rabbit/sqclass.hpp> #include <rabbit/sqclass.hpp>
#define TOP() (_stack._vals[_top-1]) #define TOP() (_stack._vals[_top-1])
@ -38,7 +38,7 @@ bool SQVM::BW_OP(uint64_t op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObje
default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; } default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; }
} }
} }
else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),GetTypeName(o1),GetTypeName(o2)); return false;} else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),getTypeName(o1),getTypeName(o2)); return false;}
trg = res; trg = res;
return true; return true;
} }
@ -167,12 +167,12 @@ bool SQVM::ArithMetaMethod(int64_t op,const SQObjectPtr &o1,const SQObjectPtr &o
if(is_delegable(o1) && _delegable(o1)->_delegate) { if(is_delegable(o1) && _delegable(o1)->_delegate) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(o1)->GetMetaMethod(this, mm, closure)) { if(_delegable(o1)->getMetaMethod(this, mm, closure)) {
Push(o1);Push(o2); Push(o1);Push(o2);
return CallMetaMethod(closure,mm,2,dest); return CallMetaMethod(closure,mm,2,dest);
} }
} }
Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2)); Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,getTypeName(o1),getTypeName(o2));
return false; return false;
} }
@ -191,7 +191,7 @@ bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
case OT_INSTANCE: case OT_INSTANCE:
if(_delegable(o)->_delegate) { if(_delegable(o)->_delegate) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(o)->GetMetaMethod(this, MT_UNM, closure)) { if(_delegable(o)->getMetaMethod(this, MT_UNM, closure)) {
Push(o); Push(o);
if(!CallMetaMethod(closure, MT_UNM, 1, temp_reg)) return false; if(!CallMetaMethod(closure, MT_UNM, 1, temp_reg)) return false;
_Swap(trg,temp_reg); _Swap(trg,temp_reg);
@ -201,7 +201,7 @@ bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
} }
default:break; //shutup compiler default:break; //shutup compiler
} }
Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o)); Raise_Error(_SC("attempt to negate a %s"), getTypeName(o));
return false; return false;
} }
@ -224,7 +224,7 @@ bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,int64_t &result)
case OT_INSTANCE: case OT_INSTANCE:
if(_delegable(o1)->_delegate) { if(_delegable(o1)->_delegate) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(o1)->GetMetaMethod(this, MT_CMP, closure)) { if(_delegable(o1)->getMetaMethod(this, MT_CMP, closure)) {
Push(o1);Push(o2); Push(o1);Push(o2);
if(CallMetaMethod(closure,MT_CMP,2,res)) { if(CallMetaMethod(closure,MT_CMP,2,res)) {
if(sq_type(res) != OT_INTEGER) { if(sq_type(res) != OT_INTEGER) {
@ -303,7 +303,7 @@ bool SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res)
case OT_INSTANCE: case OT_INSTANCE:
if(_delegable(o)->_delegate) { if(_delegable(o)->_delegate) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(o)->GetMetaMethod(this, MT_TOSTRING, closure)) { if(_delegable(o)->getMetaMethod(this, MT_TOSTRING, closure)) {
Push(o); Push(o);
if(CallMetaMethod(closure,MT_TOSTRING,1,res)) { if(CallMetaMethod(closure,MT_TOSTRING,1,res)) {
if(sq_type(res) == OT_STRING) if(sq_type(res) == OT_STRING)
@ -315,9 +315,9 @@ bool SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res)
} }
} }
default: default:
scsprintf(_sp(sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR)),sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR),_SC("(%s : 0x%p)"),GetTypeName(o),(void*)_rawval(o)); scsprintf(_sp(sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR)),sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR),_SC("(%s : 0x%p)"),getTypeName(o),(void*)_rawval(o));
} }
res = SQString::Create(_ss(this),_spval); res = SQString::create(_ss(this),_spval);
return true; return true;
} }
@ -331,7 +331,7 @@ bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &
SQChar *s = _sp(sq_rsl(l + ol + 1)); SQChar *s = _sp(sq_rsl(l + ol + 1));
memcpy(s, _stringval(a), sq_rsl(l)); memcpy(s, _stringval(a), sq_rsl(l));
memcpy(s + l, _stringval(b), sq_rsl(ol)); memcpy(s + l, _stringval(b), sq_rsl(ol));
dest = SQString::Create(_ss(this), _spval, l + ol); dest = SQString::create(_ss(this), _spval, l + ol);
return true; return true;
} }
@ -339,12 +339,12 @@ bool SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
{ {
if(is_delegable(obj1) && _delegable(obj1)->_delegate) { if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(obj1)->GetMetaMethod(this, MT_TYPEOF, closure)) { if(_delegable(obj1)->getMetaMethod(this, MT_TYPEOF, closure)) {
Push(obj1); Push(obj1);
return CallMetaMethod(closure,MT_TYPEOF,1,dest); return CallMetaMethod(closure,MT_TYPEOF,1,dest);
} }
} }
dest = SQString::Create(_ss(this),GetTypeName(obj1)); dest = SQString::create(_ss(this),getTypeName(obj1));
return true; return true;
} }
@ -358,7 +358,7 @@ bool SQVM::Init(SQVM *friendvm, int64_t stacksize)
_stackbase = 0; _stackbase = 0;
_top = 0; _top = 0;
if(!friendvm) { if(!friendvm) {
_roottable = SQTable::Create(_ss(this), 0); _roottable = SQTable::create(_ss(this), 0);
sq_base_register(this); sq_base_register(this);
} }
else { else {
@ -391,10 +391,10 @@ bool SQVM::StartCall(SQClosure *closure,int64_t target,int64_t args,int64_t stac
//dumpstack(stackbase); //dumpstack(stackbase);
int64_t nvargs = nargs - paramssize; int64_t nvargs = nargs - paramssize;
SQArray *arr = SQArray::Create(_ss(this),nvargs); rabbit::Array *arr = rabbit::Array::create(_ss(this),nvargs);
int64_t pbase = stackbase+paramssize; int64_t pbase = stackbase+paramssize;
for(int64_t n = 0; n < nvargs; n++) { for(int64_t n = 0; n < nvargs; n++) {
arr->_values[n] = _stack._vals[pbase]; (*arr)[n] = _stack._vals[pbase];
_stack._vals[pbase].Null(); _stack._vals[pbase].Null();
pbase++; pbase++;
@ -433,7 +433,7 @@ bool SQVM::StartCall(SQClosure *closure,int64_t target,int64_t args,int64_t stac
if (closure->_function->_bgenerator) { if (closure->_function->_bgenerator) {
SQFunctionProto *f = closure->_function; SQFunctionProto *f = closure->_function;
SQGenerator *gen = SQGenerator::Create(_ss(this), closure); SQGenerator *gen = SQGenerator::create(_ss(this), closure);
if(!gen->Yield(this,f->_stacksize)) if(!gen->Yield(this,f->_stacksize))
return false; return false;
SQObjectPtr temp; SQObjectPtr temp;
@ -491,9 +491,9 @@ bool SQVM::PLOCAL_INC(int64_t op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPt
bool SQVM::DerefInc(int64_t op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix,int64_t selfidx) bool SQVM::DerefInc(int64_t op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix,int64_t selfidx)
{ {
SQObjectPtr tmp, tself = self, tkey = key; SQObjectPtr tmp, tself = self, tkey = key;
if (!Get(tself, tkey, tmp, 0, selfidx)) { return false; } if (!get(tself, tkey, tmp, 0, selfidx)) { return false; }
_RET_ON_FAIL(ARITH_OP( op , target, tmp, incr)) _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
if (!Set(tself, tkey, target,selfidx)) { return false; } if (!set(tself, tkey, target,selfidx)) { return false; }
if (postfix) target = tmp; if (postfix) target = tmp;
return true; return true;
} }
@ -523,29 +523,29 @@ bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
int64_t nrefidx; int64_t nrefidx;
switch(sq_type(o1)) { switch(sq_type(o1)) {
case OT_TABLE: case OT_TABLE:
if((nrefidx = _table(o1)->Next(false,o4, o2, o3)) == -1) _FINISH(exitpos); if((nrefidx = _table(o1)->next(false,o4, o2, o3)) == -1) _FINISH(exitpos);
o4 = (int64_t)nrefidx; _FINISH(1); o4 = (int64_t)nrefidx; _FINISH(1);
case OT_ARRAY: case OT_ARRAY:
if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(exitpos); if((nrefidx = _array(o1)->next(o4, o2, o3)) == -1) _FINISH(exitpos);
o4 = (int64_t) nrefidx; _FINISH(1); o4 = (int64_t) nrefidx; _FINISH(1);
case OT_STRING: case OT_STRING:
if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos); if((nrefidx = _string(o1)->next(o4, o2, o3)) == -1)_FINISH(exitpos);
o4 = (int64_t)nrefidx; _FINISH(1); o4 = (int64_t)nrefidx; _FINISH(1);
case OT_CLASS: case OT_CLASS:
if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos); if((nrefidx = _class(o1)->next(o4, o2, o3)) == -1)_FINISH(exitpos);
o4 = (int64_t)nrefidx; _FINISH(1); o4 = (int64_t)nrefidx; _FINISH(1);
case OT_USERDATA: case OT_USERDATA:
case OT_INSTANCE: case OT_INSTANCE:
if(_delegable(o1)->_delegate) { if(_delegable(o1)->_delegate) {
SQObjectPtr itr; SQObjectPtr itr;
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(o1)->GetMetaMethod(this, MT_NEXTI, closure)) { if(_delegable(o1)->getMetaMethod(this, MT_NEXTI, closure)) {
Push(o1); Push(o1);
Push(o4); Push(o4);
if(CallMetaMethod(closure, MT_NEXTI, 2, itr)) { if(CallMetaMethod(closure, MT_NEXTI, 2, itr)) {
o4 = o2 = itr; o4 = o2 = itr;
if(sq_type(itr) == OT_NULL) _FINISH(exitpos); if(sq_type(itr) == OT_NULL) _FINISH(exitpos);
if(!Get(o1, itr, o3, 0, DONT_FALL_BACK)) { if(!get(o1, itr, o3, 0, DONT_FALL_BACK)) {
Raise_Error(_SC("_nexti returned an invalid idx")); // cloud be changed Raise_Error(_SC("_nexti returned an invalid idx")); // cloud be changed
return false; return false;
} }
@ -572,7 +572,7 @@ bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
_FINISH(0); _FINISH(0);
} }
default: default:
Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1)); Raise_Error(_SC("cannot iterate %s"), getTypeName(o1));
} }
return false; //cannot be hit(just to avoid warnings) return false; //cannot be hit(just to avoid warnings)
} }
@ -586,7 +586,7 @@ bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func) bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
{ {
int64_t nouters; int64_t nouters;
SQClosure *closure = SQClosure::Create(_ss(this), func,_table(_roottable)->GetWeakRef(OT_TABLE)); SQClosure *closure = SQClosure::create(_ss(this), func,_table(_roottable)->getWeakRef(OT_TABLE));
if((nouters = func->_noutervalues)) { if((nouters = func->_noutervalues)) {
for(int64_t i = 0; i<nouters; i++) { for(int64_t i = 0; i<nouters; i++) {
SQOuterVar &v = func->_outervalues[i]; SQOuterVar &v = func->_outervalues[i];
@ -618,13 +618,13 @@ bool SQVM::CLASS_OP(SQObjectPtr &target,int64_t baseclass,int64_t attributes)
SQClass *base = NULL; SQClass *base = NULL;
SQObjectPtr attrs; SQObjectPtr attrs;
if(baseclass != -1) { if(baseclass != -1) {
if(sq_type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; } if(sq_type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),getTypeName(_stack._vals[_stackbase+baseclass])); return false; }
base = _class(_stack._vals[_stackbase + baseclass]); base = _class(_stack._vals[_stackbase + baseclass]);
} }
if(attributes != MAX_FUNC_STACKSIZE) { if(attributes != MAX_FUNC_STACKSIZE) {
attrs = _stack._vals[_stackbase+attributes]; attrs = _stack._vals[_stackbase+attributes];
} }
target = SQClass::Create(_ss(this),base); target = SQClass::create(_ss(this),base);
if(sq_type(_class(target)->_metamethods[MT_INHERITED]) != OT_NULL) { if(sq_type(_class(target)->_metamethods[MT_INHERITED]) != OT_NULL) {
int nparams = 2; int nparams = 2;
SQObjectPtr ret; SQObjectPtr ret;
@ -763,7 +763,7 @@ exception_restore:
continue; continue;
case OT_CLASS:{ case OT_CLASS:{
SQObjectPtr inst; SQObjectPtr inst;
_GUARD(CreateClassInstance(_class(clo),inst,clo)); _GUARD(createClassInstance(_class(clo),inst,clo));
if(sarg0 != -1) { if(sarg0 != -1) {
STK(arg0) = inst; STK(arg0) = inst;
} }
@ -788,7 +788,7 @@ exception_restore:
case OT_USERDATA: case OT_USERDATA:
case OT_INSTANCE:{ case OT_INSTANCE:{
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(clo)->_delegate && _delegable(clo)->GetMetaMethod(this,MT_CALL,closure)) { if(_delegable(clo)->_delegate && _delegable(clo)->getMetaMethod(this,MT_CALL,closure)) {
Push(clo); Push(clo);
for (int64_t i = 0; i < arg3; i++) Push(STK(arg2 + i)); for (int64_t i = 0; i < arg3; i++) Push(STK(arg2 + i));
if(!CallMetaMethod(closure, MT_CALL, arg3+1, clo)) SQ_THROW(); if(!CallMetaMethod(closure, MT_CALL, arg3+1, clo)) SQ_THROW();
@ -798,11 +798,11 @@ exception_restore:
break; break;
} }
//Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo)); //Raise_Error(_SC("attempt to call '%s'"), getTypeName(clo));
//SQ_THROW(); //SQ_THROW();
} }
default: default:
Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo)); Raise_Error(_SC("attempt to call '%s'"), getTypeName(clo));
SQ_THROW(); SQ_THROW();
} }
} }
@ -811,7 +811,7 @@ exception_restore:
case _OP_PREPCALLK: { case _OP_PREPCALLK: {
SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1); SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1);
SQObjectPtr &o = STK(arg2); SQObjectPtr &o = STK(arg2);
if (!Get(o, key, temp_reg,0,arg2)) { if (!get(o, key, temp_reg,0,arg2)) {
SQ_THROW(); SQ_THROW();
} }
STK(arg3) = o; STK(arg3) = o;
@ -819,7 +819,7 @@ exception_restore:
} }
continue; continue;
case _OP_GETK: case _OP_GETK:
if (!Get(STK(arg2), ci->_literals[arg1], temp_reg, 0,arg2)) { SQ_THROW();} if (!get(STK(arg2), ci->_literals[arg1], temp_reg, 0,arg2)) { SQ_THROW();}
_Swap(TARGET,temp_reg);//TARGET = temp_reg; _Swap(TARGET,temp_reg);//TARGET = temp_reg;
continue; continue;
case _OP_MOVE: TARGET = STK(arg1); continue; case _OP_MOVE: TARGET = STK(arg1); continue;
@ -829,11 +829,11 @@ exception_restore:
continue; continue;
case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue; case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
case _OP_SET: case _OP_SET:
if (!Set(STK(arg1), STK(arg2), STK(arg3),arg1)) { SQ_THROW(); } if (!set(STK(arg1), STK(arg2), STK(arg3),arg1)) { SQ_THROW(); }
if (arg0 != 0xFF) TARGET = STK(arg3); if (arg0 != 0xFF) TARGET = STK(arg3);
continue; continue;
case _OP_GET: case _OP_GET:
if (!Get(STK(arg1), STK(arg2), temp_reg, 0,arg1)) { SQ_THROW(); } if (!get(STK(arg1), STK(arg2), temp_reg, 0,arg1)) { SQ_THROW(); }
_Swap(TARGET,temp_reg);//TARGET = temp_reg; _Swap(TARGET,temp_reg);//TARGET = temp_reg;
continue; continue;
case _OP_EQ:{ case _OP_EQ:{
@ -865,7 +865,7 @@ exception_restore:
continue; continue;
case _OP_LOADNULLS:{ for(int32_t n=0; n < arg1; n++) STK(arg0+n).Null(); }continue; case _OP_LOADNULLS:{ for(int32_t n=0; n < arg1; n++) STK(arg0+n).Null(); }continue;
case _OP_LOADROOT: { case _OP_LOADROOT: {
SQWeakRef *w = _closure(ci->_closure)->_root; rabbit::WeakRef *w = _closure(ci->_closure)->_root;
if(sq_type(w->_obj) != OT_NULL) { if(sq_type(w->_obj) != OT_NULL) {
TARGET = w->_obj; TARGET = w->_obj;
} else { } else {
@ -899,8 +899,8 @@ exception_restore:
continue; continue;
case _OP_NEWOBJ: case _OP_NEWOBJ:
switch(arg3) { switch(arg3) {
case NOT_TABLE: TARGET = SQTable::Create(_ss(this), arg1); continue; case NOT_TABLE: TARGET = SQTable::create(_ss(this), arg1); continue;
case NOT_ARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue; case NOT_ARRAY: TARGET = rabbit::Array::create(_ss(this), 0); _array(TARGET)->reserve(arg1); continue;
case NOT_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue; case NOT_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
default: assert(0); continue; default: assert(0); continue;
} }
@ -932,7 +932,7 @@ exception_restore:
default: val._type = OT_INTEGER; assert(0); break; default: val._type = OT_INTEGER; assert(0); break;
} }
_array(STK(arg0))->Append(val); continue; _array(STK(arg0))->append(val); continue;
} }
case _OP_COMPARITH: { case _OP_COMPARITH: {
int64_t selfidx = (((uint64_t)arg1&0xFFFF0000)>>16); int64_t selfidx = (((uint64_t)arg1&0xFFFF0000)>>16);
@ -963,10 +963,10 @@ exception_restore:
} continue; } continue;
case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET)) continue; case _OP_CMP: _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET)) continue;
case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, GET_FLAG_DO_NOT_RAISE_ERROR | GET_FLAG_RAW, DONT_FALL_BACK) ? true : false; continue; case _OP_EXISTS: TARGET = get(STK(arg1), STK(arg2), temp_reg, GET_FLAG_DO_NOT_RAISE_ERROR | GET_FLAG_RAW, DONT_FALL_BACK) ? true : false; continue;
case _OP_INSTANCEOF: case _OP_INSTANCEOF:
if(sq_type(STK(arg1)) != OT_CLASS) if(sq_type(STK(arg1)) != OT_CLASS)
{Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();} {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),getTypeName(STK(arg1)),getTypeName(STK(arg2))); SQ_THROW();}
TARGET = (sq_type(STK(arg2)) == OT_INSTANCE) ? (_instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?true:false) : false; TARGET = (sq_type(STK(arg2)) == OT_INSTANCE) ? (_instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?true:false) : false;
continue; continue;
case _OP_AND: case _OP_AND:
@ -989,7 +989,7 @@ exception_restore:
TARGET = int64_t(~t); TARGET = int64_t(~t);
continue; continue;
} }
Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1))); Raise_Error(_SC("attempt to perform a bitwise op on a %s"), getTypeName(STK(arg1)));
SQ_THROW(); SQ_THROW();
case _OP_CLOSURE: { case _OP_CLOSURE: {
SQClosure *c = ci->_closure._unVal.pClosure; SQClosure *c = ci->_closure._unVal.pClosure;
@ -1004,7 +1004,7 @@ exception_restore:
traps -= ci->_etraps; traps -= ci->_etraps;
if(sarg1 != MAX_FUNC_STACKSIZE) _Swap(STK(arg1),temp_reg);//STK(arg1) = temp_reg; if(sarg1 != MAX_FUNC_STACKSIZE) _Swap(STK(arg1),temp_reg);//STK(arg1) = temp_reg;
} }
else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();} else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), getTypeName(ci->_generator)); SQ_THROW();}
if(Return(arg0, arg1, temp_reg)){ if(Return(arg0, arg1, temp_reg)){
assert(traps == 0); assert(traps == 0);
outres = temp_reg; outres = temp_reg;
@ -1014,7 +1014,7 @@ exception_restore:
} }
continue; continue;
case _OP_RESUME: case _OP_RESUME:
if(sq_type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();} if(sq_type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), getTypeName(STK(arg1))); SQ_THROW();}
_GUARD(_generator(STK(arg1))->Resume(this, TARGET)); _GUARD(_generator(STK(arg1))->Resume(this, TARGET));
traps += ci->_etraps; traps += ci->_etraps;
continue; continue;
@ -1027,7 +1027,7 @@ exception_restore:
if(_generator(STK(arg0))->_state == SQGenerator::eDead) if(_generator(STK(arg0))->_state == SQGenerator::eDead)
ci->_ip += (sarg1 - 1); ci->_ip += (sarg1 - 1);
continue; continue;
case _OP_CLONE: _GUARD(Clone(STK(arg1), TARGET)); continue; case _OP_CLONE: _GUARD(clone(STK(arg1), TARGET)); continue;
case _OP_TYPEOF: _GUARD(TypeOf(STK(arg1), TARGET)) continue; case _OP_TYPEOF: _GUARD(TypeOf(STK(arg1), TARGET)) continue;
case _OP_PUSHTRAP:{ case _OP_PUSHTRAP:{
SQInstruction *_iv = _closure(ci->_closure)->_function->_instructions; SQInstruction *_iv = _closure(ci->_closure)->_function->_instructions;
@ -1102,10 +1102,10 @@ exception_trap:
assert(0); assert(0);
} }
bool SQVM::CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor) bool SQVM::createClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor)
{ {
inst = theclass->CreateInstance(); inst = theclass->createInstance();
if(!theclass->GetConstructor(constructor)) { if(!theclass->getConstructor(constructor)) {
constructor.Null(); constructor.Null();
} }
return true; return true;
@ -1129,13 +1129,13 @@ void SQVM::CallDebugHook(int64_t type,int64_t forcedline)
if(_debughook_native) { if(_debughook_native) {
const SQChar *src = sq_type(func->_sourcename) == OT_STRING?_stringval(func->_sourcename):NULL; const SQChar *src = sq_type(func->_sourcename) == OT_STRING?_stringval(func->_sourcename):NULL;
const SQChar *fname = sq_type(func->_name) == OT_STRING?_stringval(func->_name):NULL; const SQChar *fname = sq_type(func->_name) == OT_STRING?_stringval(func->_name):NULL;
int64_t line = forcedline?forcedline:func->GetLine(ci->_ip); int64_t line = forcedline?forcedline:func->getLine(ci->_ip);
_debughook_native(this,type,src,line,fname); _debughook_native(this,type,src,line,fname);
} }
else { else {
SQObjectPtr temp_reg; SQObjectPtr temp_reg;
int64_t nparams=5; int64_t nparams=5;
Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name); Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->getLine(ci->_ip)); Push(func->_name);
Call(_debughook_closure,nparams,_top-nparams,temp_reg,SQFalse); Call(_debughook_closure,nparams,_top-nparams,temp_reg,SQFalse);
Pop(nparams); Pop(nparams);
} }
@ -1232,20 +1232,20 @@ bool SQVM::TailCall(SQClosure *closure, int64_t parambase,int64_t nparams)
#define FALLBACK_NO_MATCH 1 #define FALLBACK_NO_MATCH 1
#define FALLBACK_ERROR 2 #define FALLBACK_ERROR 2
bool SQVM::Get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &dest, uint64_t getflags, int64_t selfidx) bool SQVM::get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &dest, uint64_t getflags, int64_t selfidx)
{ {
switch(sq_type(self)){ switch(sq_type(self)){
case OT_TABLE: case OT_TABLE:
if(_table(self)->Get(key,dest))return true; if(_table(self)->get(key,dest))return true;
break; break;
case OT_ARRAY: case OT_ARRAY:
if (sq_isnumeric(key)) { if (_array(self)->Get(tointeger(key), dest)) { return true; } if ((getflags & GET_FLAG_DO_NOT_RAISE_ERROR) == 0) Raise_IdxError(key); return false; } if (sq_isnumeric(key)) { if (_array(self)->get(tointeger(key), dest)) { return true; } if ((getflags & GET_FLAG_DO_NOT_RAISE_ERROR) == 0) Raise_IdxError(key); return false; }
break; break;
case OT_INSTANCE: case OT_INSTANCE:
if(_instance(self)->Get(key,dest)) return true; if(_instance(self)->get(key,dest)) return true;
break; break;
case OT_CLASS: case OT_CLASS:
if(_class(self)->Get(key,dest)) return true; if(_class(self)->get(key,dest)) return true;
break; break;
case OT_STRING: case OT_STRING:
if(sq_isnumeric(key)){ if(sq_isnumeric(key)){
@ -1263,7 +1263,7 @@ bool SQVM::Get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &des
default:break; //shut up compiler default:break; //shut up compiler
} }
if ((getflags & GET_FLAG_RAW) == 0) { if ((getflags & GET_FLAG_RAW) == 0) {
switch(FallBackGet(self,key,dest)) { switch(FallBackget(self,key,dest)) {
case FALLBACK_OK: return true; //okie case FALLBACK_OK: return true; //okie
case FALLBACK_NO_MATCH: break; //keep falling back case FALLBACK_NO_MATCH: break; //keep falling back
case FALLBACK_ERROR: return false; // the metamethod failed case FALLBACK_ERROR: return false; // the metamethod failed
@ -1274,10 +1274,10 @@ bool SQVM::Get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &des
} }
//#ifdef ROOT_FALLBACK //#ifdef ROOT_FALLBACK
if(selfidx == 0) { if(selfidx == 0) {
SQWeakRef *w = _closure(ci->_closure)->_root; rabbit::WeakRef *w = _closure(ci->_closure)->_root;
if(sq_type(w->_obj) != OT_NULL) if(sq_type(w->_obj) != OT_NULL)
{ {
if(Get(*((const SQObjectPtr *)&w->_obj),key,dest,0,DONT_FALL_BACK)) return true; if(get(*((const SQObjectPtr *)&w->_obj),key,dest,0,DONT_FALL_BACK)) return true;
} }
} }
@ -1302,18 +1302,18 @@ bool SQVM::InvokeDefaultDelegate(const SQObjectPtr &self,const SQObjectPtr &key,
case OT_WEAKREF: ddel = _weakref_ddel; break; case OT_WEAKREF: ddel = _weakref_ddel; break;
default: return false; default: return false;
} }
return ddel->Get(key,dest); return ddel->get(key,dest);
} }
int64_t SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest) int64_t SQVM::FallBackget(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest)
{ {
switch(sq_type(self)){ switch(sq_type(self)){
case OT_TABLE: case OT_TABLE:
case OT_USERDATA: case OT_USERDATA:
//delegation //delegation
if(_delegable(self)->_delegate) { if(_delegable(self)->_delegate) {
if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,0,DONT_FALL_BACK)) return FALLBACK_OK; if(get(SQObjectPtr(_delegable(self)->_delegate),key,dest,0,DONT_FALL_BACK)) return FALLBACK_OK;
} }
else { else {
return FALLBACK_NO_MATCH; return FALLBACK_NO_MATCH;
@ -1321,7 +1321,7 @@ int64_t SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjec
//go through //go through
case OT_INSTANCE: { case OT_INSTANCE: {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(self)->GetMetaMethod(this, MT_GET, closure)) { if(_delegable(self)->getMetaMethod(this, MT_GET, closure)) {
Push(self);Push(key); Push(self);Push(key);
_nmetamethodscall++; _nmetamethodscall++;
AutoDec ad(&_nmetamethodscall); AutoDec ad(&_nmetamethodscall);
@ -1344,54 +1344,54 @@ int64_t SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjec
return FALLBACK_NO_MATCH; return FALLBACK_NO_MATCH;
} }
bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,int64_t selfidx) bool SQVM::set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,int64_t selfidx)
{ {
switch(sq_type(self)){ switch(sq_type(self)){
case OT_TABLE: case OT_TABLE:
if(_table(self)->Set(key,val)) return true; if(_table(self)->set(key,val)) return true;
break; break;
case OT_INSTANCE: case OT_INSTANCE:
if(_instance(self)->Set(key,val)) return true; if(_instance(self)->set(key,val)) return true;
break; break;
case OT_ARRAY: case OT_ARRAY:
if(!sq_isnumeric(key)) { Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; } if(!sq_isnumeric(key)) { Raise_Error(_SC("indexing %s with %s"),getTypeName(self),getTypeName(key)); return false; }
if(!_array(self)->Set(tointeger(key),val)) { if(!_array(self)->set(tointeger(key),val)) {
Raise_IdxError(key); Raise_IdxError(key);
return false; return false;
} }
return true; return true;
case OT_USERDATA: break; // must fall back case OT_USERDATA: break; // must fall back
default: default:
Raise_Error(_SC("trying to set '%s'"),GetTypeName(self)); Raise_Error(_SC("trying to set '%s'"),getTypeName(self));
return false; return false;
} }
switch(FallBackSet(self,key,val)) { switch(FallBackset(self,key,val)) {
case FALLBACK_OK: return true; //okie case FALLBACK_OK: return true; //okie
case FALLBACK_NO_MATCH: break; //keep falling back case FALLBACK_NO_MATCH: break; //keep falling back
case FALLBACK_ERROR: return false; // the metamethod failed case FALLBACK_ERROR: return false; // the metamethod failed
} }
if(selfidx == 0) { if(selfidx == 0) {
if(_table(_roottable)->Set(key,val)) if(_table(_roottable)->set(key,val))
return true; return true;
} }
Raise_IdxError(key); Raise_IdxError(key);
return false; return false;
} }
int64_t SQVM::FallBackSet(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val) int64_t SQVM::FallBackset(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val)
{ {
switch(sq_type(self)) { switch(sq_type(self)) {
case OT_TABLE: case OT_TABLE:
if(_table(self)->_delegate) { if(_table(self)->_delegate) {
if(Set(_table(self)->_delegate,key,val,DONT_FALL_BACK)) return FALLBACK_OK; if(set(_table(self)->_delegate,key,val,DONT_FALL_BACK)) return FALLBACK_OK;
} }
//keps on going //keps on going
case OT_INSTANCE: case OT_INSTANCE:
case OT_USERDATA:{ case OT_USERDATA:{
SQObjectPtr closure; SQObjectPtr closure;
SQObjectPtr t; SQObjectPtr t;
if(_delegable(self)->GetMetaMethod(this, MT_SET, closure)) { if(_delegable(self)->getMetaMethod(this, MT_SET, closure)) {
Push(self);Push(key);Push(val); Push(self);Push(key);Push(val);
_nmetamethodscall++; _nmetamethodscall++;
AutoDec ad(&_nmetamethodscall); AutoDec ad(&_nmetamethodscall);
@ -1414,19 +1414,19 @@ int64_t SQVM::FallBackSet(const SQObjectPtr &self,const SQObjectPtr &key,const S
return FALLBACK_NO_MATCH; return FALLBACK_NO_MATCH;
} }
bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target) bool SQVM::clone(const SQObjectPtr &self,SQObjectPtr &target)
{ {
SQObjectPtr temp_reg; SQObjectPtr temp_reg;
SQObjectPtr newobj; SQObjectPtr newobj;
switch(sq_type(self)){ switch(sq_type(self)){
case OT_TABLE: case OT_TABLE:
newobj = _table(self)->Clone(); newobj = _table(self)->clone();
goto cloned_mt; goto cloned_mt;
case OT_INSTANCE: { case OT_INSTANCE: {
newobj = _instance(self)->Clone(_ss(this)); newobj = _instance(self)->clone(_ss(this));
cloned_mt: cloned_mt:
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(newobj)->_delegate && _delegable(newobj)->GetMetaMethod(this,MT_CLONED,closure)) { if(_delegable(newobj)->_delegate && _delegable(newobj)->getMetaMethod(this,MT_CLONED,closure)) {
Push(newobj); Push(newobj);
Push(self); Push(self);
if(!CallMetaMethod(closure,MT_CLONED,2,temp_reg)) if(!CallMetaMethod(closure,MT_CLONED,2,temp_reg))
@ -1436,10 +1436,10 @@ cloned_mt:
target = newobj; target = newobj;
return true; return true;
case OT_ARRAY: case OT_ARRAY:
target = _array(self)->Clone(); target = _array(self)->clone();
return true; return true;
default: default:
Raise_Error(_SC("cloning a %s"), GetTypeName(self)); Raise_Error(_SC("cloning a %s"), getTypeName(self));
return false; return false;
} }
} }
@ -1463,7 +1463,7 @@ bool SQVM::NewSlotA(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjec
if(!NewSlot(self, key, val,bstatic)) if(!NewSlot(self, key, val,bstatic))
return false; return false;
if(sq_type(attrs) != OT_NULL) { if(sq_type(attrs) != OT_NULL) {
c->SetAttributes(key,attrs); c->setAttributes(key,attrs);
} }
return true; return true;
} }
@ -1476,9 +1476,9 @@ bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObject
bool rawcall = true; bool rawcall = true;
if(_table(self)->_delegate) { if(_table(self)->_delegate) {
SQObjectPtr res; SQObjectPtr res;
if(!_table(self)->Get(key,res)) { if(!_table(self)->get(key,res)) {
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_NEWSLOT,closure)) { if(_delegable(self)->_delegate && _delegable(self)->getMetaMethod(this,MT_NEWSLOT,closure)) {
Push(self);Push(key);Push(val); Push(self);Push(key);Push(val);
if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) { if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) {
return false; return false;
@ -1496,7 +1496,7 @@ bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObject
case OT_INSTANCE: { case OT_INSTANCE: {
SQObjectPtr res; SQObjectPtr res;
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_NEWSLOT,closure)) { if(_delegable(self)->_delegate && _delegable(self)->getMetaMethod(this,MT_NEWSLOT,closure)) {
Push(self);Push(key);Push(val); Push(self);Push(key);Push(val);
if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) { if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) {
return false; return false;
@ -1520,7 +1520,7 @@ bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObject
} }
break; break;
default: default:
Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); Raise_Error(_SC("indexing %s with %s"),getTypeName(self),getTypeName(key));
return false; return false;
break; break;
} }
@ -1538,14 +1538,14 @@ bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr
SQObjectPtr t; SQObjectPtr t;
//bool handled = false; //bool handled = false;
SQObjectPtr closure; SQObjectPtr closure;
if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_DELSLOT,closure)) { if(_delegable(self)->_delegate && _delegable(self)->getMetaMethod(this,MT_DELSLOT,closure)) {
Push(self);Push(key); Push(self);Push(key);
return CallMetaMethod(closure,MT_DELSLOT,2,res); return CallMetaMethod(closure,MT_DELSLOT,2,res);
} }
else { else {
if(sq_type(self) == OT_TABLE) { if(sq_type(self) == OT_TABLE) {
if(_table(self)->Get(key,t)) { if(_table(self)->get(key,t)) {
_table(self)->Remove(key); _table(self)->remove(key);
} }
else { else {
Raise_IdxError((const SQObject &)key); Raise_IdxError((const SQObject &)key);
@ -1553,7 +1553,7 @@ bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr
} }
} }
else { else {
Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self)); Raise_Error(_SC("cannot delete a slot from %s"),getTypeName(self));
return false; return false;
} }
} }
@ -1561,7 +1561,7 @@ bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr
} }
break; break;
default: default:
Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self)); Raise_Error(_SC("attempt to delete a slot from a %s"),getTypeName(self));
return false; return false;
} }
return true; return true;
@ -1585,7 +1585,7 @@ int64_t prevstackbase = _stackbase;
case OT_CLASS: { case OT_CLASS: {
SQObjectPtr constr; SQObjectPtr constr;
SQObjectPtr temp; SQObjectPtr temp;
CreateClassInstance(_class(closure),outres,constr); createClassInstance(_class(closure),outres,constr);
SQObjectType ctype = sq_type(constr); SQObjectType ctype = sq_type(constr);
if (ctype == OT_NATIVECLOSURE || ctype == OT_CLOSURE) { if (ctype == OT_NATIVECLOSURE || ctype == OT_CLOSURE) {
_stack[stackbase] = outres; _stack[stackbase] = outres;
@ -1634,7 +1634,7 @@ void SQVM::FindOuter(SQObjectPtr &target, SQObjectPtr *stackindex)
} }
pp = &p->_next; pp = &p->_next;
} }
otr = SQOuter::Create(_ss(this), stackindex); otr = SQOuter::create(_ss(this), stackindex);
otr->_next = *pp; otr->_next = *pp;
otr->_idx = (stackindex - _stack._vals); otr->_idx = (stackindex - _stack._vals);
__ObjAddRef(otr); __ObjAddRef(otr);
@ -1705,11 +1705,11 @@ void SQVM::CloseOuters(SQObjectPtr *stackindex) {
p->_value = *(p->_valptr); p->_value = *(p->_valptr);
p->_valptr = &p->_value; p->_valptr = &p->_value;
_openouters = p->_next; _openouters = p->_next;
__ObjRelease(p); __Objrelease(p);
} }
} }
void SQVM::Remove(int64_t n) { void SQVM::remove(int64_t n) {
n = (n >= 0)?n + _stackbase - 1:_top + n; n = (n >= 0)?n + _stackbase - 1:_top + n;
for(int64_t i = n; i < _top; i++){ for(int64_t i = n; i < _top; i++){
_stack[i] = _stack[i+1]; _stack[i] = _stack[i+1];
@ -1730,10 +1730,10 @@ void SQVM::Pop(int64_t n) {
void SQVM::PushNull() { _stack[_top++].Null(); } void SQVM::PushNull() { _stack[_top++].Null(); }
void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; } void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
SQObjectPtr &SQVM::Top() { return _stack[_top-1]; } SQObjectPtr &SQVM::top() { return _stack[_top-1]; }
SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; } SQObjectPtr &SQVM::Popget() { return _stack[--_top]; }
SQObjectPtr &SQVM::GetUp(int64_t n) { return _stack[_top+n]; } SQObjectPtr &SQVM::getUp(int64_t n) { return _stack[_top+n]; }
SQObjectPtr &SQVM::GetAt(int64_t n) { return _stack[n]; } SQObjectPtr &SQVM::getAt(int64_t n) { return _stack[n]; }
#ifdef _DEBUG_DUMP #ifdef _DEBUG_DUMP
void SQVM::dumpstack(int64_t stackbase,bool dumpall) void SQVM::dumpstack(int64_t stackbase,bool dumpall)

View File

@ -37,7 +37,7 @@ struct SQExceptionTrap{
typedef sqvector<SQExceptionTrap> ExceptionsTraps; typedef sqvector<SQExceptionTrap> ExceptionsTraps;
struct SQVM : public SQRefCounted struct SQVM : public rabbit::RefCounted
{ {
struct CallInfo{ struct CallInfo{
//CallInfo() { _generator = NULL;} //CallInfo() { _generator = NULL;}
@ -67,22 +67,22 @@ public:
bool TailCall(SQClosure *closure, int64_t firstparam, int64_t nparams); bool TailCall(SQClosure *closure, int64_t firstparam, int64_t nparams);
//starts a RABBIT call in the same "Execution loop" //starts a RABBIT call in the same "Execution loop"
bool StartCall(SQClosure *closure, int64_t target, int64_t nargs, int64_t stackbase, bool tailcall); bool StartCall(SQClosure *closure, int64_t target, int64_t nargs, int64_t stackbase, bool tailcall);
bool CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor); bool createClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor);
//call a generic closure pure RABBIT or NATIVE //call a generic closure pure RABBIT or NATIVE
bool Call(SQObjectPtr &closure, int64_t nparams, int64_t stackbase, SQObjectPtr &outres,SQBool raiseerror); bool Call(SQObjectPtr &closure, int64_t nparams, int64_t stackbase, SQObjectPtr &outres,SQBool raiseerror);
SQRESULT Suspend(); SQRESULT Suspend();
void CallDebugHook(int64_t type,int64_t forcedline=0); void CallDebugHook(int64_t type,int64_t forcedline=0);
void CallErrorHandler(SQObjectPtr &e); void CallErrorHandler(SQObjectPtr &e);
bool Get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &dest, uint64_t getflags, int64_t selfidx); bool get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &dest, uint64_t getflags, int64_t selfidx);
int64_t FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest); int64_t FallBackget(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest);
bool InvokeDefaultDelegate(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest); bool InvokeDefaultDelegate(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest);
bool Set(const SQObjectPtr &self, const SQObjectPtr &key, const SQObjectPtr &val, int64_t selfidx); bool set(const SQObjectPtr &self, const SQObjectPtr &key, const SQObjectPtr &val, int64_t selfidx);
int64_t FallBackSet(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val); int64_t FallBackset(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val);
bool NewSlot(const SQObjectPtr &self, const SQObjectPtr &key, const SQObjectPtr &val,bool bstatic); bool NewSlot(const SQObjectPtr &self, const SQObjectPtr &key, const SQObjectPtr &val,bool bstatic);
bool NewSlotA(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,const SQObjectPtr &attrs,bool bstatic,bool raw); bool NewSlotA(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,const SQObjectPtr &attrs,bool bstatic,bool raw);
bool DeleteSlot(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &res); bool DeleteSlot(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &res);
bool Clone(const SQObjectPtr &self, SQObjectPtr &target); bool clone(const SQObjectPtr &self, SQObjectPtr &target);
bool ObjCmp(const SQObjectPtr &o1, const SQObjectPtr &o2,int64_t &res); bool ObjCmp(const SQObjectPtr &o1, const SQObjectPtr &o2,int64_t &res);
bool StringCat(const SQObjectPtr &str, const SQObjectPtr &obj, SQObjectPtr &dest); bool StringCat(const SQObjectPtr &str, const SQObjectPtr &obj, SQObjectPtr &dest);
static bool IsEqual(const SQObjectPtr &o1,const SQObjectPtr &o2,bool &res); static bool IsEqual(const SQObjectPtr &o1,const SQObjectPtr &o2,bool &res);
@ -129,10 +129,10 @@ public:
} }
bool EnterFrame(int64_t newbase, int64_t newtop, bool tailcall); bool EnterFrame(int64_t newbase, int64_t newtop, bool tailcall);
void LeaveFrame(); void LeaveFrame();
void Release(){ sq_delete(this,SQVM); } void release(){ sq_delete(this,SQVM); }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//stack functions for the api //stack functions for the api
void Remove(int64_t n); void remove(int64_t n);
static bool IsFalse(SQObjectPtr &o); static bool IsFalse(SQObjectPtr &o);
@ -140,10 +140,10 @@ public:
void Pop(int64_t n); void Pop(int64_t n);
void Push(const SQObjectPtr &o); void Push(const SQObjectPtr &o);
void PushNull(); void PushNull();
SQObjectPtr &Top(); SQObjectPtr &top();
SQObjectPtr &PopGet(); SQObjectPtr &Popget();
SQObjectPtr &GetUp(int64_t n); SQObjectPtr &getUp(int64_t n);
SQObjectPtr &GetAt(int64_t n); SQObjectPtr &getAt(int64_t n);
SQObjectPtrVec _stack; SQObjectPtrVec _stack;
@ -187,7 +187,7 @@ struct AutoDec{
int64_t *_n; int64_t *_n;
}; };
inline SQObjectPtr &stack_get(HRABBITVM v,int64_t idx){return ((idx>=0)?(v->GetAt(idx+v->_stackbase-1)):(v->GetUp(idx)));} inline SQObjectPtr &stack_get(HRABBITVM v,int64_t idx){return ((idx>=0)?(v->getAt(idx+v->_stackbase-1)):(v->getUp(idx)));}
#define _ss(_vm_) (_vm_)->_sharedstate #define _ss(_vm_) (_vm_)->_sharedstate