Example #1
0
int main()
{
	char pstfxexp[MAX];
	int i,opnd1,opnd2,n,w;
	stack s;
	
	printf("Enter the postfix expression:\n");
	scanf("%s",pstfxexp);
	
	for(i=0;i<strlen(pstfxexp);i++)
	{
		if(dig(pstfxexp[i])==1)
		{
			push(&s,(int)(pstfxexp[i]-'0'));
		}
		
		else if(dig(pstfxexp[i])==0)
		{
			opnd2=pop(&s);
			opnd1=pop(&s);
			value=opr(pstfxexp[i],opnd1,opnd2);
			push(&s,value);
		}
		
	}
	printf("the value of the given postfix operation is %d",pop(&s));
}
Example #2
0
void parsegetc(nodeType *p)
{
    if(p==NULL)
    {
        printf("getc cannot receive NULL\n");
        exit(1);
    }
    else if(p->type==typeId)
    {
        ex(opr(READC,1,p));
    }
    else
    {
        parsegetc(p->opr.op[0]);
        ex(opr(READC,1,p->opr.op[1]));
    }
}
		void assignDataTo_derived( DLA::Matrix& lhs) const
		{
			// Zero-clear for the all matrix elements
			for ( int ri = 0; ri < this->rowSz; ri++)
				// g++ 4.8.4 does not allow me to omit 'this'
				// from 'this->rowSz', althoug rowSz is
				// a data member of the base class.
				for ( int ci = 0; ci < this->colSz; ci++)
					lhs( ri, ci) = 0.0;

			// proto::_default<> trans;

			// For Dirichlet conditions
			for ( int ci = 0; ci < dirichletConds.size(); ci++) {
				int ri = dirichletConds[ ci].innerIndex(),
						oi = dirichletConds[ ci].outerIndex();
				double spacing = dirichletConds[ ci].outerInnerSpacing();

				if ( ri < oi ) {
					lhs( ri, ci) = ExprGrammar()(
										opr( spacing, FaceToEastTag() ) );
				} else {
					lhs( ri, ci) = ExprGrammar()(
										opr( spacing, FaceToWestTag() ) );
				}
			}

			// For Neumann conditions
			for ( int i = 0; i < neumannConds.size(); i++) {
				int ri = neumannConds[ i].innerIndex(),
						oi = neumannConds[ i].outerIndex();
				double spacing = neumannConds[ i].outerInnerSpacing();

				if ( ri < oi ) {
					lhs( ri, i + dirichletConds.size())
							= ExprGrammar()(
									opr( spacing, FaceToEastTag() ) );
				} else {
					lhs( ri, i + dirichletConds.size())
							= ExprGrammar()(
									opr( spacing, FaceToWestTag() ) );
				}
			}
		}
