#ifndef __NASAL_VM_H__ #define __NASAL_VM_H__ #include #include #include "nasal_codegen.h" class vm { protected: /* registers and constants of vm */ u32 pc; // program counter var* localr; // local scope register var* memr; // used for mem_call var funcr; // function register var upvalr; // upvalue register var* canary; // avoid stackoverflow var* top; // stack top const f64* num_table;// const numbers, ref from codegen const string* str_table;// const symbols, ref from codegen std::vector imm; // immediate number /* garbage collector */ gc ngc; /* main stack */ var stack[STACK_DEPTH]; /* values used for debugger */ const string* files; // ref from linker const opcode* bytecode; // ref from codegen void init( const std::vector&, const std::vector&, const std::vector&, const std::vector&, const std::vector&); /* debug functions */ bool detail_info; void valinfo(var&); void traceback(); void stackinfo(const u32); void reginfo(); void gstate(); void lstate(); void ustate(); void detail(); void die(const string&); #define vm_error(info) {die(info);return;} /* vm calculation functions*/ bool condition(var); /* vm operands */ void o_intg(); void o_intl(); void o_loadg(); void o_loadl(); void o_loadu(); void o_pnum(); void o_pnil(); void o_pstr(); void o_newv(); void o_newh(); void o_newf(); void o_happ(); void o_para(); void o_deft(); void o_dyn(); void o_unot(); void o_usub(); void o_add(); void o_sub(); void o_mul(); void o_div(); void o_lnk(); void o_addc(); void o_subc(); void o_mulc(); void o_divc(); void o_lnkc(); void o_addeq(); void o_subeq(); void o_muleq(); void o_diveq(); void o_lnkeq(); void o_addeqc(); void o_subeqc(); void o_muleqc(); void o_diveqc(); void o_lnkeqc(); void o_meq(); void o_eq(); void o_neq(); void o_less(); void o_leq(); void o_grt(); void o_geq(); void o_lessc(); void o_leqc(); void o_grtc(); void o_geqc(); void o_pop(); void o_jmp(); void o_jt(); void o_jf(); void o_cnt(); void o_findex(); void o_feach(); void o_callg(); void o_calll(); void o_upval(); void o_callv(); void o_callvi(); void o_callh(); void o_callfv(); void o_callfh(); void o_callb(); void o_slcbeg(); void o_slcend(); void o_slc(); void o_slc2(); void o_mcallg(); void o_mcalll(); void o_mupval(); void o_mcallv(); void o_mcallh(); void o_ret(); public: vm(): pc(0),localr(nullptr),memr(nullptr),funcr(nil), upvalr(nil),canary(nullptr),top(stack), num_table(nullptr),str_table(nullptr), ngc(pc,localr,memr,funcr,upvalr,canary,top,stack), files(nullptr),bytecode(nullptr),detail_info(false){} void run( const codegen&, const linker&, const std::vector&, const bool); }; void vm::init( const std::vector& strs, const std::vector& nums, const std::vector& code, const std::vector& filenames, const std::vector& argv) { ngc.init(strs,argv); num_table=nums.data(); str_table=strs.data(); bytecode=code.data(); files=filenames.data(); /* set canary and program counter */ pc=0; localr=memr=nullptr; funcr=upvalr=nil; canary=stack+STACK_DEPTH-1; // stack[STACK_DEPTH-1] top=stack; /* clear main stack */ for(u32 i=0;i "< entry:0x"< ["< ["< {"< obj:0x"<<(u64)val.obj().ptr < coroutine";break; default: std::cout<<"| err | <0x"< unknown object";break; } std::cout<<"\n"; } void vm::traceback() { /* bytecode[0].num is the global size */ var* bottom=ngc.stack==stack?stack+bytecode[0].num:ngc.stack; var* ctx_top=ngc.stack==stack?top:ngc.top; std::stack ret; for(var* i=bottom;i<=ctx_top;++i) if(i->type==vm_ret && i->ret()!=0) ret.push(i->ret()); ret.push(pc); // store the position program crashed std::cout<<"trace back ("<<(ngc.stack==stack?"main":"coroutine")<<")\n"; for(u32 p=0,same=0,prev=0xffffffff;!ret.empty();prev=p,ret.pop()) { if((p=ret.top())==prev) { ++same; continue; } if(same) std::cout <<" 0x"<, limit "<=bottom;++i,--t) { std::cout<<" 0x"<)\n"<)\n"< upval["<>16)&0xffff] .upval()[imm[pc]&0xffff]=(top--)[0]; } inline void vm::o_pnum() { (++top)[0]={vm_num,num_table[imm[pc]]}; } inline void vm::o_pnil() { (++top)[0]=nil; } inline void vm::o_pstr() { (++top)[0]=ngc.strs[imm[pc]]; } inline void vm::o_newv() { var newv=ngc.alloc(vm_vec); auto& vec=newv.vec().elems; vec.resize(imm[pc]); // use top-=imm[pc]-1 here will cause error if imm[pc] is 0 top=top-imm[pc]+1; for(u32 i=0;isize has 1 place reserved for "me" func.keys[imm[pc]]=func.psize; func.local[func.psize++]={vm_none}; } inline void vm::o_deft() { var val=top[0]; nas_func& func=(--top)[0].func(); // func->size has 1 place reserved for "me" func.keys[imm[pc]]=func.psize; func.local[func.psize++]=val; } inline void vm::o_dyn() { top[0].func().dpara=imm[pc]; } inline void vm::o_unot() { var val=top[0]; switch(val.type) { case vm_nil:top[0]=one;break; case vm_num:top[0]=val.num()?zero:one;break; case vm_str: { const f64 num=str2num(val.str().c_str()); if(std::isnan(num)) top[0]={vm_num,(f64)val.str().empty()}; else top[0]=num?zero:one; }break; default:vm_error("incorrect value type");break; } } inline void vm::o_usub() { top[0]={vm_num,-top[0].tonum()}; } #define op_calc(type)\ top[-1]={vm_num,top[-1].tonum() type top[0].tonum()};\ --top; inline void vm::o_add(){op_calc(+);} inline void vm::o_sub(){op_calc(-);} inline void vm::o_mul(){op_calc(*);} inline void vm::o_div(){op_calc(/);} inline void vm::o_lnk() { top[-1]=ngc.newstr(top[-1].tostr()+top[0].tostr()); --top; } #define op_calc_const(type)\ top[0]={vm_num,top[0].tonum() type num_table[imm[pc]]}; inline void vm::o_addc(){op_calc_const(+);} inline void vm::o_subc(){op_calc_const(-);} inline void vm::o_mulc(){op_calc_const(*);} inline void vm::o_divc(){op_calc_const(/);} inline void vm::o_lnkc() { top[0]=ngc.newstr(top[0].tostr()+str_table[imm[pc]]); } #define op_calc_eq(type)\ top[-1]=memr[0]={vm_num,memr[0].tonum() type top[-1].tonum()};\ memr=nullptr;\ top-=imm[pc]+1; inline void vm::o_addeq(){op_calc_eq(+);} inline void vm::o_subeq(){op_calc_eq(-);} inline void vm::o_muleq(){op_calc_eq(*);} inline void vm::o_diveq(){op_calc_eq(/);} inline void vm::o_lnkeq() { top[-1]=memr[0]=ngc.newstr(memr[0].tostr()+top[-1].tostr()); memr=nullptr; top-=imm[pc]+1; } #define op_calc_eq_const(type)\ top[0]=memr[0]={vm_num,memr[0].tonum() type num_table[imm[pc]&0x7fffffff]};\ memr=nullptr;\ top-=(imm[pc]>>31); inline void vm::o_addeqc(){op_calc_eq_const(+);} inline void vm::o_subeqc(){op_calc_eq_const(-);} inline void vm::o_muleqc(){op_calc_eq_const(*);} inline void vm::o_diveqc(){op_calc_eq_const(/);} inline void vm::o_lnkeqc() { top[0]=memr[0]=ngc.newstr(memr[0].tostr()+str_table[imm[pc]&0x7fffffff]); memr=nullptr; top-=(imm[pc]>>31); } inline void vm::o_meq() { // pop old memr[0] and replace it // the reason why we should get memr and push the old value on stack // is that when lnkeq/lnkeqc is called, there will be // a new gc object vm_str which is returned by gc::alloc // this may cause gc, so we should temporarily put it on stack memr[0]=top[-1]; memr=nullptr; top-=imm[pc]+1; } inline void vm::o_eq() { var val2=top[0]; var val1=(--top)[0]; if(val1.type==vm_nil && val2.type==vm_nil) top[0]=one; else if(val1.type==vm_str && val2.type==vm_str) top[0]=(val1.str()==val2.str())?one:zero; else if((val1.type==vm_num || val2.type==vm_num) && val1.type!=vm_nil && val2.type!=vm_nil) top[0]=(val1.tonum()==val2.tonum())?one:zero; else top[0]=(val1==val2)?one:zero; } inline void vm::o_neq() { var val2=top[0]; var val1=(--top)[0]; if(val1.type==vm_nil && val2.type==vm_nil) top[0]=zero; else if(val1.type==vm_str && val2.type==vm_str) top[0]=(val1.str()!=val2.str())?one:zero; else if((val1.type==vm_num || val2.type==vm_num) && val1.type!=vm_nil && val2.type!=vm_nil) top[0]=(val1.tonum()!=val2.tonum())?one:zero; else top[0]=(val1!=val2)?one:zero; } #define op_cmp(type)\ --top;\ top[0]=(top[0].tonum() type top[1].tonum())?one:zero; inline void vm::o_less(){op_cmp(<);} inline void vm::o_leq(){op_cmp(<=);} inline void vm::o_grt(){op_cmp(>);} inline void vm::o_geq(){op_cmp(>=);} #define op_cmp_const(type)\ top[0]=(top[0].tonum() type num_table[imm[pc]])?one:zero; inline void vm::o_lessc(){op_cmp_const(<);} inline void vm::o_leqc(){op_cmp_const(<=);} inline void vm::o_grtc(){op_cmp_const(>);} inline void vm::o_geqc(){op_cmp_const(>=);} inline void vm::o_pop() { --top; } inline void vm::o_jmp() { pc=imm[pc]-1; } inline void vm::o_jt() { if(condition(top[0])) pc=imm[pc]-1; } inline void vm::o_jf() { if(!condition(top[0])) pc=imm[pc]-1; --top; } inline void vm::o_cnt() { if(top[0].type!=vm_vec) vm_error("must use vector in forindex/foreach"); (++top)[0]={vm_cnt,(i64)-1}; } inline void vm::o_findex() { if((usize)(++top[0].cnt())>=top[-1].vec().size()) { pc=imm[pc]-1; return; } top[1]={vm_num,(f64)top[0].cnt()}; ++top; } inline void vm::o_feach() { auto& ref=top[-1].vec().elems; if((usize)(++top[0].cnt())>=ref.size()) { pc=imm[pc]-1; return; } top[1]=ref[top[0].cnt()]; ++top; } inline void vm::o_callg() { (++top)[0]=stack[imm[pc]]; } inline void vm::o_calll() { (++top)[0]=localr[imm[pc]]; } inline void vm::o_upval() { (++top)[0]=funcr.func().upval[(imm[pc]>>16)&0xffff] .upval()[imm[pc]&0xffff]; } inline void vm::o_callv() { var val=top[0]; var vec=(--top)[0]; if(vec.type==vm_vec) { top[0]=vec.vec().get_val(val.tonum()); if(top[0].type==vm_none) vm_error("index out of range:"+std::to_string(val.tonum())); } else if(vec.type==vm_hash) { if(val.type!=vm_str) vm_error("must use string as the key"); top[0]=vec.hash().get_val(val.str()); if(top[0].type==vm_none) vm_error("cannot find member \""+val.str()+"\""); if(top[0].type==vm_func) top[0].func().local[0]=val;// 'me' } else if(vec.type==vm_str) { string& str=vec.str(); i32 num=val.tonum(); i32 len=str.length(); if(num<-len || num>=len) vm_error("index out of range:"+std::to_string(val.tonum())); top[0]={vm_num,f64((u8)str[num>=0? num:num+len])}; } else vm_error("must call a vector/hash/string"); } inline void vm::o_callvi() { var val=top[0]; if(val.type!=vm_vec) vm_error("must use a vector"); // cannot use operator[],because this may cause overflow (++top)[0]=val.vec().get_val(imm[pc]); if(top[0].type==vm_none) vm_error("index out of range:"+std::to_string(imm[pc])); } inline void vm::o_callh() { var val=top[0]; if(val.type!=vm_hash) vm_error("must call a hash"); top[0]=val.hash().get_val(str_table[imm[pc]]); if(top[0].type==vm_none) vm_error("member \""+str_table[imm[pc]]+"\" does not exist"); if(top[0].type==vm_func) top[0].func().local[0]=val;// 'me' } inline void vm::o_callfv() { u32 argc=imm[pc]; // arguments counter var* local=top-argc+1; // arguments begin address if(local[-1].type!=vm_func) vm_error("must call a function"); auto& func=local[-1].func(); var tmp=local[-1]; local[-1]=funcr; funcr=tmp; // top-argc+lsize(local) +1(old pc) +1(old localr) +1(old upvalr) if(top-argc+func.lsize+3>=canary) vm_error("stack overflow"); // parameter size is func->psize-1, 1 is reserved for "me" u32 psize=func.psize-1; if(argc=0)// load dynamic arguments { dynamic=ngc.alloc(vm_vec); for(u32 i=psize;i=1;--i)// load arguments local[i]=local[i-1]; local[0]=func.local[0];// load "me" // load local scope & default arguments for(u32 i=min_size+1;i=0) local[psize+1]=dynamic; top[0]=upvalr; (++top)[0]={vm_addr,localr}; (++top)[0]={vm_ret,pc}; pc=func.entry-1; localr=local; upvalr=nil; } inline void vm::o_callfh() { auto& hash=top[0].hash().elems; if(top[-1].type!=vm_func) vm_error("must call a function"); auto& func=top[-1].func(); var tmp=top[-1]; top[-1]=funcr; funcr=tmp; // top -1(hash) +lsize(local) +1(old pc) +1(old localr) +1(old upvalr) if(top+func.lsize+2>=canary) vm_error("stack overflow"); if(func.dpara>=0) vm_error("special call cannot use dynamic argument"); var* local=top; top+=func.lsize; for(u32 i=0;i=size || num2<-size || num2>=size){ vm_error("index "+std::to_string(num1)+":"+std::to_string(num2)+" out of range."); }else if(num1<=num2){ for(i32 i=num1;i<=num2;++i) aim.push_back(i>=0?ref[i]:ref[i+size]); } } inline void vm::o_mcallg() { memr=stack+imm[pc]; (++top)[0]=memr[0]; // push value in this memory space on stack // to avoid being garbage collected } inline void vm::o_mcalll() { memr=localr+imm[pc]; (++top)[0]=memr[0]; // push value in this memory space on stack // to avoid being garbage collected } inline void vm::o_mupval() { memr=&(funcr.func().upval[(imm[pc]>>16)&0xffff].upval()[imm[pc]&0xffff]); (++top)[0]=memr[0]; // push value in this memory space on stack // to avoid being garbage collected } inline void vm::o_mcallv() { var val=top[0]; // index var vec=(--top)[0]; // mcall vector, reserved on stack to avoid gc if(vec.type==vm_vec) { memr=vec.vec().get_mem(val.tonum()); if(!memr) vm_error("index out of range:"+std::to_string(val.tonum())); }else if(vec.type==vm_hash) // do mcallh but use the mcallv way { if(val.type!=vm_str) vm_error("must use string as the key"); nas_hash& ref=vec.hash(); string& str=val.str(); memr=ref.get_mem(str); if(!memr) { ref.elems[str]=nil; memr=ref.get_mem(str); } }else vm_error("cannot get memory space in this type"); } inline void vm::o_mcallh() { var hash=top[0]; // mcall hash, reserved on stack to avoid gc if(hash.type!=vm_hash) vm_error("must call a hash"); nas_hash& ref=hash.hash(); const string& str=str_table[imm[pc]]; memr=ref.get_mem(str); if(!memr) // create a new key { ref.elems[str]=nil; memr=ref.get_mem(str); } } inline void vm::o_ret() { /* +-------------+ * | return value| <- top[0] * +-------------+ * | old pc | <- top[-1] * +-------------+ * | old localr | <- top[-2] * +-------------+ * | old upvalr | <- top[-3] * +-------------+ * | local scope | * | ... | * +-------------+ <- local pointer stored in localr * | old funcr | <- old function stored in funcr * +-------------+ */ var ret =top[0]; var* local=localr; var func =funcr; var up =upvalr; pc =top[-1].ret(); localr=top[-2].addr(); upvalr=top[-3]; top=local-1; funcr=top[0]; top[0]=ret; // rewrite func with returned value if(up.type==vm_upval) // synchronize upvalue { auto& upval=up.upval(); auto size=func.func().lsize; upval.onstk=false; for(u32 i=0;i& argv, const bool detail) { detail_info=detail; init(gen.strs(),gen.nums(),gen.codes(),linker.filelist(),argv); #ifndef _MSC_VER const void* oprs[]= { &&vmexit, &&intg, &&intl, &&loadg, &&loadl, &&loadu, &&pnum, &&pnil, &&pstr, &&newv, &&newh, &&newf, &&happ, &¶, &&deft, &&dyn, &&unot, &&usub, &&add, &&sub, &&mul, &&div, &&lnk, &&addc, &&subc, &&mulc, &&divc, &&lnkc, &&addeq, &&subeq, &&muleq, &&diveq, &&lnkeq, &&addeqc, &&subeqc, &&muleqc, &&diveqc, &&lnkeqc, &&meq, &&eq, &&neq, &&less, &&leq, &&grt, &&geq, &&lessc, &&leqc, &&grtc, &&geqc, &&pop, &&jmp, &&jt, &&jf, &&cnt, &&findex, &&feach, &&callg, &&calll, &&upval, &&callv, &&callvi, &&callh, &&callfv, &&callfh, &&callb, &&slcbeg, &&slcend, &&slc, &&slc2, &&mcallg, &&mcalll, &&mupval, &&mcallv, &&mcallh, &&ret }; std::vector code; for(auto& i:gen.codes()) { code.push_back(oprs[i.op]); imm.push_back(i.num); } // goto the first operand goto *code[pc]; #else typedef void (vm::*nafunc)(); const nafunc oprs[]= { nullptr, &vm::o_intg, &vm::o_intl, &vm::o_loadg, &vm::o_loadl, &vm::o_loadu, &vm::o_pnum, &vm::o_pnil, &vm::o_pstr, &vm::o_newv, &vm::o_newh, &vm::o_newf, &vm::o_happ, &vm::o_para, &vm::o_deft, &vm::o_dyn, &vm::o_unot, &vm::o_usub, &vm::o_add, &vm::o_sub, &vm::o_mul, &vm::o_div, &vm::o_lnk, &vm::o_addc, &vm::o_subc, &vm::o_mulc, &vm::o_divc, &vm::o_lnkc, &vm::o_addeq, &vm::o_subeq, &vm::o_muleq, &vm::o_diveq, &vm::o_lnkeq, &vm::o_addeqc, &vm::o_subeqc, &vm::o_muleqc, &vm::o_diveqc, &vm::o_lnkeqc, &vm::o_meq, &vm::o_eq, &vm::o_neq, &vm::o_less, &vm::o_leq, &vm::o_grt, &vm::o_geq, &vm::o_lessc, &vm::o_leqc, &vm::o_grtc, &vm::o_geqc, &vm::o_pop, &vm::o_jmp, &vm::o_jt, &vm::o_jf, &vm::o_cnt, &vm::o_findex, &vm::o_feach, &vm::o_callg, &vm::o_calll, &vm::o_upval, &vm::o_callv, &vm::o_callvi, &vm::o_callh, &vm::o_callfv, &vm::o_callfh, &vm::o_callb, &vm::o_slcbeg, &vm::o_slcend, &vm::o_slc, &vm::o_slc2, &vm::o_mcallg, &vm::o_mcalll, &vm::o_mupval, &vm::o_mcallv, &vm::o_mcallh, &vm::o_ret }; std::vector code; for(auto& i:gen.codes()) { code.push_back(oprs[i.op]); imm.push_back(i.num); } while(code[pc]){ (this->*code[pc])(); if(top>=canary) die("stack overflow"); ++pc; } #endif vmexit: if(detail) ngc.info(); ngc.clear(); imm.clear(); return; #ifndef _MSC_VER // may cause stackoverflow #define exec_check(op) {\ op();\ if(top