Esempio n. 1
0
//======================================================================
int EightNode_Brick_u_p::addInertiaLoadToUnbalance(const Vector &accel)
{
    static Vector ra(Num_ElemDof);
    int i;

    for (i=0; i<Num_Nodes; i++) {
      const Vector &RA = theNodes[i]->getRV(accel);

      if ( RA.Size() != Num_Dof ) {
        opserr << "EightNode_Brick_u_p::addInertiaLoadToUnbalance(): matrix and vector sizes are incompatable \n";
        return (-1);
      }

      ra(i*Num_Dof +0) = RA(0);
      ra(i*Num_Dof +1) = RA(1);
      ra(i*Num_Dof +2) = RA(2);
      ra(i*Num_Dof +3) = 0.0;
    }

    this->getMass();

    if (Q == 0)  
      Q = new Vector(Num_ElemDof);

    Q->addMatrixVector(1.0, MCK, ra, -1.0);

    return 0;
}
Esempio n. 2
0
bool is_immediate_pair(inst_t* instp) {
  // find out if instp points to lis followed by ori/addi/load/store
  inst_t i1 = instp[0];
  if (!is_lis(i1)) return false;
  fint reg = RT(i1);
  inst_t i2 = instp[1];
  return
       is_ori(i2)                    &&  RA(i2) == reg  &&  RS(i2) == reg 
  ||   is_addi(i2)                   &&  RT(i2) == reg  &&  RS(i2) == reg
  ||   is_load_store_immediate(i2)   &&  RA(i2) == reg;
}
Esempio n. 3
0
	void move_assign(array_t &A)
	{
		for(range_type R(*this), RA(A); !R.empty(); ++R.begin(), ++RA.begin())
		{
			move::assign(R.front(), RA.front());
		}
	}
Esempio n. 4
0
bool b2WheelJoint::SolvePositionConstraints(float32 baumgarte)
{
	B2_NOT_USED(baumgarte);

	b2Body* bA = m_bodyA;
	b2Body* bB = m_bodyB;

	b2Vec2 xA = bA->m_sweep.c;
	float32 angleA = bA->m_sweep.a;

	b2Vec2 xB = bB->m_sweep.c;
	float32 angleB = bB->m_sweep.a;

	b2Mat22 RA(angleA), RB(angleB);

	b2Vec2 rA = b2Mul(RA, m_localAnchorA - m_localCenterA);
	b2Vec2 rB = b2Mul(RB, m_localAnchorB - m_localCenterB);
	b2Vec2 d = xB + rB - xA - rA;

	b2Vec2 ay = b2Mul(RA, m_localYAxisA);

	float32 sAy = b2Cross(d + rA, ay);
	float32 sBy = b2Cross(rB, ay);

	float32 C = b2Dot(d, ay);

	float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;

	float32 impulse;
	if (k != 0.0f)
	{
		impulse = - C / k;
	}
	else
	{
		impulse = 0.0f;
	}

	b2Vec2 P = impulse * ay;
	float32 LA = impulse * sAy;
	float32 LB = impulse * sBy;

	xA -= m_invMassA * P;
	angleA -= m_invIA * LA;
	xB += m_invMassB * P;
	angleB += m_invIB * LB;

	// TODO_ERIN remove need for this.
	bA->m_sweep.c = xA;
	bA->m_sweep.a = angleA;
	bB->m_sweep.c = xB;
	bB->m_sweep.a = angleB;
	bA->SynchronizeTransform();
	bB->SynchronizeTransform();

	return b2Abs(C) <= b2_linearSlop;
}
Esempio n. 5
0
void eterm_show(int m, cmulti **x, func_t *fF, int bmax, int kappa)
{
  int kmax,k,db=64;
  int *b=NULL,tau;
  func_t *fJ=NULL;
  cmulti **y=NULL;
  rmulti **e=NULL,**eps=NULL,**em=NULL,**r=NULL,*rmax=NULL,**p=NULL;
  
  kmax=(bmax-64)/db; if(kmax<0){ kmax=2; }
  tau=cvec_get_exp_max(m,x);
  printf("tau=%d\n",tau);

  fJ=func_grad(func_retain(fF),func_var1_list(m));
  CVA(y,m); RVA(e,kmax); RVA(eps,kmax); RVA(em,kmax); RVA(r,kmax); RVA(p,kmax); RA(rmax);

  b=ivec_allocate(kmax);

  b[0]=53;
  for(k=1; k<kmax; k++){ b[k]=(k-1)*db+64; }

  for(k=0; k<kmax; k++){
    printf("b=%4d ",b[k]);
    set_default_prec(b[k]);
    rset_d(eps[k],1); rmul_2exp(eps[k],eps[k],-b[k]+tau);
    mpfr_printf("2^(-b+tau)=%8.1Re ",eps[k]);
    cvec_round(m,y,b[k]);
    csolve_newton_map(m,y,x,fF,fJ);
    csolve_newton_e_norm(e[k],m,y,x,fF,fJ,bmax*4);
    if(rgt(eps[k],e[k])){ printf("> "); }else{ printf("< "); }
    mpfr_printf("e=%8.1Re ",e[k]);
    rset_d(em[k],1); rmul_2exp(em[k],em[k],-b[k]+tau+kappa);
    if(rgt(e[k],em[k])){ printf("> "); }else{ printf("< "); }
    mpfr_printf("em=%8.1Re ",em[k]);

    rlog2(p[k],e[k]); rsub_d1(p[k],tau,p[k]); rsub_d1(p[k],b[k],p[k]);
    mpfr_printf("b-tau+log2(e)=%+6.2Rf ",p[k]);


    rlog2(r[k],e[k]); rsub_d1(r[k],tau,r[k]); rdiv_d2(r[k],r[k],b[k]); rsub_d1(r[k],1,r[k]);
    mpfr_printf("κ=1-(tau-log2(e))/b=%+.10Rf ",r[k]);
    printf("\n");
  }
  rvec_max(rmax,kmax,p);
  mpfr_printf("cancel bits=%+.2Rf\n",rmax);
  rvec_max(rmax,kmax,r);
  mpfr_printf("κ_max=%+.10Rf\n",rmax);
  

  // done
  fJ=func_del(fJ);
  b=ivec_free(b);
  CVF(y,m); RVF(e,kmax); RVF(eps,kmax); RVF(em,kmax); RVF(r,kmax); RVF(p,kmax); RF(rmax);
}
void QmitkDiffusionQuantificationView::CreateConnections()
{
    if ( m_Controls )
    {
        connect( (QObject*)(m_Controls->m_StandardGFACheckbox), SIGNAL(clicked()), this, SLOT(GFACheckboxClicked()) );
        connect( (QObject*)(m_Controls->m_GFAButton), SIGNAL(clicked()), this, SLOT(GFA()) );
        connect( (QObject*)(m_Controls->m_CurvatureButton), SIGNAL(clicked()), this, SLOT(Curvature()) );
        connect( (QObject*)(m_Controls->m_FAButton), SIGNAL(clicked()), this, SLOT(FA()) );
        connect( (QObject*)(m_Controls->m_RAButton), SIGNAL(clicked()), this, SLOT(RA()) );
        connect( (QObject*)(m_Controls->m_ADButton), SIGNAL(clicked()), this, SLOT(AD()) );
        connect( (QObject*)(m_Controls->m_RDButton), SIGNAL(clicked()), this, SLOT(RD()) );
        connect( (QObject*)(m_Controls->m_MDButton), SIGNAL(clicked()), this, SLOT(MD()) );
        connect( (QObject*)(m_Controls->m_ClusteringAnisotropy), SIGNAL(clicked()), this, SLOT(ClusterAnisotropy()) );
    }
}
Esempio n. 7
0
void vm_mini_vm(lua_State *L, LClosure *cl, int count, int pseudo_ops_offset) {
  const Instruction *pc;
  StkId base;
  TValue *k;

  k = cl->p->k;
  pc = cl->p->code + pseudo_ops_offset;
  base = L->base;
  /* process next 'count' ops */
  for (; count > 0; count--) {
    const Instruction i = *pc++;
    StkId ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      default: {
        luaG_runerror(L, "Bad opcode: opcode=%d", GET_OPCODE(i));
        continue;
      }
    }
  }
}
Esempio n. 8
0
File: lvm.c Progetto: lriki/Volkoff
void luaV_execute (lua_State *L) {
  CallInfo *ci = L->ci;
  LClosure *cl;
  TValue *k;
  StkId base;
 newframe:  /* reentry point when frame changes (call/return) */
  lua_assert(ci == L->ci);
  cl = clLvalue(ci->func);
  k = cl->p->k;
  base = ci->u.l.base;

  //printf( "s:%p\n", ci->u.l.savedpc );
  /* main loop of interpreter */
  for (;;) {

    Instruction i = *(ci->u.l.savedpc++);
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      Protect(traceexec(L));
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == ci->u.l.base);
    lua_assert(base <= L->top && L->top < L->stack + L->stacksize);


    // 命令出力
    //printInst( ci->u.l.savedpc - 1 );


    vmdispatch (GET_OPCODE(i)) {
      vmcase(OP_MOVE,
        setobjs2s(L, ra, RB(i));
      )
      vmcase(OP_LOADK,
        TValue *rb = k + GETARG_Bx(i);
        setobj2s(L, ra, rb);
      )
      vmcase(OP_LOADKX,
        TValue *rb;
        lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
        rb = k + GETARG_Ax(*ci->u.l.savedpc++);
        setobj2s(L, ra, rb);
      )
Esempio n. 9
0
int main(int argc, const char *argv[])
{
  char *eq[]={"{x-sin(3/2*(x+y)), y-cos(3/2*(x+y))}",
	      "{x^3+y^2+1, x^2+y^2+2}",
	      "{2*x^2+y, x+2*y+5}",
	      "{3*x^2-1,log(x)+y+3}",          //-eq 0 -eps 1e-100 --> ## 2 step 戻る ## 実数解 
	      "{x^2+y^2+x^2-1,x^2+z^2-y,x-z}",       //eq 5  ## 2step 戻る ##
	      "{-x+x^2+2*y^2+2*z^2+2*w^2, -y+2*x*y+2*y*z+2*z*w, -z+y^2+2*x*z+2*y*w, -1+x+2*y+2*z+2*w}", //eq 6 ## 2step 戻る ##
	      "{x-10000-y^2,x*y^2-100}",             // eq 8 ## 2step 戻る ##
	      "{0.3*x^2-1}",                         // eq 9 ## 2step 戻る ##
	      "{(3*x-y^2)^3-1000,log(x)^(-1)+2*y-30}",                //eq 12 ### 3step 戻る ### 
	      "{cos(0.5*x)+cos(y)-1, sin(0.5*x)-sin(y)-1}",           //eq31 // x=pi, y=0  ## 2回 2step 戻る ##	      
	      "{-x+x^2+2*y^2+2*z^2+2*w^2, -y+2*x*y+2*y*z+2*z*w, -z+y^2+2*x*z+2*y*w, -1+x+2*y+2*z+2*w}", //eq 36 4変数 x=1, y=z=w=0  ## 2step 戻る ##
	      "{x^2-y^2-1,x^4-y^4-1999}",             // 桁落ち kappa=0.06,  解 x=sqrt(1000),y=sqrt(999)
	      "{x^2+y^2-1, x^2+2*x*y+y^2-2}",         // 線形
	      "{x+y,x*y}",                            // 線形,零
	      NULL 
  };
  int debug=0,i,m,step_max0=-1,step_max=-1,prec0=53,prec=53,no=0,solve_true=0,info,seed=0,eterm=0,e_prec=2048,e_seed=-1,kappa=26,l=4;
  double mu=8;
  func_t *fF=NULL;
  cmulti **x0=NULL,**x=NULL,**x_true=NULL,**e=NULL;
  rmulti *eps=NULL,*eps_true=NULL;

  // init func_t
  func_eval(func_script("begin(x,y,z,w,v,u)"));

  // default prec
  set_default_prec(prec0);

  // allocate
  RA(eps); RA(eps_true);

  // default parameters
  rset_d(eps,1e-200);
  rset_s(eps_true,"1e-2000");

  // get options
  i=1;
  while(i<argc){
    if(STR_EQ(argv[i],"--help"))                 { usage(); }
    else if(STR_EQ(argv[i],"-v"))                { debug=1; }
    else if(STR_EQ(argv[i],"-vv"))               { debug=2; }
    else if(STR_EQ(argv[i],"-vvv"))              { debug=3; }
    else if(STR_EQ(argv[i],"-true"))             { solve_true=1; }
    else if(STR_EQ(argv[i],"-eterm"))            { eterm=1; }
    else if(i+1<argc && STR_EQ(argv[i],"-mu"))   { mu=atof(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-l"))    { l=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-kappa")){ kappa=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-eq"))   { no=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-n"))    { step_max=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-prec0")){ prec0=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-prec")) { prec=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-e-prec")){ e_prec=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-e-seed")){ e_seed=atoi(argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-eps"))  { rset_s(eps,argv[++i]); }
    else if(i+1<argc && STR_EQ(argv[i],"-seed")) { seed=atoi(argv[++i]); }
    else                                         { usage(); }
    i++;
  }

  //
  printf("step_max=%d\n",step_max);
  printf("mu=%g\n",mu);
  printf("l=%d\n",l);
  printf("kappa=%d\n",kappa);
  fF=func_script(eq[no]);  printf("fF="); func_print(fF); printf("\n");
  m=func_asize(fF);        printf("m=%d\n",m);

  // allocate vectors and matrices
  set_default_prec(prec0);  printf("prec0=%d\n",prec0);
  CVA(x0,m); CVA(x,m); CVA(x_true,m); CVA(e,m);

  // set initial vector
  init_genrand(seed);
  cvec_set_rand(m,x0,2,-1);     cvec_print(m,x0,"x0=","f",6);

  // solve for true solution
  printf("#-------------------\n");
  cvec_clone(m,x_true,x0);
  csolve_newton(m,x_true,fF,step_max0,debug);
    //prec=csolve_newton_adjust(m,x_true,fF,NULL,eps_true,step_max0,mu,l,kappa,debug);
  cvec_print(m,x_true,"x*=","e",20);
  cvec_clone(m,x,x_true);

  // solve
  if(solve_true){
    printf("#-------------------\n");
    cvec_clone(m,x,x0);
    prec=csolve_newton_adjust(m,x,fF,x_true,eps,step_max,mu,l,kappa,debug);
    cvec_print(m,x,"x=","e",20);
  }
 
  // error
  printf("#-------------------\n");
  printf("prec=%d\n",prec);
  set_default_prec(prec);
  cvec_round(m,e,prec);
  cvec_set_nan(m,e);
  info=csolve_krawczyk(m,e,x,fF,debug-2);
  if(info){ print_red(); printf("failed.\n"); } else{ print_green(); printf("succeeded.\n"); } print_reset();
  cvec_print(m,e,"e=","e",1);

  if(eterm){
    printf("#-------------------\n");
    if(e_seed>=0){ init_genrand(e_seed); cvec_set_rand(m,x,2,-1); }
    eterm_show(m,x,fF,e_prec,kappa);
  }

  // done
  printf("#-------------------\n");
  fF=func_del(fF);
  func_clear();
  RF(eps); CVF(x,m); CVF(e,m);
  printf("func_new_del_check_sum=%d\n",func_new_del_check_sum());  
  return 0;
}
Esempio n. 10
0
void Transference::execute()
{
	if (data.type == 16) RR();
	else if (data.type == 79) AR();
	else if (data.type == 80) RA();
}
Esempio n. 11
0
File: lvm.c Progetto: zapline/zlib
static void Arith (lua_State *L, StkId ra, const TValue *rb,
                   const TValue *rc, TMS op) {
  TValue tempb, tempc;
  const TValue *b, *c;
#if LUA_REFCOUNT
  luarc_newvalue(&tempb);
  luarc_newvalue(&tempc);
  if ((b = luaV_tonumber(L, rb, &tempb)) != NULL &&
      (c = luaV_tonumber(L, rc, &tempc)) != NULL) {
#else
  if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
      (c = luaV_tonumber(rc, &tempc)) != NULL) {
#endif /* LUA_REFCOUNT */
    lua_Number nb = nvalue(b), nc = nvalue(c);
#if LUA_REFCOUNT
    luarc_cleanvalue(&tempb);
    luarc_cleanvalue(&tempc);
#endif /* LUA_REFCOUNT */
    switch (op) {
      case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
      case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
      case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
      case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
      case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
      case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
      case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
      default: lua_assert(0); break;
    }
  }
#if LUA_REFCOUNT
  else if (!call_binTM(L, rb, rc, ra, op)) {
    luarc_cleanvalue(&tempb);
    luarc_cleanvalue(&tempc);
    luaG_aritherror(L, rb, rc);
  }
#else
  else if (!call_binTM(L, rb, rc, ra, op))
    luaG_aritherror(L, rb, rc);
#endif /* LUA_REFCOUNT */
}



/*
** some macros for common tasks in `luaV_execute'
*/

#define runtime_check(L, c)	{ if (!(c)) break; }

#define RA(i)	(base+GETARG_A(i))
/* to be used after possible stack reallocation */
#define RB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
#define RC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
#define RKB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
	ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
#define RKC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
	ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
#define KBx(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i))


#define dojump(L,pc,i)	{(pc) += (i); luai_threadyield(L);}


#define Protect(x)	{ L->savedpc = pc; {x;}; base = L->base; }


#define arith_op(op,tm) { \
        TValue *rb = RKB(i); \
        TValue *rc = RKC(i); \
        if (ttisnumber(rb) && ttisnumber(rc)) { \
          lua_Number nb = nvalue(rb), nc = nvalue(rc); \
          setnvalue(ra, op(nb, nc)); \
        } \
        else \
          Protect(Arith(L, ra, rb, rc, tm)); \
      }