Example #4
0
void parseputsn(nodeType *p)
{
    if(p==NULL)
    {
        printf("puts_ cannot receive NULL\n");
        exit(1);
    }
    else if(p->type==typeId || p->type==typeString)
    {
        ex(opr(PSN,1,p));
    }
    else if(p->type==typeOpr && p->opr.oper == ACCESS){
        ex(opr(PSN,1,p));
    }
    else
    {
        parseputsn(p->opr.op[0]);
        ex(opr(PSN,1,p->opr.op[1]));
    }
}
Example #5
0
void parseputcfm(nodeType *p1,nodeType *p2)
{
    if(p2==NULL)
    {
        printf("putc cannot receive NULL\n");
        exit(1);
    }
    else if(p2->type==typeId || p2->type==typeCon)
    {
        ex(opr(PC,2,p1,p2));
    }
    else if(p2->type==typeOpr && p2->opr.oper == ACCESS){
        ex(opr(PC,2,p1,p2));
    }
    else
    {
        parseputcfm(p1,p2->opr.op[0]);
        ex(opr(PC,2,p1,p2->opr.op[1]));
    }
}
Example #6
0
void execute()
{
    switch ( ir.op)
        {
        //lit
        case 1:
            lit(ir.m);
            break;
        // opr will require another sub-function to decide
        // which operation to run
        case 2:
            opr();
            break;
        //lod
        case 3:
            lod(ir.l, ir.m);
            break;
        //sto
        case 4:
            sto(ir.l, ir.m);
            break;
        //cal
        case 5:
            cal(ir.l, ir.m);
            break;
        //inc
        case 6:
            inc(ir.m);
            break;
        //jmp
        case 7:
            jmp(ir.m);
            break;
        //jpc
        case 8:
            jpc(ir.m);
            break;
        //sio
        //this will require another sub function to decide
        //which i/o to run
        case 9:
            sio();
            break;

        default:
            fprintf(output, "OP code input was invalid. ");
            sio3();
        }
        //print pc, bp, sp
        //use loop to print stack
        fprintf(output, "\t%d\t\t%d\t%d\t", pc, bp, sp);
        stackPrint();
}
Example #7
0
Type* UnaryOperation::type()
{
	if (opr() == DEREFERENCE)
	{
		auto t = operand()->type();
		if (PointerType* pt = dynamic_cast<PointerType*>(t))
		{
			auto bt = pt->baseType()->clone();
			SAFE_DELETE(t);
			return bt;
		} else
		{
			SAFE_DELETE(t);
			return new ErrorType("dereferencing a value that is not a pointer");
		}
	}
	else if (opr() == ADDRESSOF)
		return new PointerType(operand()->type(), false);
	else
		return operand()->type();
}
Example #8
0
int main(){
  lab3 lab3;
  int i,size;
  ifstream opr("file.in",ios::in);
  if(!opr){
    cerr<<"File is not opened"<<endl;
    exit(1);
  }
  opr>>size;
  vector <int> a(size);
  for(i=0;i<size;i++){
    opr>>a.at(i);
  }
  lab3.sort(a,size);
}
		void assignDataTo_derived( DLA::Matrix& lhs) const
		{
			int ri;

			// Zero-clear for the all matrix elements
			for (ri = 0; ri < this->rowSz; ri++)
				// g++ 4.8.4 does not allow me to omit 'this'
				// from 'this->rowSz', althoug rowSz is
				// a data member of the base class.
				// colSz == rowSz
				for ( int ci = 0; ci < this->colSz; ci++) lhs( ri, ci) = 0.0;

			// proto::_default<> trans;

			lhs( 0, 0) = ExprGrammar()(
							opr( spacing, westBoundarySpacing) );
			for (ri = 1; ri < this->rowSz - 1; ri++)
				lhs( ri, ri) = ExprGrammar()(
											opr( spacing, spacing) );
			lhs( this->rowSz - 1, this->rowSz - 1) = ExprGrammar()(
							opr( spacing, eastBoundarySpacing) );

			lhs( 0, 1) = ExprGrammar()(
					opr( spacing, FaceToEastTag() ) );
			for (ri = 1; ri < this->rowSz - 1; ri++) {
				lhs( ri, ri - 1) = ExprGrammar()(
						opr( spacing, FaceToWestTag() ) );
				lhs( ri, ri + 1) = ExprGrammar()(
						opr( spacing, FaceToEastTag() ) );
			}
			lhs( this->rowSz - 1, this->rowSz - 2) = ExprGrammar()(
					opr( spacing, FaceToWestTag() ) );

			/* for (ri = 0; ri < this->rowSz; ri++) {
				int ci;
				for (ci = 0; ci < ri; ci++)
					lhs( ri, ci)
						= ExprGrammar()(
								opr( spacing, FaceToWestTag() ) );

				// colSz == rowSz
				for (ci = ri + 1;  ci < this->rowSz; ci++)
					lhs( ri, ci)
						= ExprGrammar()(
								opr( spacing, FaceToEastTag() ) );
			}*/
		}
Example #10
0
data eval_expr(node expr, symrec ** symTable,list * routineList){
  data res;
  switch (expr.operator) {
    case SEMICOLON:
      {
        //c'è sempre uno statement da valutare
        //valuto il primo
        eval(expr.op[0],symTable,routineList);
        if(expr.noperands>1){
          //valuto il secondo, non è possibile per la struttura del parser averne più di due
          return eval(expr.op[1], symTable, routineList);
        }
      }
      break;
    case PRINT:
        { //statement
          data e = eval(expr.op[0], symTable,routineList);
          printData(e);
          res.type = no_op;
          return res;
        }
      break;
    case EQUALS: //statement
        {
          symrec * s = getSymbolFromIdentifier(expr.op[0]->value.id,symTable);
          //check if the variable is function
          routine * r = getRoutine(expr.op[0]->value.id.name, routineList);
          if(s == NULL && r == NULL){
            yyerror("during assignment found unknown variable or function");
            exit(NO_SUCH_VARIABLE);
          }
          //else
          data res;
          if(s!=NULL){
            res = assignment(s,expr.op[1],symTable,routineList);
          }
          if(r!=NULL){
            //TODO check if this is a function or a procedure
            res = r_assignment(r,expr.op[1], symTable,routineList);
          }
          return res;
        }
          break;
    case WHILE: //statement
        { // in ro con ambiente delta valuto <while e to c, omega> --> c <c; while e do c, omega> solo se in ro con ambiente delta posso valutare e a boleano vedi pag 54 semantica opearzionale
          data bool_guard = eval(expr.op[0],symTable,routineList);
          //here typechecking for correct return type of bool_guard...must be boolean
          if(bool_guard.b.b == true){
            eval(expr.op[1],symTable,routineList);
            //ho fatto il comando c, ora rimetto a valutazione la stessa operazione
            treeNode * newWhile = opr(WHILE,2,expr.op[0],expr.op[1]);
            eval(newWhile,symTable,routineList);
            //free(newWhile)
          }
          data res;
          res.type = no_op;
          return res;
        }
        break;
    case IF: //statement
      {
          data bool_guard = eval(expr.op[0],symTable,routineList);
          //here typechecking for correct return type of bool_guard...must be boolean
          if(bool_guard.b.b == true){
            eval(expr.op[1],symTable,routineList);
          }else if(expr.noperands == 3){ //se c'è il branch else
            eval(expr.op[2],symTable,routineList);
          }
          data res;
          res.type = no_op;
          return res;
      }
    break;
    case FOR: //statement
      {
        symrec * s = getSymbolFromIdentifier(expr.op[0]->value.id,symTable);
        if(s == NULL){
          yyerror("NO_SUCH_VARIABLE");
          exit(NO_SUCH_VARIABLE);
        }

        assignment(s,expr.op[1],symTable,routineList);
        identifier index; index.name = malloc(strlen(s->name)+1);
        strcpy(index.name,s->name);
        data id = eval_identifier(index, symTable,routineList);
        //consider only LT
        data guard = eval(expr.op[2],symTable,routineList);
        data comparison = operation(LT, id,guard);
        //here happens typechecking
        if(comparison.b.b == true){
          eval(expr.op[3],symTable,routineList);
          //incremento la variable, assume only integers
          treeNode * nextValue = constantNode(basic_int_value, id.b.i + 1);
          //assignment(s,nextValue,symTable);
          treeNode * newFor = opr(FOR,4,expr.op[0],nextValue,expr.op[2],expr.op[3]);

          eval(newFor,symTable,routineList);
          //free(newFor);
          //free(nextValue);
        }


      }
      break;
    case UMINUS:
    { data e1, e2;
      //typechecking happens here
      e1= eval(expr.op[0],symTable,routineList);
      return negate(e1);
    }
    case MINUS:
    { data e1, e2;
      //typechecking happens here
      e1= eval(expr.op[0],symTable,routineList);
      e2= eval(expr.op[1],symTable,routineList);
      return operation(MINUS, e1,e2);
    }
    break;

    case PLUS :
    { data e1, e2;
      //typechecking happens here
      e1= eval(expr.op[0],symTable,routineList);
      e2= eval(expr.op[1],symTable,routineList);
      return operation(PLUS, e1,e2);
    }
    break;

    case MULTIPLY:
    { data e1, e2;
      //typechecking happens here
      e1= eval(expr.op[0],symTable,routineList);
      e2= eval(expr.op[1],symTable,routineList);
      return operation(MULTIPLY, e1,e2);
    }
    break;

    case DIVIDE :
    { data e1, e2;
      //typechecking happens here
      e1= eval(expr.op[0],symTable,routineList);
      e2= eval(expr.op[1],symTable,routineList);
      return operation(DIVIDE, e1,e2);
    }
    break;
    case LT :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(LT, e1,e2);
      }
      break;
    case GT :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(GT, e1,e2);
      }
      break;
    case GE :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(GE, e1,e2);
      }
      break;
    case LE :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(LE, e1,e2);
      }
      break;
    case NE :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(NE, e1,e2);
      }
      break;
    case EQ :
      { data e1, e2;
        //typechecking happens here
        e1= eval(expr.op[0],symTable,routineList);
        e2= eval(expr.op[1],symTable,routineList);
        return operation(EQ, e1,e2);
      }
      break;
    default:
    yyerror("eval_expr new type not implemented");
    exit(NOT_IMPLEMENTED_YET);
    break;
  }
  return res;
}
Example #11
0
int ex(nodeType *p){
    int lbl1, lbl2;
    
    if(!p) return 0;
    switch (p->type) {
        case typeCon:
            printf("\tpush\t%d\n",p->con.value); //push the value of a constant on the stack
            break;
        case typeId:
            printf("\tpush\t%c\n",p->id.i + 'a');
            break;
        case typeOpr:
            switch (p->opr.oper) {
                case WHILE:
                    printf("L%03d:\n",lbl1 = lbl++);
                    ex(p->opr.op[0]);//evaluate/execute the "boolean" expression
                    printf("\tjz\tL%03d\n", lbl2 = lbl++);
                    ex(p->opr.op[1]);
                    printf("\tjmp\tL%03d\n",lbl1);
                    printf("L%03d:\n",lbl2);
                    break;
                case FOR:
                    //initial evaluation of i
                    ex(opr('=',2,p->opr.op[0],p->opr.op[1]));
                    printf("L%03d:\n",lbl1 = lbl++);
                    //build a guard node to be evaluated
                    ex(opr('-',2,p->opr.op[0], p->opr.op[2]));
                    printf("\tjz\tL%03d\n", lbl2 = lbl++);
                    ex(p->opr.op[3]);
                    //aggiorna la variabile
                    ex(opr('+',2,p->opr.op[0],con(1)));
                    //loop
                    printf("\tjmp\tL%03d\n",lbl1);
                    //esci dal ciclo
                    printf("L%03d:\n",lbl2);
                    break;

                case IF:
                    ex(p->opr.op[0]);
                    if(p->opr.nops > 2){
                    /* we are processing and if (then) else */
                    /* we have to manage the if branch and the else branch providing the flow control on the single stack, thus using two labels*/
                        printf("\tjz\tL%03d\n", lbl1=lbl++); //jz = jump if zero
                        ex(p->opr.op[1]);
                        printf("\tjmp\tL%03d\n",lbl2=lbl++);
                        printf("L%03d:\n",lbl1);
                        ex(p->opr.op[2]);
                        printf("L%03d:\n",lbl2);
                    }
                    else{
                        /*if in a single branch, we should check that opr.nops == 1 but for the sake of simplicity we will omit it
                        */
                        printf("\tjz\tL%03d\n", lbl1 = lbl++);
                        ex(p->opr.op[1]);
                        printf("L%03d:\n",lbl1);
                    }
                    break;
                case PRINT:
                    ex(p->opr.op[0]); //evaluate the expression and put it on the stack
                    printf("\tprint\n"); //thus print it
                    break;
                case '=':
                    ex(p->opr.op[1]); //evaluate expression and push it on the stack
                    printf("\tpop\t%c\n", p->opr.op[0]->id.i + 'a'); //pop out the variable/identifier by consuming a value on the stack - namely consumes the value of opr.op[1] and binds it to the identifier
                    break;
                case UMINUS:
                    ex(p->opr.op[0]);
                    printf("\tneg\n");
                    break;
                default: //match operators with 2 operands - we know our grammar and we know how it is done, we don't have operation with more than 2 operators. since this are operators we have to push it on the stack before consuming them
                    //if is a constant will be pushed by typeCon ---> push 10
                    //if is a id will be pushed by typeID --> push x
                    ex(p->opr.op[0]); //push operators on the stack
                    ex(p->opr.op[1]);
                    switch (p->opr.oper) {
                        case'+':
                            printf("\tadd\n");
                            break;
                        case'-':
                            printf("\tsub\n");
                            break;
                        case'*':
                            printf("\tmul\n");
                            break;
                        case'/':
                            printf("\tdiv\n");
                            break;
                        case'<':
                            printf("\tcompLT\n");
                            break;
                        case'>':
                            printf("\tcompGT\n");
                            break;
                        case GE:
                            printf("\tcompGE\n");
                            break;
                        case LE:
                            printf("\tcompLE\n");
                            break;
                        case NE:
                            printf("\tcompNE\n");
                            break;
                        case EQ:
                            printf("\tcompEQ\n");
                            break;
                    }
            }
    }
    return 0;
}
Example #12
0
int main()
{
   bool fl_end			= false,							// индикатор конца игры
   fl_hod_gamer	= false,							// индикатор хода игрока
   fl_hod_comp		= false,							// индикатор хода компа
   fl_err			= false;							// индикатор ошибки
   int a=0,b=0/*,end*/,                                            // просто переменные
   Npos=-1,                                           // номер известной позиции
   win=0,                                              // победитель
   count=1,                                            // счётчик ходов
   gamerX=-1,                                         // столбик игрока
   gamerY=-1,                                         // строка игрока
   compX=-1,                                          // столбик компа
   compY=-1;                                          // строка компа

   sys_clear_screen();
   printf_color(0x0d, "X-O by Denis Zgursky, 2005\nHelloOS port by Ilya Skriblovsky\n\n");
   printf_color(0x0d, "Controls:\n  W\nA S D   Enter\n\n");

   while(fl_end==false && count<=5)
   {
      // выводим сетку
      draw_field();

      //      int i;
      //      for( i=0;i<8;i++)
      //      {
      //         int j;
      //         for( j=0;j<8;j++)
      //            printf("%c",setka[i][j]);
      //         printf("\n");
      //      }

      // "обнуляем" переменные

      fl_hod_gamer=false;
      fl_hod_comp=false;
      gamerX=-1;
      gamerY=-1;
      compX=-1;
      compY=-1;

      // ход игрока: заполняем Field и setka

      while(fl_hod_gamer==false)
      {
         while (1)
         {
            char k = sys_getch();
            if (k == 0x0d)
            {
               gamerY = cury;
               gamerX = curx;
               break;
            }
            switch (k)
            {
               case 'w': if (cury > 0) cury--; break;
               case 's': if (cury < 2) cury++; break;
               case 'a': if (curx > 0) curx--; break;
               case 'd': if (curx < 2) curx++; break;
            }
            draw_field();
         }


         if(Field[gamerY][gamerX]==0)
         {
            Field[gamerY][gamerX]=2;
            switch(gamerY)
            {
               case 0:
                  b=gamerY+2;
                  break;
               case 1:
                  b=gamerY+3;
                  break;
               case 2:
                  b=gamerY+4;
                  break;
            }
            switch(gamerX)
            {
               case 0:
                  a=gamerX+2;
                  break;
               case 1:
                  a=gamerX+3;
                  break;
               case 2:
                  a=gamerX+4;
                  break;
            }
            setka[b][a]='X';
            fl_hod_gamer=true;
         }
         //         }
   }

   // если пятый ход, то проверяем на возможность победы и заканчиваем

   if(count==5)
   {
      fl_end=true;
      fl_hod_comp=true;
      win=Victory(Field);
   }

   // анализ первого хода

   if(count==1)
   {
      if((gamerY==0 && gamerX==0) ||
            (gamerY==0 && gamerX==2) ||
            (gamerY==2 && gamerX==0) ||
            (gamerY==2 && gamerX==2))
      {
         compY=1;
         compX=1;
      }
      if((gamerY==0 && gamerX==1) ||
            (gamerY==2 && gamerX==1))
      {
         compY=gamerY;
         compX=gamerX-1;
      }
      if((gamerY==1 && gamerX==0) ||
            (gamerY==1 && gamerX==2))
      {
         compY=gamerY+1;
         compX=gamerX;
      }
      if(gamerY==1 && gamerX==1)
      {
         compY=0;
         compX=2;
      }
      fl_hod_comp=true;
   }

   // проверка на выигрыш/проигрыш

   if(fl_hod_comp==false)
   {
      win=Victory(Field);
      if(win==1 || win==2)
      {
         fl_hod_comp=true;
         fl_end=true;
      }
   }

   // проверка на возможность выигрыша

   if(fl_hod_comp==false)
   {
      opr(Field,1,&compY,&compX);
      if(compY!=-1 && compX!=-1) fl_hod_comp=true;
   }

   // прверка на возможность проигрыша

   if(fl_hod_comp==false)
   {
      opr(Field,2,&compY,&compX);
      if(compY!=-1 && compX!=-1) fl_hod_comp=true;
   }

   // прверка на схожесть с известной позицией

   if(fl_hod_comp==false)
   {
      Npos=pos(Field);
      if(Npos!=-1)
      {
         prod(Npos,&compY,&compX);
         fl_hod_comp=true;
      }
   }

   // просто ход

   if(fl_hod_comp==false)
   {
      hod(Field,&compY,&compX);
      fl_hod_comp=true;
   }

   // заносим запись в Field и в setka, иначе ошибка

   if(fl_hod_comp==true && fl_end==false && compY!=-1 && compX!=-1)
   {
      Field[compY][compX]=1;
      switch(compY)
      {
         case 0:
            b=compY+2;
            break;
         case 1:
            b=compY+3;
            break;
         case 2:
            b=compY+4;
            break;
      }
      switch(compX)
      {
         case 0:
            a=compX+2;
            break;
         case 1:
            a=compX+3;
            break;
         case 2:
            a=compX+4;
            break;
      }
      setka[b][a]='O';
   }
   else
   {
      if(fl_end==false)
      {
         fl_err=true;
         fl_end=true;
      }
   }

   // проверяем не победил ли комп после своего хода

   if(fl_err==false && fl_hod_comp==true)
   {
      win=Victory(Field);
      if(win==1 || win==2)
         fl_end=true;
   }
   count++;
}

// если нет ошибки то выводим результат

if(fl_err==false)
{
   int i;
   for( i=0;i<8;i++)
   {
      int j;
      for( j=0;j<8;j++)
         printf("%c",setka[i][j]);
      printf("\n");
   }
   switch(win)
   {
      case 0:
         printf("Drawn game\n");
         break;
      case 1:
         printf("I win! :)\n");
         break;
      case 2:
         printf("Your win! :(\n");
         break;
   }
}
else
{
   printf("Error!Sorry!");
}

return 0;
}
Example #13
0
ret * ex(nodeType *p) {
    // Early exit on EOTree.
    if (!p) return 0;

    switch(p->type) {
        case nodeBlock:
            // This is support for scoping.
            /* NOTE: if function implementation is needed
            // just store dic_list and run it after saved EBP
            */
            {
                symrec * bk_EBP = EBP; // Backup EBP
                EBP = symTable; // new EBP from ESP

                // IMPROVEMENT: if func: ex(dec_list)
                ex(p->blk);

                symTable = EBP; // Reset ESP
                EBP = bk_EBP; // Reset EBP
                return 0;
            }
        case nodeDic:
            if (isdefsym(p->dic.name, EBP)) {
                fprintf(stderr, "[ERROR] Variable %s was previously declared.\n", p->dic.name);
                exit(1);
            }
            putsym(p->dic.name, p->dic.type);
            return 0;

        case nodeCon:
            {
                ret * r = xmalloc(sizeof(ret));
                memcpy(r, &(p->con), sizeof(ret));
                return r;
            }

        case nodeId:
            {
                symrec * s = getsym(p->id.name);
                if(!s) {
                    fprintf(stderr, "[ERROR] There is not such '%s' variable in the symtable\n", p->id.name);
                    exit(1);
                }
                return ex(con(s->value, s->type));
            }

        case nodeOpr:
            {
                // Used for expr
                mappable f = NULL;
                ret * a = NULL , * b = NULL;
                int flag = 0;

                switch(p->opr.oper) {
                    case WHILE:
                        while(coercion(ex(p->opr.op[0]), BOOLTYPE)->value)
                            ex(p->opr.op[1]);

                        return 0;

                    case FOR:
                        {
                            /*
                            * 0: var
                            * 1: initial value
                            * 2: upper boundary
                            * 3: body
                            */

                            ret * c;

                            symrec * s = getsym(p->opr.op[0]->id.name);

                            // DO first assign via opr in order to ensure
                            // type checking and coercion.
                            ex(opr(EQ, 2, p->opr.op[0], p->opr.op[1]));

                            // iterator < boundary
                            while(coercion(ex(opr(LT, 2, p->opr.op[0], p->opr.op[2])), BOOLTYPE)->value) {
                                // exec
                                ex(p->opr.op[3]);

                                // Speed up (no need for other checks)
                                s->value += 1;
                            }

                            return 0;
                        }

                    case IF:
                        {
                            if(coercion(ex(p->opr.op[0]), BOOLTYPE)->value)
                                ex(p->opr.op[1]); // IF
                            else if (p->opr.nops > 2)
                                ex(p->opr.op[2]); // ELSE (if any)
                            return 0;
                        }

                    case PRINTINT:
                    case PRINTREAL:
                    case PRINTBOOL:

                    case PRINT: // HERE NO COERCION !
                        {
                            int cmd = p->opr.oper;
                            ret * to_print = ex(p->opr.op[0]);

                            switch(to_print->type){
                                case INTTYPE:
                                    if (cmd != PRINT && cmd != PRINTINT) yyerror("Type error.");
                                    printf("%d\n", (int)(to_print->value));
                                    break;
                                case REALTYPE:
                                    if (cmd != PRINT && cmd != PRINTREAL) yyerror("Type error.");
                                    {
                                        char * fstr = (char*)xmalloc(46 + 1); // len(print(FLT_MAX);
                                        sprintf(fstr, "%f", to_print->value);

                                        // substitute comma with dot
                                        char * c = fstr;
                                        for(; *c != '.'; c++);
                                        *c = ',';
                                        printf("%s\n", fstr);

                                        free(fstr);
                                    }
                                        break;

                                case BOOLTYPE:
                                    if (cmd != PRINT && cmd != PRINTBOOL) yyerror("Type error.");
                                    if (to_print->value)
                                        printf("true\n");
                                    else
                                        printf("false\n");
                                    break;
                                default:
                                    yyerror("Unrecognized type.");
                            }
                            return 0;
                        }

                    case SEMICOLON:
                        ex(p->opr.op[0]);
                        return ex(p->opr.op[1]);

                    case EQ:
                        {
                            symrec * s = getsym(p->opr.op[0]->id.name);
                            if(s == NULL){
                                fprintf(stderr, "[ERROR] There is not such '%s' varibale in the symtable\n", p->opr.op[0]->id.name);
                                exit(1);
                            }

                            ret * val = coercion(ex(p->opr.op[1]), s->type);
                            s->value = val->value;
                            return 0;
                        }


                    case UMINUS: f = f != NULL ? f : &neg;
                    case PLUS: f = f != NULL ? f : &sum;
                    case MIN:  f = f != NULL ? f : &mni;
                    case MUL:  f = f != NULL ? f : &mul;
                    case DIV:  f = f != NULL ? f : &dvi;
                        flag = 3;

                    case LT:   f = f != NULL ? f : &lt;
                    case GT:   f = f != NULL ? f : &gt;
                    case GTE:  f = f != NULL ? f : &gte;
                    case LTE:  f = f != NULL ? f : &lte;
                        flag = max(flag, 2);

                    case NE:  f = f != NULL ? f : &neq;
                    case DEQ: f = f != NULL ? f : &deq;
                        flag = max(flag, 1);

                    case AND: f = f != NULL ? f : &and;
                    case OR:  f = f != NULL ? f : &or;
                    case NOT: f = f != NULL ? f : &not;
                        flag = max(flag, 0);
                        {
                            varTypeEnum
                                retType = BOOLTYPE,
                                valType = BOOLTYPE;

                            a = ex(p->opr.op[0]);
                            b = p->opr.nops == 2 ? ex(p->opr.op[1]) : NULL;

                            switch (flag) {
                                case 3:
                                    valType = retType = max(b ? max(a->type, b->type) : a->type, INTTYPE);
                                    break;
                                case 2:
                                    valType = max(b ? max(a->type, b->type) : a->type, INTTYPE);
                                    break;
                                case 1:
                                    valType = b ? max(a->type, b->type) : a->type;
                                    break;
                            }

                            return ex(con((*f)(
                                coercion(a, valType)->value,
                                b ? coercion(b, valType)->value : 0), retType));
                        }
                    default:
                        yyerror("Operator not matched.");
                }
                break;
            }
        default:
            yyerror("Node was not matched.");
    }

    yyerror("WTF! This should be DEAD CODE.");
    return 0;
}
Example #14
0
void executeInstruction()
{
    switch(ir.op)
    {
    case 1:
        lit();
        break;
    case 2:
        opr();
        break;
    case 3:
        lod();
        break;
    case 4:
        sto();
        break;
    case 5:
        cal();
        break;
    case 6:
        inc();
        break;
    case 7:
        jmp();
        break;
    case 8:
        jpc();
        break;
    case 9:
        sio();
    default:
        break;

    }

    void opr()
{
    switch ( ir.m)
    {
        //rtn
        case 0:
            ret();
            break;
        //neg
        case 1:
            neg();
            break;
       //add
        case 2:
            add();
            break;
       //sub
        case 3:
            sub();
            break;
        //mul
        case 4:
            mul();
            break;
        //div
        case 5:
            divid();
            break;
        //odd
        case 6:
            odd();
            break;
        //mod
        case 7:
            mod();
            break;
        //eql
        case 8:
            eql();
            break;
        //neq
        case 9:
            neq();
            break;
        //lss
        case 10:
            lss();
            break;
        //leq
        case 11:
            leq();
            break;
        //gtr
        case 12:
            gtr();
            break;
        //geq
        case 13:
            geq();
            break;

        default:
            fprintf(output, "OP code input was invalid. ");
            halt = 1;
            break;
    }
}

}