#if LUA_BITFIELD_OPS

#define bit_op(op) { \
        TValue *rb = RKB(i); \
        TValue *rc = RKC(i); \
        if (ttisnumber(rb) && ttisnumber(rc)) { \
          unsigned int nb = (unsigned int)nvalue(rb), nc = (unsigned int)nvalue(rc); \
          setnvalue(ra, nb op nc); \
        } \
        else \
          luaG_aritherror(L, rb, rc); \
      }

#endif /* LUA_BITFIELD_OPS */



void luaV_execute (lua_State *L, int nexeccalls) {
  LClosure *cl;
  StkId base;
  TValue *k;
  const Instruction *pc;
 reentry:  /* entry point */
  lua_assert(isLua(L->ci));
  pc = L->savedpc;
  cl = &clvalue(L->ci->func)->l;
  base = L->base;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L, pc);
      if (L->status == LUA_YIELD) {  /* did hook yield? */
        L->savedpc = pc - 1;
        return;
      }
      base = L->base;
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        continue;
      }
      case OP_LOADNIL: {
        TValue *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_GETGLOBAL: {
        TValue g;
        TValue *rb = KBx(i);
#if LUA_REFCOUNT
        sethvalue2n(L, &g, cl->env);
#else
        sethvalue(L, &g, cl->env);
#endif /* LUA_REFCOUNT */
        lua_assert(ttisstring(rb));
        Protect(luaV_gettable(L, &g, rb, ra));
#if LUA_REFCOUNT
		setnilvalue(&g);
#endif /* LUA_REFCOUNT */
        continue;
      }
      case OP_GETTABLE: {
        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
        continue;
      }
      case OP_SETGLOBAL: {
        TValue g;
#if LUA_REFCOUNT
        sethvalue2n(L, &g, cl->env);
#else
        sethvalue(L, &g, cl->env);
#endif /* LUA_REFCOUNT */
        lua_assert(ttisstring(KBx(i)));
        Protect(luaV_settable(L, &g, KBx(i), ra));
#if LUA_REFCOUNT
		setnilvalue(&g);
#endif /* LUA_REFCOUNT */
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
        Protect(luaC_checkGC(L));
        continue;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        setobjs2s(L, ra+1, rb);
        Protect(luaV_gettable(L, rb, RKC(i), ra));
        continue;
      }
      case OP_ADD: {
        arith_op(luai_numadd, TM_ADD);
        continue;
      }
      case OP_SUB: {
        arith_op(luai_numsub, TM_SUB);
        continue;
      }
      case OP_MUL: {
        arith_op(luai_nummul, TM_MUL);
        continue;
      }
      case OP_DIV: {
        arith_op(luai_numdiv, TM_DIV);
        continue;
      }
      case OP_MOD: {
        arith_op(luai_nummod, TM_MOD);
        continue;
      }
      case OP_POW: {
        arith_op(luai_numpow, TM_POW);
        continue;
      }
      case OP_UNM: {
        TValue *rb = RB(i);
        if (ttisnumber(rb)) {
          lua_Number nb = nvalue(rb);
          setnvalue(ra, luai_numunm(nb));
        }
        else {
          Protect(Arith(L, ra, rb, rb, TM_UNM));
        }
        continue;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        continue;
      }
#if LUA_BITFIELD_OPS
      case OP_BAND: {
        bit_op(&);
        continue;
      }
      case OP_BOR: {
        bit_op(|);
        continue;
      }
      case OP_BXOR: {
        bit_op(^);
        continue;
      }
      case OP_BSHL: {
        bit_op(<<);
        continue;
      }
      case OP_BSHR: {
        bit_op(>>);
        continue;
      }
#endif /* LUA_BITFIELD_OPS */
      case OP_LEN: {
        const TValue *rb = RB(i);
        switch (ttype(rb)) {
          case LUA_TTABLE: {
            setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
            break;
          }
          case LUA_TSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
#if LUA_WIDESTRING
          case LUA_TWSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
#endif /* LUA_WIDESTRING */
          default: {  /* try metamethod */
            Protect(
              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
                luaG_typeerror(L, rb, "get length of");
            )
          }
        }
        continue;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
        setobjs2s(L, RA(i), base+b);
        continue;
      }
      case OP_JMP: {
        dojump(L, pc, GETARG_sBx(i));
        continue;
      }
      case OP_EQ: {
        TValue *rb = RKB(i);
        TValue *rc = RKC(i);
        Protect(
          if (equalobj(L, rb, rc) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LT: {
        Protect(
          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LE: {
        Protect(
          if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
Esempio n. 12
0
int main()
{
    printf("%d\n", RA());
    return 0;
}
Esempio n. 13
0
// 已经准备好了lua函数的调用环境,开始逐句执行lua函数的指令
void luaV_execute (lua_State *L, int nexeccalls) {
  LClosure *cl;
  StkId base;
  TValue *k;
  const Instruction *pc;
 reentry:  /* entry point */
  pc = L->savedpc;					//这时候已经保存了lua函数的第一个指令位置
  cl = &clvalue(L->ci->func)->l;
  base = L->base;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L, pc);
      if (L->status == LUA_YIELD) {  /* did hook yield? */
        L->savedpc = pc - 1;
        return;
      }
      base = L->base;
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));

	// 阅读说明:
	// 每lua的一个函数在编译器会生成这个函数的信息:函数引用到的upvalue,函数固定参数
	// 数量,是否含有可变参数,指令序列等等,这些都记录在Proto结构体中。
	// 可以通过 luac -o tmp <luafile> | luac -l tmp 来函数对应的字节码以及Proto信息
	// 例如以下lua代码:
	// -- t.lua
	// local x, y, z
	// x = x*y + y*z + x*z - (x*x + y*y + z*z)
	// 得到以下输出:
	// main <t.lua:0,0> (12 instructions, 48 bytes at 0074B6A0)
	// 0 + params, 6 slots, 0 upvalues, 3 locals, 0 constants, 0 functions
	//	1[2]	MUL      	3 0 1
	//	2[2]	MUL      	4 1 2
	//	3[2]	ADD      	3 3 4
	//	4[2]	MUL      	4 0 2
	//	5[2]	ADD      	3 3 4
	//	6[2]	MUL      	4 0 0
	//	7[2]	MUL      	5 1 1
	//	8[2]	ADD      	4 4 5
	//	9[2]	MUL      	5 2 2
	//	10[2]	ADD      	4 4 5
	//	11[2]	SUB      	0 3 4
	//	12[2]	RETURN   	0 1
	// 从输出可以得到的信息包括:
	//  1 生成了多少个Proto
	//  2 Proto对应的lua源代码在哪里 (<t.lua:0,0>)
	//  3 Proto中的sizecode (12 instructions, 48 bytes at 0074B6A0)
	//  4 Proto中的固定参数数量numparams (0 + params,这里的0)
	//  5 Proto是否有可变参数is_vararg (0 + params,这里的+表示带有可变参数,没有可变参数就是 0 params)
	//  6 Proto中在栈上用到的临时变量总数maxstacksize (6 slots,表示local变量+计算中辅助用的临时变量=6个)
	//  7 Proto中用到的upvalue数量nups (0 upvalues,表示用到了0个upvalue)
	//  8 Proto中用到的local变量数量sizelocvars (3 locals,刚好t.lua用到了x,y,z三个local变量)
	//  9 Proto中用到的字面常量数量sizek (0 constants)
	// 10 Proto中用到的Closure数量sizep (0 functions)
	// 11 Proto中生成的字节码指令内容code,每条指令包括:
	//    a 指令下标
	//    b 指令在源代码中对应的行号
	//    c 指令opcode
	//    d 指令参数
	// 
	// PS:第6条和第8条,由于计算一条表达式需要用到的辅助临时变量数目是不定的,但是是可以通过
	// 分析一条表达式的AST来确定最少需要几个临时变量(后续遍历+逆波兰式拟真)。
	// PS:lua是会对表达式进行常量计算优化的!例如 x = x + 5*60*60*1000,只有一个常量18000000
	// PS:函数执行的时候需要用到“一段”参数栈上的空间,也就是第6条所谓的临时变量。这一段空间的
	// 范围由L->base开始,到L->top结束。通过相对L->base的下标来标识具体的变量是哪个。一般来说,
	// 固定参数的函数,L->base指向第一个固定参数,而L->base-1指向当前正在运行的函数;而可变参数
	// 的函数,L->base和当前正在运行的函数中间,保存有全部的传入参数。
    switch (GET_OPCODE(i)) {

	  // 功能:用一个已有的变量创建一个新的变量
	  // 将一个 lua_TValue设置成另一个lua_TValue的样子
      // iABC: A待创建变量在参数栈索引,B参数栈已有lua变量的索引。
      case OP_MOVE: {		
		// local x, y   -----> 记录 index(x) = 0, index(y) = 1
		// x = ...
		// .....
		// y = x    -----> OP_MOVE: 1, 0
        setobjs2s(L, ra, RB(i));
        continue;
      }

	  // 功能:用一个常量来创建一个新的变量
	  // 从常量池(保存在Proto类型中)中保存的常量赋值给栈上的变量
	  // iABx: A待创建变量在参数栈索引,Bx常量在常量池的索引
      case OP_LOADK: {		
		// local x = 9	-----> 记录 index(x) = 0, index(constval(9)) = 1 
		//              >----> OP_LOADK: 0, 1
        setobj2s(L, ra, KBx(i));
        continue;
      }

	  // 功能:用一个布尔值来创建一个新的变量
	  // iABC: A待创建变量在参数栈索引,B布尔值,C通常是0
      case OP_LOADBOOL: {	
		// 注意,local c = true这种,true就不作为一个常量放到k里面
		// 而是作为字面值放到参数B里面了!所以不需要KB(i)!
		// local a = false -----> 记录 index(a) = 0
		//                 >----> OP_LOADBOOL 0 0 0
		// local b = true  -----> 记录 index(b) = 1
		//                 >----> OP_LOADBOOL 1 1 0
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        continue;
      }

	  // 功能:用nil来初始化一个到多个变量
	  // 类似于bzero,这个指令会把一段内存中的变量置为nil
	  // iABC: A第一个要置nil的变量参数栈索引,B最后一个要置nil的变量参数栈索引
      case OP_LOADNIL: {
		// local a, b, c, d, e, f, g = 1, 2, 3, 4 -----> index(a~g) = 0~6
		//                                        >----> OP_LOADNIL 4 6
        TValue *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        continue;
      }

	  // 功能:用upvalue来创建一个新的变量
	  // 所谓的“创建”操作,其实创建的不是副本而是引用
	  // iABC: A待创建变量在参数栈索引,B当前函数的upvalue表的索引
      case OP_GETUPVAL: {	
		// local x = {}
		// ...  -- do something to x
		// function f() local a = x[1] end   -----> 记录index(a) = 0, index(upval(x)) = 1
		//                                   >----> OP_GETUPVAL 0 1
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }

	  // 功能:从全局表中取某个key的值来创建一个新的变量
	  // iABx:A待创建变量在参数栈索引,Bxkey对应的常量在常量池的索引
      case OP_GETGLOBAL: {
		// local a = dofile    ------> 记录 index(a) = 0, index(constval("dofile")) = 1
		//                     >-----> OP_GETGLOBAL 0 1
        TValue g;
        TValue *rb = KBx(i);
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(rb));
        Protect(luaV_gettable(L, &g, rb, ra));
        continue;
      }

	  // 功能:从某个table中取某个key的值来创建一个新的变量
	  // iABC:A待创建变量在参数栈索引,B要取出key的table变量在参数栈的索引,Ckey对应的参数栈下标或者常量池下标
      case OP_GETTABLE: {
		// local a = hello["world"] -----> 记录 index(a) = 0, index(hello) = 1 index(constval("world")) = 0
		//                          >----> OP_GETTABLE 0 1 0|BITRK
        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
        continue;
      }

	  // 功能:将参数栈上变量设置到全局表中
	  // iABx:A要写入全局表的变量在栈上的索引,Bx写入到全局表的key在常量池中的下标
      case OP_SETGLOBAL: {
		// 假设我要替换 bit库
		// local mybit = {}
		// mybit.band = ...
		// mybit.bor = ...
		// mybit.bxor = ...
		// ...
		// bit = mybit -----> 记录 index(mybit) = 0, index(constval("bit")) = 1
		//             >----> OP_SETGLOBAL 0 1
        TValue g;
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(KBx(i)));
        Protect(luaV_settable(L, &g, KBx(i), ra));
        continue;
      }

	  // 功能:修改upvalue的值
	  // iABC:A要写入upvalue的变量在参数栈上的索引,B待写入的upvalue在upvalue表的索引
      case OP_SETUPVAL: {
		// local a = 5
		// function p()
		//  a = "hello" -----> 记录 index(upval(a)) = 0, index(constval("hello")) = 1
		//              >----> OP_SETUPVAL 0 1
		// end
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }

	  // 功能:修改某个table对应的key
	  // iABC:A要写入table变量在参数栈的索引,B要写入的key的变量的栈索引或者常量索引,C要写入的value的变量索引或者常量索引
      case OP_SETTABLE: {
		// local a = {}
		// a[5] = 3
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }

	  // 功能:在栈上创建一个table变量
	  // iABC:A存放table变量的参数栈索引,B创建的table变量的数组容量,C创建的table变量的字典容量
      case OP_NEWTABLE: {
		// local a = {}   -----> index(a) = 0
		//                >----> OP_NEWTABLE 0 szArray szHash
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
        Protect(luaC_checkGC(L));			// 注意,创建table可能会引起GC
        continue;
      }

	  // 功能:把self.method和self放到参数栈上相邻的两个位置。
	  // 为成员方法调用的语法糖提供支持
	  // iABC:A存放self.method的参数栈索引,B存放self的参数栈索引,C需要从self中调用的方法对应的变量索引或者常量索引
	  // 执行完成后,栈上内容为: ... -> self.method -> self -> ...
	  //                                   ^
	  //                                   RA
	  // 当然,OP_SELF之后能看到OP_CALL的身影
      case OP_SELF: {
		// CCNode:create()  -> index(constants("CCNode")) = 1, index(constants("create")) = 2
		//                  -> OP_GETGLOBAL 0 1
		//                  -> OP_SELF 0 0 2
		//                  -> OP_CALL 0 2 1
        StkId rb = RB(i);
        setobjs2s(L, ra+1, rb);
        Protect(luaV_gettable(L, rb, RKC(i), ra));
        continue;
      }

	//---------------------------------------------------------------------------运算符指令
	  // 功能:实现二元运算符:+, -, *, /, %, ^
	  // iABC:A存放运算结果的参数栈索引,B存放第一操作数的参数栈索引,C存放第二操作数的参数栈索引
      case OP_ADD: {
		// local a, b, c = ... -----> index(a) = 0, index(b) = 1, index(c) = 2
		// a = b + c -----> OP_ADD 0 1|BITRK 2|BITRK
		// a = 1 + b -----> index(constval(1)) = 0
		//           >----> OP_ADD 0 0 1|BITRK
		// a = 1 + 100 -----> index(constval(1)) = 0, index(constval(100)) = 1
		//             >----> OP_ADD 0 0 1
        arith_op(luai_numadd, TM_ADD);
        continue;
      }
      case OP_SUB: {
		// see OP_ADD
        arith_op(luai_numsub, TM_SUB);
        continue;
      }
      case OP_MUL: {
		// see OP_ADD
        arith_op(luai_nummul, TM_MUL);
        continue;
      }
      case OP_DIV: {
		// see OP_ADD
        arith_op(luai_numdiv, TM_DIV);
        continue;
      }
      case OP_MOD: {
		// 这个很特殊!由于lua没有整数,所以mod可不是%这个运算符!
		// 这里定义 mod(x, y) => (x - floor(x/y)*y)
		// see OP_ADD
        arith_op(luai_nummod, TM_MOD);
        continue;
      }
      case OP_POW: {
		// see OP_ADD
        arith_op(luai_numpow, TM_POW);
        continue;
      }

	  // 功能:实现一元运算符 -, not, #
	  // iABC:A存放运算结果的参数栈索引,B存放操作数的参数栈索引
      case OP_UNM: {
		// local a = -b -----> index(a) = 1, index(b) = 2
		//              >----> OP_UNM 1 2
        TValue *rb = RB(i);
        if (ttisnumber(rb)) {
          lua_Number nb = nvalue(rb);
          setnvalue(ra, luai_numunm(nb));
        }
        else {
          Protect(Arith(L, ra, rb, rb, TM_UNM));
        }
        continue;
      }
      case OP_NOT: {
		// local a = not b -----> index(a) = 1, index(b) = 2
		//                 >----> OP_NOT 1 2
		// 那local a = not true呢?人家编译期就给你处理好了
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        continue;
      }
      case OP_LEN: {
		// local a = #b -----> index(a) = 1, index(b) = 2
		//              >----> OP_LEN 1 2
        const TValue *rb = RB(i);
        switch (ttype(rb)) {
          case LUA_TTABLE: {
            setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
            break;
          }
          case LUA_TSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
          default: {  /* try metamethod */
            Protect(
              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
                luaG_typeerror(L, rb, "get length of");
            )
          }
        }
        continue;
      }

	  // 功能:实现字符串拼接运算符 ..
	  // iABC:A拼接后存放结果的参数栈索引,B第一个要拼接的变量的参数栈索引,C最后一个要拼接的变量的参数栈索引
	  // 要执行这个指令,对参数栈有特殊要求:
	  // ... -> string1 -> string2 ... -> stringN -> ...
	  //          ^                          ^
	  //          RB                         RC
      case OP_CONCAT: {
		// 类似OP_LOADNIL,只不过,这次范围是[rb,rc],loadnil是[ra,rb]
		// local b, c, d, a = "hello", "world", "!"
		// a = b .. c .. d -----> index(a) = 4, index(b~d) = 1~3
		//                 >----> OP_CONCAT 4 1 3
		// 问题是如果b~d不能保证是连续的怎么办?答案是一个个MOVE上去在OP_CONCAT...
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
        setobjs2s(L, RA(i), base+b);
        continue;
      }

	//---------------------------------------------------------------------------跳转指令
	  // 功能:无条件跳转
	  // iAsBx:A不使用,sBx跳转偏移
	  // 一般这个语句不单独出现,都是在一些条件控制中和其他的条件跳转指令配合使用的。
      case OP_JMP: {
		// 无条件跳转指令。由于跳转偏移总是有正向和反向之分的,所以需要用到
		// 负数。那就只能用iAsBx类型的指令了。而sBx是有长度限制的!
		// 所以,如果生成的指令很多,超过了sBx的长度限制,可能就会编译失败
        dojump(L, pc, GETARG_sBx(i));
        continue;
      }

	  // 功能:检查两个变量是否相等,满足预期则跳转。配合OP_JMP使用。
	  // iABC:A纯数字,对比较结果的预期,满足预期则跳转,B参数1的索引,C参数2的索引
      case OP_EQ: {
		// if a == b then -----> index(a) = 1, index(b) = 2
		//                >----> 这里将生成两行指令:
		//                >----> OP_EQ  0 1 2	// 用0,因为成立的话跳过,不成立才执行
		//                >----> OP_JMP N		// N 表示then ... end中间的指令数量
		//                >----> ...			// Instructions between "then" and "end"
        TValue *rb = RKB(i);
        TValue *rc = RKC(i);
        Protect(
          if (equalobj(L, rb, rc) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
	
	  // 功能:检查两个变量是否小于,满足预期则跳转。配合OP_JMP使用。
	  // iABC:A纯数字,对比较结果的预期,满足预期则跳转,B参数1的索引,C参数2的索引
      case OP_LT: {
		// if a < b then -----> index(a) = 1, index(b) = 2
		//               >----> 这里将生成两行指令:
		//               >----> OP_LT  0 1 2	// 用0,因为成立的话跳过,不成立才执行
		//               >----> OP_JMP N		// N 表示then ... end中间的指令数量
		//               >----> ...				// Instructions between "then" and "end"
        Protect(
          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }

	  // 功能:检查两个变量是否小于等于,满足预期则跳转。配合OP_JMP使用。
	  // iABC:A纯数字,对比较结果的预期,满足预期则跳转,B参数1的索引,C参数2的索引
      case OP_LE: {
		  // if a <= b then -----> index(a) = 1, index(b) = 2
		  //                >----> 这里将生成两行指令:
		  //                >----> OP_LE  0 1 2	// 用0,因为成立的话跳过,不成立才执行
		  //                >----> OP_JMP N		// N 表示then ... end中间的指令数量
		  //                >----> ...			// Instructions between "then" and "end"
		  Protect(
          if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
Esempio n. 14
0
File: vm.c Progetto: joelagnel/ktap
static void ktap_execute(ktap_state *ks)
{
	int exec_count = 0;
	ktap_callinfo *ci;
	ktap_lclosure *cl;
	ktap_value *k;
	unsigned int instr, opcode;
	StkId base; /* stack pointer */
	StkId ra; /* register pointer */
	int res, nresults; /* temp varible */

	ci = ks->ci;

 newframe:
	cl = CLVALUE(ci->func);
	k = cl->p->k;
	base = ci->u.l.base;

 mainloop:
	/* main loop of interpreter */

	/* dead loop detaction */
	if (exec_count++ == 10000) {
		if (G(ks)->mainthread != ks) {
			kp_error(ks, "non-mainthread executing too much, "
				     "please try to enlarge execution limit\n");
			return;
		}

		cond_resched();
		if (signal_pending(current)) {
			flush_signals(current);
			return;
		}
		exec_count = 0;
	}

	instr = *(ci->u.l.savedpc++);
	opcode = GET_OPCODE(instr);

	/* ra is target register */
	ra = RA(instr);

	switch (opcode) {
	case OP_MOVE:
		setobj(ra, base + GETARG_B(instr));
		break;
	case OP_LOADK:
		setobj(ra, k + GETARG_Bx(instr));
		break;
	case OP_LOADKX:
		setobj(ra, k + GETARG_Ax(*ci->u.l.savedpc++));
		break;
	case OP_LOADBOOL:
		setbvalue(ra, GETARG_B(instr));
		if (GETARG_C(instr))
			ci->u.l.savedpc++;
		break;
	case OP_LOADNIL: {
		int b = GETARG_B(instr);
		do {
			setnilvalue(ra++);
		} while (b--);
		break;
		}
	case OP_GETUPVAL: {
		int b = GETARG_B(instr);
		setobj(ra, cl->upvals[b]->v);
		break;
		}
	case OP_GETTABUP: {
		int b = GETARG_B(instr);
		gettable(ks, cl->upvals[b]->v, RKC(instr), ra);
		base = ci->u.l.base;
		break;
		}
	case OP_GETTABLE:
		gettable(ks, RB(instr), RKC(instr), ra);
		base = ci->u.l.base;
		break;
	case OP_SETTABUP: {
		int a = GETARG_A(instr);
		settable(ks, cl->upvals[a]->v, RKB(instr), RKC(instr));
		base = ci->u.l.base;
		break;
		}
	case OP_SETUPVAL: {
		ktap_upval *uv = cl->upvals[GETARG_B(instr)];
		setobj(uv->v, ra);
		break;
		}
	case OP_SETTABLE:
		settable(ks, ra, RKB(instr), RKC(instr));
		base = ci->u.l.base;
		break;
	case OP_NEWTABLE: {
		int b = GETARG_B(instr);
		int c = GETARG_C(instr);
		ktap_table *t = kp_table_new(ks);
		sethvalue(ra, t);
		if (b != 0 || c != 0)
			kp_table_resize(ks, t, fb2int(b), fb2int(c));
		break;
		}
	case OP_SELF: {
		StkId rb = RB(instr);
		setobj(ra+1, rb);
		gettable(ks, rb, RKC(instr), ra);
		base = ci->u.l.base;
		break;
		}
	case OP_ADD:
		arith_op(ks, NUMADD);
		break;
	case OP_SUB:
		arith_op(ks, NUMSUB);
		break;
	case OP_MUL:
		arith_op(ks, NUMMUL);
		break;
	case OP_DIV:
		/* divide 0 checking */
		if (!nvalue(RKC(instr))) {
			kp_error(ks, "divide 0 arith operation\n");
			return;
		}
		arith_op(ks, NUMDIV);
		break;
	case OP_MOD:
		/* divide 0 checking */
		if (!nvalue(RKC(instr))) {
			kp_error(ks, "mod 0 arith operation\n");
			return;
		}
		arith_op(ks, NUMMOD);
		break;
	case OP_POW:
		kp_error(ks, "ktap don't support pow arith in kernel\n");
		return;
	case OP_UNM: {
		ktap_value *rb = RB(instr);
		if (ttisnumber(rb)) {
			ktap_number nb = nvalue(rb);
			setnvalue(ra, NUMUNM(nb));
		}
		break;
		}
	case OP_NOT:
		res = isfalse(RB(instr));
		setbvalue(ra, res);
		break;
	case OP_LEN: {
		int len = kp_objlen(ks, RB(instr));
		if (len < 0)
			return;
		setnvalue(ra, len);
		break;
		}
	case OP_CONCAT: {
		int b = GETARG_B(instr);
		int c = GETARG_C(instr);
		ktap_concat(ks, b, c);
		break;
		}
	case OP_JMP:
		dojump(ci, instr, 0);
		break;
	case OP_EQ: {
		ktap_value *rb = RKB(instr);
		ktap_value *rc = RKC(instr);
		if ((int)equalobj(ks, rb, rc) != GETARG_A(instr))
			ci->u.l.savedpc++;
		else
			donextjump(ci);

		base = ci->u.l.base;
		break;
		}
	case OP_LT:
		if (lessthan(ks, RKB(instr), RKC(instr)) != GETARG_A(instr))
			ci->u.l.savedpc++;
		else
			donextjump(ci);
		base = ci->u.l.base;
		break;
	case OP_LE:
		if (lessequal(ks, RKB(instr), RKC(instr)) != GETARG_A(instr))
			ci->u.l.savedpc++;
		else
			donextjump(ci);
		base = ci->u.l.base;
		break;
	case OP_TEST:
		if (GETARG_C(instr) ? isfalse(ra) : !isfalse(ra))
			ci->u.l.savedpc++;
		else
			donextjump(ci);
		break;
	case OP_TESTSET: {
		ktap_value *rb = RB(instr);
		if (GETARG_C(instr) ? isfalse(rb) : !isfalse(rb))
			ci->u.l.savedpc++;
		else {
			setobj(ra, rb);
			donextjump(ci);
		}
		break;
		}
	case OP_CALL: {
		int b = GETARG_B(instr);
		int ret;

		nresults = GETARG_C(instr) - 1;

		if (b != 0)
			ks->top = ra + b;

		ret = precall(ks, ra, nresults);
		if (ret) { /* C function */
			if (nresults >= 0)
				ks->top = ci->top;
			base = ci->u.l.base;
			break;
		} else { /* ktap function */
			ci = ks->ci;
			/* this flag is used for return time, see OP_RETURN */
			ci->callstatus |= CIST_REENTRY;
			goto newframe;
		}
		break;
		}
	case OP_TAILCALL: {
		int b = GETARG_B(instr);

		if (b != 0)
			ks->top = ra+b;
		if (precall(ks, ra, -1))  /* C function? */
			base = ci->u.l.base;
		else {
			int aux;

			/* 
			 * tail call: put called frame (n) in place of
			 * caller one (o)
			 */
			ktap_callinfo *nci = ks->ci;  /* called frame */
			ktap_callinfo *oci = nci->prev;  /* caller frame */
			StkId nfunc = nci->func;  /* called function */
			StkId ofunc = oci->func;  /* caller function */
			/* last stack slot filled by 'precall' */
			StkId lim = nci->u.l.base +
				    CLVALUE(nfunc)->p->numparams;

			/* close all upvalues from previous call */
			if (cl->p->sizep > 0)
				function_close(ks, oci->u.l.base);

			/* move new frame into old one */
			for (aux = 0; nfunc + aux < lim; aux++)
				setobj(ofunc + aux, nfunc + aux);
			/* correct base */
			oci->u.l.base = ofunc + (nci->u.l.base - nfunc);
			/* correct top */
			oci->top = ks->top = ofunc + (ks->top - nfunc);
			oci->u.l.savedpc = nci->u.l.savedpc;
			/* remove new frame */
			ci = ks->ci = oci;
			/* restart ktap_execute over new ktap function */
			goto newframe;
		}
		break;
		}
	case OP_RETURN: {
		int b = GETARG_B(instr);
		if (b != 0)
			ks->top = ra+b-1;
		if (cl->p->sizep > 0)
			function_close(ks, base);
		b = poscall(ks, ra);

		/* if it's called from external invocation, just return */
		if (!(ci->callstatus & CIST_REENTRY))
			return;

		ci = ks->ci;
		if (b)
			ks->top = ci->top;
		goto newframe;
		}
	case OP_FORLOOP: {
		ktap_number step = nvalue(ra+2);
		/* increment index */
		ktap_number idx = NUMADD(nvalue(ra), step);
		ktap_number limit = nvalue(ra+1);
		if (NUMLT(0, step) ? NUMLE(idx, limit) : NUMLE(limit, idx)) {
			ci->u.l.savedpc += GETARG_sBx(instr);  /* jump back */
			setnvalue(ra, idx);  /* update internal index... */
			setnvalue(ra+3, idx);  /* ...and external index */
		}
		break;
		}
	case OP_FORPREP: {
		const ktap_value *init = ra;
		const ktap_value *plimit = ra + 1;
		const ktap_value *pstep = ra + 2;

		if (!ktap_tonumber(init, ra)) {
			kp_error(ks, KTAP_QL("for")
				 " initial value must be a number\n");
			return;
		} else if (!ktap_tonumber(plimit, ra + 1)) {
			kp_error(ks, KTAP_QL("for")
				 " limit must be a number\n");
			return;
		} else if (!ktap_tonumber(pstep, ra + 2)) {
			kp_error(ks, KTAP_QL("for") " step must be a number\n");
			return;
		}

		setnvalue(ra, NUMSUB(nvalue(ra), nvalue(pstep)));
		ci->u.l.savedpc += GETARG_sBx(instr);
		break;
		}
	case OP_TFORCALL: {
		StkId cb = ra + 3;  /* call base */
		setobj(cb + 2, ra + 2);
		setobj(cb + 1, ra + 1);
		setobj(cb, ra);
		ks->top = cb + 3;  /* func. + 2 args (state and index) */
		kp_call(ks, cb, GETARG_C(instr));
		base = ci->u.l.base;
		ks->top = ci->top;
		instr = *(ci->u.l.savedpc++);  /* go to next instruction */
		ra = RA(instr);
		}
		/*go through */
	case OP_TFORLOOP:
		if (!ttisnil(ra + 1)) {  /* continue loop? */
			setobj(ra, ra + 1);  /* save control variable */
			ci->u.l.savedpc += GETARG_sBx(instr);  /* jump back */
		}
		break;
	case OP_SETLIST: {
		int n = GETARG_B(instr);
		int c = GETARG_C(instr);
		int last;
		ktap_table *h;

		if (n == 0)
			n = (int)(ks->top - ra) - 1;
		if (c == 0)
			c = GETARG_Ax(*ci->u.l.savedpc++);

		h = hvalue(ra);
		last = ((c - 1) * LFIELDS_PER_FLUSH) + n;
		if (last > h->sizearray)  /* needs more space? */
			kp_table_resizearray(ks, h, last);

		for (; n > 0; n--) {
			ktap_value *val = ra+n;
			kp_table_setint(ks, h, last--, val);
		}
		/* correct top (in case of previous open call) */
		ks->top = ci->top;
		break;
		}
	case OP_CLOSURE: {
		/* need to use closure cache? (multithread contention issue)*/
		ktap_proto *p = cl->p->p[GETARG_Bx(instr)];
		pushclosure(ks, p, cl->upvals, base, ra);
		break;
		}
	case OP_VARARG: {
		int b = GETARG_B(instr) - 1;
		int j;
		int n = (int)(base - ci->func) - cl->p->numparams - 1;
		if (b < 0) {  /* B == 0? */
			b = n;  /* get all var. arguments */
			checkstack(ks, n);
			/* previous call may change the stack */
			ra = RA(instr);
			ks->top = ra + n;
		}
		for (j = 0; j < b; j++) {
			if (j < n) {
				setobj(ra + j, base - n + j);
			} else
				setnilvalue(ra + j);
		}
		break;
		}
	case OP_EXTRAARG:
		return;

	case OP_EVENT: {
		struct ktap_event *e = ks->current_event;

		if (unlikely(!e)) {
			kp_error(ks, "invalid event context\n");
			return;
		}
		setevalue(ra, e);
		break;
		}

	case OP_EVENTNAME: {
		struct ktap_event *e = ks->current_event;

		if (unlikely(!e)) {
			kp_error(ks, "invalid event context\n");
			return;
		}
		setsvalue(ra, kp_tstring_new(ks, e->call->name));
		break;
		}
	case OP_EVENTARG:
		if (unlikely(!ks->current_event)) {
			kp_error(ks, "invalid event context\n");
			return;
		}

		kp_event_getarg(ks, ra, GETARG_B(instr));		
		break;
	case OP_LOAD_GLOBAL: {
		ktap_value *cfunc = cfunction_cache_get(ks, GETARG_C(instr));
		setobj(ra, cfunc);
		}
		break;

	case OP_EXIT:
		return;
	}

	goto mainloop;
}
#define AC_NO_PLUS KC_MINS
#define AC_NO_BSLS KC_EQUAL
#define AC_NO_QUOTE KC_BSLS
#define AC_NO_MINS KC_SLSH
#define AC_NO_PIPE KC_GRAVE


const uint16_t PROGMEM actionmaps[][MATRIX_ROWS][MATRIX_COLS] = {
  KEYMAP( /* 0: mostly letters */
    Q,   W,         E,         R,         T,   					   /*|,, |*/         Y,              U,         I,   	          O,    P,    \
    A,   S,         D,         F,         G,   					   /*|,, |*/         H,              J,         K,   	          L,    COMM, \
		Z,   X,         C,         V,         B,               /*|,, |*/         N,              M,         COMM,           DOT,  KP_SLASH, \
    ESC, TAPT(3),   OSM(LGUI), OSM(LSFT), MK(LCTL,BSPC), TAPT(1), TAPT(2),   MK(LALT,SPC),   TACK(TAB), TACSK(SLSH), SH(2), ENT
  ),
  KEYMAP( /* layer one is mostly for programming and shell. lots of idea shortcute on left, not sure how much i will use them.*/
    ACK(7),  CTRL(W),    NO_AE,      SH(F10),     ACSK(L),                     SH(NO_ACNT), RA(7), RA(0), NO_OE,   SH(1), \
    NO_AA,   ACK(LEFT),  CSK(ENT),   ACK(RIGHT),  ALT(INS),                    0,           SH(8), SH(9), NO_PIPE, RA(4), \
    CSK(A),  CSK(F),     ACSK(T),    ALT(V),      CTRL(F9),                    SH(NO_BSLS), RA(8), RA(9), SH(6),   RA(NO_ACNT), \
    ESC,     TRNS,       OSM(LGUI),  OSM(LSFT),   TRNS,    TRNS,    TRNS,      SPC,         OFF(1),RA(2), NO_QUOTE,KP_EQUAL
  ),
  KEYMAP( /* hold space brings up move pad and numpad */
    INS,      HOME,   UP  ,      END  ,     PGUP,                          SH(5),         7     , 8  , 9, SH(NO_QUOTE),     \
    DEL,      LEFT,   DOWN,      RIGHT,     PGDN,                          NO_MINS,       4     , 5  , 6, NO_PLUS, \
    GUI(1),   GUI(2), GUI(3),    GUI(4),    GUI(5),                        RA(4),         1     , 2  , 3, NO_BSLS,      \
    ACK(DEL), TRNS, OSM(LGUI), OSM(LSFT),   GUI(D) , TRNS, TRNS,           MK(LALT,SPC),  OFF(1), DOT, 0, KP_EQUAL
  ),
  KEYMAP( /* hold tab to have fpad and mouse */
    F1,     F2,    F3,        F4,         F5,                             WH_D ,           BTN1   ,  MS_U ,         BTN2 ,      SH(3) , \
    F6,     F7,    F8,        F9,         F10,                            WH_U ,           MS_L   ,  MS_D ,         MS_R ,      BTN3 , \
    F11,    F12,   F13,       F14,        BOOT,                           NO   ,           ACL0   ,  NO_LT,         SH(NO_LT) , BTN4 , \
    BOOT, TRNS,   OSM(LGUI), OSM(LSFT),   MK(LCTL,BSPC), TRNS, TRNS,      MK(LALT,SPC),    TACK(TAB),TACSK(MINS) , SH(NO_BSLS), KP_EQUAL
Esempio n. 16
0
void CatalogDB::GetAllObjects(const QString &catalog,
                              QList< SkyObject* > &sky_list,
                              QList < QPair <int, QString> > &object_names,
                              CatalogComponent *catalog_ptr) {
    sky_list.clear();
    QString selected_catalog = QString::number(FindCatalog(catalog));
    skydb_.open();
    QSqlQuery get_query(skydb_);
    get_query.prepare("SELECT Epoch, Type, RA, Dec, Magnitude, Prefix, "
                      "IDNumber, LongName, MajorAxis, MinorAxis, "
                      "PositionAngle, Flux FROM ObjectDesignation JOIN DSO "
                      "JOIN Catalog WHERE Catalog.id = :catID AND "
                      "ObjectDesignation.id_Catalog = Catalog.id AND "
                      "ObjectDesignation.UID_DSO = DSO.UID");
    get_query.bindValue("catID", selected_catalog);

//     kWarning() << get_query.lastQuery();
//     kWarning() << get_query.lastError();
//     kWarning() << FindCatalog(catalog);

    if (!get_query.exec()) {
        kWarning() << get_query.lastQuery();
        kWarning() << get_query.lastError();
    }

    while (get_query.next()) {

        int cat_epoch = get_query.value(0).toInt();
        unsigned char iType = get_query.value(1).toInt();
        dms RA(get_query.value(2).toDouble());
        dms Dec(get_query.value(3).toDouble());
        float mag = get_query.value(4).toFloat();
        QString catPrefix = get_query.value(5).toString();
        int id_number_in_catalog = get_query.value(6).toInt();
        QString lname = get_query.value(7).toString();
        float a = get_query.value(8).toFloat();
        float b = get_query.value(9).toFloat();
        float PA = get_query.value(10).toFloat();
        float flux = get_query.value(11).toFloat();

        QString name = catPrefix + ' ' + QString::number(id_number_in_catalog);
        SkyPoint t;
        t.set(RA, Dec);

        if (cat_epoch == 1950) {
            // Assume B1950 epoch
            t.B1950ToJ2000();  // t.ra() and t.dec() are now J2000.0
                               // coordinates
        } else if (cat_epoch == 2000) {
            // Do nothing
                 { }
               } else {
                 // FIXME: What should we do?
                 // FIXME: This warning will be printed for each line in the
                 //        catalog rather than once for the entire catalog
                 kWarning() << "Unknown epoch while dealing with custom "
                               "catalog. Will ignore the epoch and assume"
                               " J2000.0";
        }

        RA = t.ra();
        Dec = t.dec();

        if (iType == 0) {  // Add a star
            StarObject *o = new StarObject(RA, Dec, mag, lname);
            sky_list.append(o);
        } else {  // Add a deep-sky object
            DeepSkyObject *o = new DeepSkyObject(iType, RA, Dec, mag,
                                                 name, QString(), lname,
                                                 catPrefix, a, b, -PA);
            o->setFlux(flux);
            o->setCustomCatalog(catalog_ptr);

            sky_list.append(o);

            // Add name to the list of object names
            if (!name.isEmpty()) {
                object_names.append(qMakePair<int,QString>(iType, name));
            }
        }

        if (!lname.isEmpty() && lname != name) {
            object_names.append(qMakePair<int,QString>(iType, lname));
        }
    }

    get_query.clear();
    skydb_.close();
}
Esempio n. 17
0
 {"movtc",	OP(0x36),		"cN,rP,rA",	F_CEX},
 {"mulhi",	OP(0x1D),		"rD",		F_CEX},
 {"muli",	OP(0x2E),		"rD,rA,cI",	F_CEX},
 {"muls",	OP(0x05),		"rD,rA,rB",	F_CEX},
 {"muls_16",	OP(0x08),		"rD,rA,rB",	F_CEX},
 {"mulu",	OP(0x06),		"rD,rA,rB",	F_CEX},
 {"mulu_16",	OP(0x09),		"rD,rA,rB",	F_CEX},
 {"mulus",	OP(0x07),		"rD,rA,rB",	F_CEX},
 {"mulus_16",	OP(0x0A),		"rD,rA,rB",	F_CEX},
 {"nop",	NOP,			"",		0},
 {"not",	OP(0x14),		"rD,rA",	F_CEX},
 {"or",	OP(0x0B),		"rD,rA,rB",	F_CEX},
 {"ori",	OP(0x2A),		"rD,rA,cU",	F_CEX},
 {"rcon",	OP(0x1E),		"rA",		0},
 {"reti",	OP(0x17),		"",		0},
 {"retu",	OP(0x1F)|RA(0x1F),	"",		0},
 {"scall",	OP(0x3B)|RD(0x1F),	"",		F_CEX},
 {"scon",	OP(0x1C),		"rD",		0},
 {"sext",	OP(0x0C),		"rD,rA,rB",	F_CEX},
 {"sexti",	OP(0x2B),		"rD,rA,cb",	F_CEX},
 {"sll",	OP(0x0D)|SM(1),		"rD,rA,rB",	F_CEX|F_SHIFT},
 {"slli",	OP(0x0D),		"rD,rA,cK",	F_CEX|F_SHIFT},
 {"sra",	OP(0x0E)|SM(1),		"rD,rA,rB",	F_CEX|F_SHIFT},
 {"srai",	OP(0x0E),		"rD,rA,cK",	F_CEX|F_SHIFT},
 {"srl",	OP(0x0F)|SM(1),		"rD,rA,rB",	F_CEX|F_SHIFT},
 {"srli",	OP(0x0F),		"rD,rA,cK",	F_CEX|F_SHIFT},
 {"st",	OP(0x34),		"rB,rA,cS",	F_CEX},
 {"sub",	OP(0x10),		"rD,rA,rB",	F_CEX},
 {"subu",	OP(0x11),		"rD,rA,rB",	F_CEX},
 {"swm",	OP(0x2F),		"cK",		0},
 {"trap",	OP(0x18),		"cb",		F_CEX},
Esempio n. 18
0
zysst()

{
    IATYPE	whence, temp;
    FILEPOS  offset;
    register struct fcblk *fcb = WA (struct fcblk *);
    register struct ioblk *iob = MK_MP(fcb->iob, struct ioblk *);
    register struct icblk *icp;

    /* ensure iob is open, fail if unsuccessful */
    if ( !(iob->flg1 & IO_OPN) )
        return EXIT_3;

#if PIPES
    /* not allowed to do a set of a pipe */
    if ( iob->flg2 & IO_PIP )
        return EXIT_4;
#endif					/* PIPES */

    /* whence may come in either integer or string form */
    icp = WC( struct icblk * );
    if ( !getint(icp,&whence) )
        return EXIT_1;

#if SETREAL
    /* offset comes in as a real in RA */
    offset = RA(FILEPOS);
#else
    /* offset may come in either integer or string form */
    icp = WB( struct icblk * );
    if ( !getint(icp,&temp) ) {
        struct scblk *scp;
        scp = (struct scblk *)icp;
        if (!checkstr(scp) || scp->len != 1)
            return EXIT_1;
        temp = whence;
        switch (uppercase(scp->str[0])) {
        case 'P':
            whence = 0;
            break;

        case 'H':
            temp = (whence << 15) + ((int)doset(iob,0,1) & 0x7FFFL);
            whence = 0;
            break;

        case 'R':
            whence = 1;
            break;

        case 'E':
            whence = 2;
            break;

        case 'C':
            if ( fcb->mode == 0 && temp > 0 && temp <= (word)maxsize ) {
                fcb->rsz = temp;
                temp = 0;
                whence = 1;			/* return current position */
                break;
            }
            else {
                if (temp < 0 || temp > (word)maxsize)
                    return EXIT_2;
                else
                    return EXIT_1;
            }

        default:
            return EXIT_1;		/* Unrecognised control */
        }
    }
    offset = (FILEPOS)temp;
#endif
    /*  finally, set the file position  */
    offset = doset( iob, offset, (int)whence );

    /*  test for error.  01.02 */
    if ( offset < (FILEPOS)0 )
        return EXIT_5;
#if SETREAL
    /*  return resulting position in RA.  01.07  */
    SET_RA( offset );
#else
    /*  return resulting position in IA.  01.02  */
    SET_IA( (IATYPE)offset );
#endif

    /* normal return */
    return NORMAL_RETURN;
}
Esempio n. 19
0
/* bjartek atreus layout for norwegian keyboard
 * - all the mods are oneshot. see here for information about this. https://github.com/tmk/tmk_keyboard/blob/master/tmk_core/doc/keymap.md
 * - layer one has norwegian special characters at AEO positions
 * - needs us mac keyboard layout
 */

const uint16_t PROGMEM actionmaps[][MATRIX_ROWS][MATRIX_COLS] = {
KEYMAP(
Q       , W        , E        , R        , T          ,                       Y         , U         , I       , O         , P        , \
A       , S        , D        , F        , G          ,                       H         , J         , K       , L         , SCLN     , \
Z       , X        , C        , V        , B          ,                       N         , M         , COMM    , DOT       , SLSH     , \
ESC     , OSM(RALT), OSM(LCTL), OSM(LSFT), TAP(1,BSPC), OSM(LGUI), OSM(LALT), TAP(2,SPC), TAP(3,TAB), MINS    , QUOT      , ENT     ),

KEYMAP(
AGK(F7) , GUI(F12) , RA(QUOT) , ACK(R)   , AGSK(L)    ,                       SH(6)     , SH(LBRC)  , SH(RBRC), RA(O)     , SH(1)    , \
RA(A)   , GUI(LBRC), CSK(ENT) , GUI(RBRC), GSK(T)     ,                       0         , SH(9)     , SH(0)   , SH(BSLS)  , SH(4)    , \
GSK(A)  , GSK(F)   , CTRL(T)  , ALT(V)   , GUI(F9)    ,                       GRAVE     , LBRC      , RBRC    , SH(7)     , SH(GRAVE), \
GA      , OSM(RALT), OSM(LCTL), OSM(LSFT), TRNS       , OSM(LGUI), OSM(LALT), CTRL(F2)  , OFF(1)    , SH(2)   , QUOT      , OSM(LGUI)),

KEYMAP(
INS     , HOME     , UP       , END      , PGUP       ,                       SH(5)     , 7         , 8       , 9         , SH(8)    , \
DEL     , LEFT     , DOWN     , RIGHT    , PGDN       ,                       MINS      , 4         , 5       , 6         , SH(EQUAL), \
VOLU    , MPRV     , MPLY     , MNXT     , GCK(Q)     ,                       SH(4)     , 1         , 2       , 3         , BSLS     , \
VOLD    , MUTE     , OSM(LCTL), OSM(LSFT), CSK(SPC)   , OSM(LGUI), OSM(LALT), TRNS      , OFF(1)    , DOT     , 0         , KP_EQUAL),

KEYMAP(
F1      , F2       , F3       , F4       , F5         ,                       WH_D      , BTN1      , MS_U    , BTN2      , SH(3)    , \
F6      , F7       , F8       , F9       , F10        ,                       WH_U      , MS_L      , MS_D    , MS_R      , BTN3     , \
F11     , F12      , F13      , F14      , BOOT       ,                       NO        , ACL0      , NO      , NO        , NO       , \
GA      , OSM(RALT), OSM(LCTL), OSM(LSFT), GS         , OSM(LGUI), OSM(LALT), SPC       , TRNS      , MINS    , SH(BSLS)  , KP_EQUAL)
Esempio n. 20
0
StkId luaV_execute (lua_State *L) {
  LClosure *cl;
  TObject *k;
  const Instruction *pc;
 callentry:  /* entry point when calling new functions */
  L->ci->u.l.pc = &pc;
  if (L->hookmask & LUA_MASKCALL)
    luaD_callhook(L, LUA_HOOKCALL, -1);
 retentry:  /* entry point when returning to old functions */
  lua_assert(L->ci->state == CI_SAVEDPC ||
             L->ci->state == (CI_SAVEDPC | CI_CALLING));
  L->ci->state = CI_HASFRAME;  /* activate frame */
  pc = L->ci->u.l.savedpc;
  cl = &clvalue(L->base - 1)->l;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId base, ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L);
      if (L->ci->state & CI_YIELD) {  /* did hook yield? */
        L->ci->u.l.savedpc = pc - 1;
        L->ci->state = CI_YIELD | CI_SAVEDPC;
        return NULL;
      }
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    base = L->base;
    ra = RA(i);
    lua_assert(L->ci->state & CI_HASFRAME);
    lua_assert(base == L->ci->base);
    lua_assert(L->top <= L->stack + L->stacksize && L->top >= base);
    lua_assert(L->top == L->ci->top ||
         GET_OPCODE(i) == OP_CALL ||   GET_OPCODE(i) == OP_TAILCALL ||
         GET_OPCODE(i) == OP_RETURN || GET_OPCODE(i) == OP_SETLISTO);
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(ra, RB(i));
        break;
      }
      case OP_LOADK: {
        setobj2s(ra, KBx(i));
        break;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        break;
      }
      case OP_LOADNIL: {
        TObject *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        break;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(ra, cl->upvals[b]->v);
        break;
      }
      case OP_GETGLOBAL: {
        TObject *rb = KBx(i);
        const TObject *v;
        lua_assert(ttisstring(rb) && ttistable(&cl->g));
        v = luaH_getstr(hvalue(&cl->g), tsvalue(rb));
        if (!ttisnil(v)) { setobj2s(ra, v); }
        else
          setobj2s(XRA(i), luaV_index(L, &cl->g, rb, 0));
        break;
      }
      case OP_GETTABLE: {
        StkId rb = RB(i);
        TObject *rc = RKC(i);
        if (ttistable(rb)) {
          const TObject *v = luaH_get(hvalue(rb), rc);
          if (!ttisnil(v)) { setobj2s(ra, v); }
          else
            setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
        }
        else
          setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
        break;
      }
      case OP_SETGLOBAL: {
        lua_assert(ttisstring(KBx(i)) && ttistable(&cl->g));
        luaV_settable(L, &cl->g, KBx(i), ra);
        break;
      }
      case OP_SETUPVAL: {
        int b = GETARG_B(i);
        setobj(cl->upvals[b]->v, ra);  /* write barrier */
        break;
      }
      case OP_SETTABLE: {
        luaV_settable(L, ra, RKB(i), RKC(i));
        break;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        b = fb2int(b);
        sethvalue(ra, luaH_new(L, b, GETARG_C(i)));
        luaC_checkGC(L);
        break;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        TObject *rc = RKC(i);
        runtime_check(L, ttisstring(rc));
        setobjs2s(ra+1, rb);
        if (ttistable(rb)) {
          const TObject *v = luaH_getstr(hvalue(rb), tsvalue(rc));
          if (!ttisnil(v)) { setobj2s(ra, v); }
          else
            setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
        }
        else
          setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
        break;
      }
      case OP_ADD: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) + nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_ADD);
        break;
      }
      case OP_SUB: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) - nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_SUB);
        break;
      }
      case OP_MUL: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) * nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_MUL);
        break;
      }
      case OP_DIV: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) / nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_DIV);
        break;
      }
      case OP_POW: {
        Arith(L, ra, RKB(i), RKC(i), TM_POW);
        break;
      }
      case OP_UNM: {
        const TObject *rb = RB(i);
        TObject temp;
        if (tonumber(rb, &temp)) {
          setnvalue(ra, -nvalue(rb));
        }
        else {
          setnilvalue(&temp);
          if (!call_binTM(L, RB(i), &temp, ra, TM_UNM))
            luaG_aritherror(L, RB(i), &temp);
        }
        break;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        break;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        luaV_concat(L, c-b+1, c);  /* may change `base' (and `ra') */
        base = L->base;
        setobjs2s(RA(i), base+b);
        luaC_checkGC(L);
        break;
      }
      case OP_JMP: {
        dojump(pc, GETARG_sBx(i));
        break;
      }
      case OP_EQ: {
        if (equalobj(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_LT: {
        if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_LE: {
        if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_TEST: {
        TObject *rb = RB(i);
        if (l_isfalse(rb) == GETARG_C(i)) pc++;
        else {
          setobjs2s(ra, rb);
          dojump(pc, GETARG_sBx(*pc) + 1);
        }
        break;
      }
      case OP_CALL:
      case OP_TAILCALL: {
        StkId firstResult;
        int b = GETARG_B(i);
        int nresults;
        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
        nresults = GETARG_C(i) - 1;
        firstResult = luaD_precall(L, ra);
        if (firstResult) {
          if (firstResult > L->top) {  /* yield? */
            lua_assert(L->ci->state == (CI_C | CI_YIELD));
            (L->ci - 1)->u.l.savedpc = pc;
            (L->ci - 1)->state = CI_SAVEDPC;
            return NULL;
          }
          /* it was a C function (`precall' called it); adjust results */
          luaD_poscall(L, nresults, firstResult);
          if (nresults >= 0) L->top = L->ci->top;
        }
        else {  /* it is a Lua function */
          if (GET_OPCODE(i) == OP_CALL) {  /* regular call? */
            (L->ci-1)->u.l.savedpc = pc;  /* save `pc' to return later */
            (L->ci-1)->state = (CI_SAVEDPC | CI_CALLING);
          }
          else {  /* tail call: put new frame in place of previous one */
            int aux;
            base = (L->ci - 1)->base;  /* `luaD_precall' may change the stack */
            ra = RA(i);
            if (L->openupval) luaF_close(L, base);
            for (aux = 0; ra+aux < L->top; aux++)  /* move frame down */
              setobjs2s(base+aux-1, ra+aux);
            (L->ci - 1)->top = L->top = base+aux;  /* correct top */
            lua_assert(L->ci->state & CI_SAVEDPC);
            (L->ci - 1)->u.l.savedpc = L->ci->u.l.savedpc;
            (L->ci - 1)->u.l.tailcalls++;  /* one more call lost */
            (L->ci - 1)->state = CI_SAVEDPC;
            L->ci--;  /* remove new frame */
            L->base = L->ci->base;
          }
          goto callentry;
        }
        break;
      }
      case OP_RETURN: {
        CallInfo *ci = L->ci - 1;  /* previous function frame */
        int b = GETARG_B(i);
        if (b != 0) L->top = ra+b-1;
        lua_assert(L->ci->state & CI_HASFRAME);
        if (L->openupval) luaF_close(L, base);
        L->ci->state = CI_SAVEDPC;  /* deactivate current function */
        L->ci->u.l.savedpc = pc;
        /* previous function was running `here'? */
        if (!(ci->state & CI_CALLING)) {
          lua_assert((ci->state & CI_C) || ci->u.l.pc != &pc);
          return ra;  /* no: return */
        }
        else {  /* yes: continue its execution */
          int nresults;
          lua_assert(ci->u.l.pc == &pc &&
                     ttisfunction(ci->base - 1) &&
                     (ci->state & CI_SAVEDPC));
          lua_assert(GET_OPCODE(*(ci->u.l.savedpc - 1)) == OP_CALL);
          nresults = GETARG_C(*(ci->u.l.savedpc - 1)) - 1;
          luaD_poscall(L, nresults, ra);
          if (nresults >= 0) L->top = L->ci->top;
          goto retentry;
        }
      }
      case OP_FORLOOP: {
        lua_Number step, idx, limit;
        const TObject *plimit = ra+1;
        const TObject *pstep = ra+2;
        if (!ttisnumber(ra))
          luaG_runerror(L, "`for' initial value must be a number");
        if (!tonumber(plimit, ra+1))
          luaG_runerror(L, "`for' limit must be a number");
        if (!tonumber(pstep, ra+2))
          luaG_runerror(L, "`for' step must be a number");
        step = nvalue(pstep);
        idx = nvalue(ra) + step;  /* increment index */
        limit = nvalue(plimit);
        if (step > 0 ? idx <= limit : idx >= limit) {
          dojump(pc, GETARG_sBx(i));  /* jump back */
          chgnvalue(ra, idx);  /* update index */
        }
        break;
      }
      case OP_TFORLOOP: {
        int nvar = GETARG_C(i) + 1;
        StkId cb = ra + nvar + 2;  /* call base */
        setobjs2s(cb, ra);
        setobjs2s(cb+1, ra+1);
        setobjs2s(cb+2, ra+2);
        L->top = cb+3;  /* func. + 2 args (state and index) */
        luaD_call(L, cb, nvar);
        L->top = L->ci->top;
        ra = XRA(i) + 2;  /* final position of first result */
        cb = ra + nvar;
        do {  /* move results to proper positions */
          nvar--;
          setobjs2s(ra+nvar, cb+nvar);
        } while (nvar > 0);
        if (ttisnil(ra))  /* break loop? */
          pc++;  /* skip jump (break loop) */
        else
          dojump(pc, GETARG_sBx(*pc) + 1);  /* jump back */
        break;
      }
      case OP_TFORPREP: {  /* for compatibility only */
        if (ttistable(ra)) {
          setobjs2s(ra+1, ra);
          setobj2s(ra, luaH_getstr(hvalue(gt(L)), luaS_new(L, "next")));
        }
        dojump(pc, GETARG_sBx(i));
        break;
      }
      case OP_SETLIST:
      case OP_SETLISTO: {
        int bc;
        int n;
        Table *h;
        runtime_check(L, ttistable(ra));
        h = hvalue(ra);
        bc = GETARG_Bx(i);
        if (GET_OPCODE(i) == OP_SETLIST)
          n = (bc&(LFIELDS_PER_FLUSH-1)) + 1;
        else {
          n = L->top - ra - 1;
          L->top = L->ci->top;
        }
        bc &= ~(LFIELDS_PER_FLUSH-1);  /* bc = bc - bc%FPF */
        for (; n > 0; n--)
          setobj2t(luaH_setnum(L, h, bc+n), ra+n);  /* write barrier */
        break;
      }
      case OP_CLOSE: {
        luaF_close(L, ra);
        break;
      }
      case OP_CLOSURE: {
        Proto *p;
        Closure *ncl;
        int nup, j;
        p = cl->p->p[GETARG_Bx(i)];
        nup = p->nups;
        ncl = luaF_newLclosure(L, nup, &cl->g);
        ncl->l.p = p;
        for (j=0; j<nup; j++, pc++) {
          if (GET_OPCODE(*pc) == OP_GETUPVAL)
            ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
          else {
            lua_assert(GET_OPCODE(*pc) == OP_MOVE);
            ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
          }
        }
        setclvalue(ra, ncl);
        luaC_checkGC(L);
        break;
      }
    }
  }
}
Esempio n. 21
0
static inline int do_32(unsigned long inst, struct pt_regs *regs)
{
	int imm, regular, load, len, sign_ext;
	unsigned long unaligned_addr, target_val, shift;

	unaligned_addr = *idx_to_addr(regs, RA(inst));

	switch ((inst >> 25) << 1) {

	case 0x02:		/* LHI       */
		imm = 1;
		regular = 1;
		load = 1;
		len = 2;
		sign_ext = 0;
		break;
	case 0x0A:		/* LHI.bi    */
		imm = 1;
		regular = 0;
		load = 1;
		len = 2;
		sign_ext = 0;
		break;
	case 0x22:		/* LHSI      */
		imm = 1;
		regular = 1;
		load = 1;
		len = 2;
		sign_ext = 1;
		break;
	case 0x2A:		/* LHSI.bi   */
		imm = 1;
		regular = 0;
		load = 1;
		len = 2;
		sign_ext = 1;
		break;
	case 0x04:		/* LWI       */
		imm = 1;
		regular = 1;
		load = 1;
		len = 4;
		sign_ext = 0;
		break;
	case 0x0C:		/* LWI.bi    */
		imm = 1;
		regular = 0;
		load = 1;
		len = 4;
		sign_ext = 0;
		break;
	case 0x12:		/* SHI       */
		imm = 1;
		regular = 1;
		load = 0;
		len = 2;
		sign_ext = 0;
		break;
	case 0x1A:		/* SHI.bi    */
		imm = 1;
		regular = 0;
		load = 0;
		len = 2;
		sign_ext = 0;
		break;
	case 0x14:		/* SWI       */
		imm = 1;
		regular = 1;
		load = 0;
		len = 4;
		sign_ext = 0;
		break;
	case 0x1C:		/* SWI.bi    */
		imm = 1;
		regular = 0;
		load = 0;
		len = 4;
		sign_ext = 0;
		break;

	default:
		switch (inst & 0xff) {

		case 0x01:	/* LH        */
			imm = 0;
			regular = 1;
			load = 1;
			len = 2;
			sign_ext = 0;
			break;
		case 0x05:	/* LH.bi     */
			imm = 0;
			regular = 0;
			load = 1;
			len = 2;
			sign_ext = 0;
			break;
		case 0x11:	/* LHS       */
			imm = 0;
			regular = 1;
			load = 1;
			len = 2;
			sign_ext = 1;
			break;
		case 0x15:	/* LHS.bi    */
			imm = 0;
			regular = 0;
			load = 1;
			len = 2;
			sign_ext = 1;
			break;
		case 0x02:	/* LW        */
			imm = 0;
			regular = 1;
			load = 1;
			len = 4;
			sign_ext = 0;
			break;
		case 0x06:	/* LW.bi     */
			imm = 0;
			regular = 0;
			load = 1;
			len = 4;
			sign_ext = 0;
			break;
		case 0x09:	/* SH        */
			imm = 0;
			regular = 1;
			load = 0;
			len = 2;
			sign_ext = 0;
			break;
		case 0x0D:	/* SH.bi     */
			imm = 0;
			regular = 0;
			load = 0;
			len = 2;
			sign_ext = 0;
			break;
		case 0x0A:	/* SW        */
			imm = 0;
			regular = 1;
			load = 0;
			len = 4;
			sign_ext = 0;
			break;
		case 0x0E:	/* SW.bi     */
			imm = 0;
			regular = 0;
			load = 0;
			len = 4;
			sign_ext = 0;
			break;

		default:
			return -EFAULT;
		}
	}

	if (imm)
		shift = GET_IMMSVAL(IMM(inst)) * len;
	else
		shift = *idx_to_addr(regs, RB(inst)) << SV(inst);

	if (regular)
		unaligned_addr += shift;

	if (load) {

		if (!access_ok(VERIFY_READ, (void *)unaligned_addr, len))
			return -EACCES;

		get_data(unaligned_addr, &target_val, len);

		if (sign_ext)
			*idx_to_addr(regs, RT(inst)) =
			    sign_extend(target_val, len);
		else
			*idx_to_addr(regs, RT(inst)) = target_val;
	} else {

		if (!access_ok(VERIFY_WRITE, (void *)unaligned_addr, len))
			return -EACCES;

		target_val = *idx_to_addr(regs, RT(inst));
		set_data((void *)unaligned_addr, target_val, len);
	}

	if (!regular)
		*idx_to_addr(regs, RA(inst)) = unaligned_addr + shift;

	regs->ipc += 4;

	return 0;
fault:
	return -EACCES;
}
Esempio n. 22
0
//--------------------------------------------------------------
void testApp::setup(){
	cout << "ITU: " << Ritu_db(1000) << "dB => " << Ritu(6000) << endl;
	cout << "A: " << RA_db(1000) << "dB => " << RA(1000) << endl;
	cout << "B: " << RB_db(1000) << "dB => " << RB(1000) << endl;
	cout << "C: " << RC_db(1000) << "dB => " << RC(1000) << endl;
	cout << "D: " << RD_db(1000) << "dB => " << RD(1000) << endl;
	
	/* some standard setup stuff*/
	ofEnableAlphaBlending();
	ofSetupScreen();
	ofBackground(0, 0, 0);
	ofSetFrameRate(20);
	ofSetVerticalSync(false);

	EscalaF = 1.015;
	
	/* This is stuff you always need.*/
	sampleRate 			= 44100; /* Sampling Rate */
	initialBufferSize	= 512;	/* Buffer Size. you have to fill this buffer with sound*/
	lAudioOut			= new float[initialBufferSize];/* outputs */
	rAudioOut			= new float[initialBufferSize];
	lAudioIn			= new float[initialBufferSize];/* inputs */
	rAudioIn			= new float[initialBufferSize];
	
	/* This is a nice safe piece of code */
	memset(lAudioOut, 0, initialBufferSize * sizeof(float));
	memset(rAudioOut, 0, initialBufferSize * sizeof(float));
	
	memset(lAudioIn, 0, initialBufferSize * sizeof(float));
	memset(rAudioIn, 0, initialBufferSize * sizeof(float));
	
	//	samp.load(ofToDataPath("sinetest_stepping2.wav"));
	//	samp.load(ofToDataPath("whitenoise2.wav"));
	//	samp.load(ofToDataPath("additive22.wav"));
	//  samp.load(ofToDataPath("pinknoise2.wav"));
	//  samp.setLength(sampleRate*8);
	//  samp.clear();
	  samp.load(ofToDataPath("sweep_0_22K.wav"));
		
	fftSize = 1024;
	mfft.setup(fftSize, 512, 256);
	ifft.setup(fftSize, 512, 256);
		
	nAverages = 12;
	oct.setup(sampleRate, fftSize/2, nAverages);
	
	mfccs = (double*) malloc(sizeof(double) * 13);
	mfcc.setup(512, 42, 13, 1, 22050, sampleRate);
	
	ofxMaxiSettings::setup(sampleRate, 2, initialBufferSize);
	soundStream.setDeviceID(0);
	soundStream.listDevices();
	//ofSoundStreamSetup(2,2, this, sampleRate, initialBufferSize, 4);/* Call this last ! */
	soundStream.setup(this,2,2, sampleRate, initialBufferSize, 4);
	//soundStream.setOutput(this);

	// Determinação de curvas
	int bins =  fftSize/2;
	CurvaItu = new float[bins];
	CurvaA = new float[bins];
	CurvaB = new float[bins];
	CurvaC = new float[bins];
	CurvaD = new float[bins];
	for (int i=0; i<bins; i++){
		float f = sampleRate/bins;
		CurvaItu[i] = Ritu(i);
		CurvaA[i] = RA_db(i);
		CurvaB[i] = RB(i);
		CurvaC[i] = RC(i);
		CurvaD[i] = RD(i);
	}

	// Gravação
	wavWriter.setFormat(1, sampleRate, 16);  
	IsRecording = false;
}
int TotalLagrangianFD8NodeBrick::addInertiaLoadToUnbalance(const Vector &accel)

{

    // Check for a quick return

    if (rho == 0.0) return 0;



    static Vector ra(NumElemDof);

    int i, j;



    for (i=0; i<NumNodes; i++) {

      const Vector &RA = theNodes[i]->getRV(accel);

      if ( RA.Size() != NumDof ) {

        opserr << "TotalLagrangianFD8NodeBrick::addInertiaLoadToUnbalance(): matrix and vector sizes are incompatable \n";

        return (-1);

      }

      

      for (j=0; j<NumDof; j++) {

	    ra(i*NumDof +j) = RA(j);

      }



    }



    this->getMass();



    if (Q == 0)  

      Q = new Vector(NumElemDof);



    Q->addMatrixVector(1.0, M, ra, -1.0);



    return 0;  

    

}
Esempio n. 24
0
void luaV_execute (lua_State *L, int nexeccalls) {
  LClosure *cl;
  StkId base;
  TValue *k;
  const Instruction *pc;
 reentry:  /* entry point */
  lua_assert(isLua(L->ci));
  pc = L->savedpc;
  cl = &clvalue(L->ci->func)->l;
  base = L->base;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L, pc);
      if (L->status == LUA_YIELD) {  /* did hook yield? */
        L->savedpc = pc - 1;
        return;
      }
      base = L->base;
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        continue;
      }
      case OP_LOADNIL: {
        TValue *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_GETGLOBAL: {
        TValue g;
        TValue *rb = KBx(i);
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(rb));
        Protect(luaV_gettable(L, &g, rb, ra));
        continue;
      }
      case OP_GETTABLE: {
        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
        continue;
      }
      case OP_SETGLOBAL: {
        TValue g;
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(KBx(i)));
        Protect(luaV_settable(L, &g, KBx(i), ra));
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
        Protect(luaC_checkGC(L));
        continue;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        setobjs2s(L, ra+1, rb);
        Protect(luaV_gettable(L, rb, RKC(i), ra));
        continue;
      }
      case OP_ADD: {
        arith_op(luai_numadd, TM_ADD);
        continue;
      }
      case OP_SUB: {
        arith_op(luai_numsub, TM_SUB);
        continue;
      }
      case OP_MUL: {
        arith_op(luai_nummul, TM_MUL);
        continue;
      }
      case OP_DIV: {
        arith_op(luai_numdiv, TM_DIV);
        continue;
      }
      case OP_MOD: {
        arith_op(luai_nummod, TM_MOD);
        continue;
      }
      case OP_POW: {
        arith_op(luai_numpow, TM_POW);
        continue;
      }
      case OP_UNM: {
        TValue *rb = RB(i);
        if (ttisnumber(rb)) {
          lua_Number nb = nvalue(rb);
          setnvalue(ra, luai_numunm(nb));
        }
        else {
          Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
        }
        continue;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        continue;
      }
      case OP_LEN: {
        const TValue *rb = RB(i);
        switch (ttype(rb)) {
          case LUA_TTABLE: {
            setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
            break;
          }
          case LUA_TSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
          default: {  /* try metamethod */
            Protect(
              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
                luaG_typeerror(L, rb, "get length of");
            )
          }
        }
        continue;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
        setobjs2s(L, RA(i), base+b);
        continue;
      }
      case OP_JMP: {
        dojump(L, pc, GETARG_sBx(i));
        continue;
      }
      case OP_EQ: {
        TValue *rb = RKB(i);
        TValue *rc = RKC(i);
        Protect(
          if (equalobj(L, rb, rc) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LT: {
        Protect(
          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LE: {
        Protect(
          if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
Esempio n. 25
0
static uint format_input(uchar *input_seqfile, FILE *indfile, FILE *strfile,
			 FILE *binfile) {
  FILE *sf;
  uint line_no, input_length, name_start, name_end, i, j;
  uint input_allocsize;
  uchar *inputline;
  seqmeta_t *seqmeta;
  seqmeta_t *seq;
  uchar *sequence, *binseq, *comp;
  uchar **seq_names;
  int binsize, seqsize;
  int seq_length;
  int seq_id;

  int name_ptr, binfile_ptr, strfile_ptr;

  inputline = NULL;
  input_allocsize = 0;
  binfile_ptr = strfile_ptr = 4;
  name_ptr = 0;

  /* This holds metadata for output when we are finished. */
  MA(seq, sizeof(seqmeta_t *));
  seqmeta = NULL; 
  seq_names = NULL;

  /* This holds sequence as its read in */
  sequence = NULL;
  binseq = NULL;
  binsize = 0;
  seqsize = 0;

  sf = openfile(input_seqfile, "r", "FASTA sequence file");

  input_length = read_fullline(&inputline, &input_allocsize, sf);
  line_no = 1;
  seq_id = 0;
  while(input_length>0) {
    PUSH(seqmeta, seq_id, sizeof(seqmeta_t));
    seq = seqmeta + seq_id;

    /* Assumption: inputline at this place always contains a FASTA 
       header line */
    if (inputline[0]!='>') {
      logmsg(MSG_FATAL,"FASTA parse error at line %u in file %s: header"
	     " line expected, beginning with '>'",line_no, input_seqfile);
    }
    
    /* Recover the sequence name */
    name_start = 1;
    while(name_start < input_length && white_space(inputline[name_start])) 
      name_start++;
    name_end = name_start + 1;
    while(name_end < input_length && !white_space(inputline[name_end]))
      name_end++;

    if (name_start == input_length) {
      logmsg(MSG_FATAL,"FASTA parse error at line %u in file %s:\nsequence "
	     "name not found in header: %s\n",line_no, input_seqfile, 
	     inputline);
    }

    inputline[name_end] = 0;

    PUSH(seq_names, seq_id, sizeof(uchar *));
    seq_names[seq_id] = strdup(inputline + name_start);

    seq->name_length = name_end - name_start;
    seq->name_pos = name_ptr;
    name_ptr += seq->name_length + 1;

    /* Read in sequence data */
    seq_length = 0;
    input_length = read_fullline(&inputline, &input_allocsize, sf);
    line_no++;
    i = 0;
    while(input_length>0 && inputline[0]!='>') {
      j=0;
      if (seq_length + input_length >= seqsize) {
	seqsize += input_length;
	RA(sequence, sizeof(uchar), seqsize);
      }	
      while(j<input_length) {
	if (nucleotide(inputline[j])) {
	  sequence[seq_length++] = inputline[j];
	}
	j++;
      }
      input_length = read_fullline(&inputline, &input_allocsize, sf);
      line_no++;
    }

    seq->seq_length = seq_length;
    seq->seqstr_pos = strfile_ptr;
    seq->seqbin_pos = binfile_ptr;

    /* Output the sequence in text (string) form to the string file */
    fwrite(sequence, sizeof(uchar), seq_length, strfile);

    if (seq_length > binsize) {
      binsize = seq_length;
      RA(binseq, sizeof(uchar), binsize);
    }

    /* Convert the sequence to binary form (not packed) */
    for(j=0;j<seq_length;j++) {
      binseq[j] = base_toint(sequence[j]);
    }
    fwrite(binseq, sizeof(uchar), seq_length, binfile);

    binfile_ptr += seq_length;
    strfile_ptr += seq_length;
    seq_id++;

#if 0
    /* Generate a reverse complement meta record */
    PUSH(seq_names, seq_id, sizeof(uchar *));
    MA(seq_names[seq_id], seq->name_length+2);
    strcpy(seq_names[seq_id], seq_names[seq_id-1]);
    strcat(seq_names[seq_id], "-");

    PUSH(seqmeta, seq_id, sizeof(seqmeta_t));
    seq = seqmeta + seq_id;

    seq->name_length = strlen(seq_names[seq_id]);
    seq->name_pos = name_ptr;
    seq->seq_length = seq_length;
    seq->seqstr_pos = strfile_ptr;
    seq->seqbin_pos = binfile_ptr;

    /* Generate the actual reverse complement text sequence from the 
       "template strand" */
    MA(comp, sizeof(uchar)*seq_length);
    for(j=0;j<seq_length;j++) {
      switch(sequence[seq_length-j-1]) {
      case 'A':
	comp[j] = 'T';
	break;
      case 'C':
	comp[j] = 'G';
	break;
      case 'G':
	comp[j] = 'C';
	break;
      case 'T':
	comp[j] = 'A';
	break;
      case 'N':
      case 'X':
	comp[j] = sequence[seq_length-j-1];
	break;
      default:
	logmsg(MSG_ERROR,"Unknown nucleotide '%c' in sequence %s at position "
	       "%d\n",sequence[seq_length-j-1],seq_names[seq_id-1],
	       seq_length-j-1);
	break;
      }
    }

    /* Write out complement sequence to string file */
    fwrite(comp, sizeof(uchar), seq_length, strfile);

    /* Build complement sequence in binary form and write out to binary file */
    for(j=0;j<seq_length;j++) {
      binseq[j] = base_toint(comp[j]);
    }
    fwrite(binseq, sizeof(uchar), seq_length, binfile);

    name_ptr += seq->name_length;
    strfile_ptr += seq->seq_length;
    binfile_ptr += seq->seq_length;
    seq_id++;

    free(comp);
#endif
  }

  fclose(sf);

  free(inputline);
  free(binseq);
  free(sequence);

  fwrite(&seq_id, sizeof(uint), 1, indfile);
  fwrite(seqmeta, sizeof(seqmeta_t), seq_id, indfile);
  for(i=0;i<seq_id;i++) {
    fwrite(seq_names[i], sizeof(uchar), seqmeta[i].name_length + 1, indfile);
  }

  return seq_id;
}