Exemple #1
0
void factor(){
  int l;
  int m;
  symTableEntry* symbol;
  if(currentToken == identsym){
    //First looking for a constant that matches
    symbol = findSymbol(symTable, CONST, tokenVal.string, scope);
    if(findConst(tokenVal.string, scope, &m)){
      genCode(LIT, 0, m);
    }else if(findVar(tokenVal.string, scope, &l, &m)){
      //If that fails, looking for a variable
        genCode(LOD, l, m);
    }else{
        throwError(UNDEC_ID);
    }
    readToken();
  }else if(currentToken == numbersym){
    genCode(LIT, 0, tokenVal.numeric);
    readToken();
  }else if(currentToken == lparentsym){
    readToken();
    
    expression();
    
    if(currentToken != rparentsym)
      throwError(RPAREN_MISS);
    else
      readToken();
  }
  else
    throwError(PREC_FACTOR_CANNOT_BEGIN_SYM);
  
  return;
}
void ast::ReadStatement::addToken(Token identifier)
{
	lookup::Variable* pvar = getEnv()->findVariableOrParam(identifier.getString());
	if (pvar == NULL)
	{
		throw err::Error(err::READ_TO_NONVAR,identifier);
	}

	std::string readstr;
	switch( pvar->getType() )
	{
	case lookup::Char:
		readstr = "%c";
		break;
	case lookup::Int:
		readstr = "%d";
		break;
	case lookup::Float:
		readstr = "%f";
		break;
	default:
		assert(0);
	}
	

	m_src1 = lookup::Env::createString("",readstr);
	m_target = pvar;
	genCode();
}
TCA genCallArrayPrologue(Func* func, const DVFuncletsVec& dvs) {
  auto context = prologue_context(kInvalidTransID, func, func->base());
  IRGS env{context, TransFlags{}};

  assertx(mcg->cgFixups().empty());

  auto& main = mcg->code.main();
  auto& frozen = mcg->code.frozen();

  auto const start = main.frontier();

  irgen::emitCallArrayPrologue(env, dvs);
  irgen::sealUnit(env);
  genCode(env.unit, CodeKind::CrossTrace);

  if (RuntimeOption::EvalPerfRelocate) {
    GrowableVector<IncomingBranch> ibs;
    recordPerfRelocMap(start, main.frontier(),
                       frozen.frontier(), frozen.frontier(),
                       SrcKey { func, dvs[0].second, false },
                       0, ibs, mcg->cgFixups());
  }
  mcg->cgFixups().process(nullptr);

  return start;
}
void ast::FunctionCallStatement::addNode(pValueParamList p)
{
		//确保自动删除
	std::auto_ptr<ast::ASTNode> point_manager(p);
	
	//CALL
	genCode();
}
void ast::WhileStatement::addNode(pStatement p)
{
	//确保自动删除
	std::auto_ptr<ast::ASTNode> point_manager(p);
	
	//gotostart (m_startlabel is alias of m_src1)
	genCode();

	tuple::TupleManager::putLabel( m_falseLabel );
}
Exemple #6
0
  void NodeInstanceof::genCodeToStoreInto(File * fp, UVPass& uvpass)
  {
    //lhs
    assert(getStoreIntoAble() == TBOOL_TRUE); //not so..why not!
    genCode(fp, uvpass); //t41085

    //tmp variable becomes the object of the constructor call (t41085)
    m_tmpvarSymbol = Node::makeTmpVarSymbolForCodeGen(uvpass, NULL);
    m_state.m_currentObjSymbolsForCodeGen.push_back(m_tmpvarSymbol);
  } //genCodeToStoreInto
Exemple #7
0
void term(){
  token tempToken;
  factor();
  
  while(currentToken == multsym || currentToken == slashsym){
    tempToken = currentToken;
 
    readToken();
    
    factor();
 
    if(tempToken == multsym)
      genCode(OPR, 0, MUL);
    else if(tempToken == slashsym)
      genCode(OPR, 0, DIV);
  }
  
  return;
}
Exemple #8
0
void expression(){
  int minus = 0; //A flag to negate the expression if we need to
  token operator;
 
  if(currentToken != plussym && currentToken != minussym
     && currentToken != lparentsym && currentToken != identsym
     && currentToken != numbersym)
    throwError(SYMBOL_CANNOT_BEGIN_THIS_EXP);

  if(currentToken == minussym)
    minus = 1;
 
  if(currentToken == plussym || currentToken == minussym)
    readToken();
  
  if(currentToken == procsym)
    throwError(EXP_CANNOT_CONTAIN_PROC_IDENT);
  
  term();
  
  if(minus)
    genCode(OPR, 0, NEG);

  while(currentToken == plussym || currentToken == minussym){
    operator = currentToken;
    
    readToken();
    
    if(currentToken == procsym)
      throwError(EXP_CANNOT_CONTAIN_PROC_IDENT);
    
    term();
 
    if(operator == plussym)
      genCode(OPR, 0, ADD);
    else if(operator == minussym)
      genCode(OPR, 0, SUB);
  }
 
  return;
}
void ast::AssignmentStatement::addNode(pExpression p)
{
	//È·±£×Ô¶¯É¾³ý
	std::auto_ptr<ast::ASTNode> point_manager(p);
	
	m_src1 = p->getResult();

	genCode();

	if ( m_src1->getType() > m_target->getType() )
		warning::Warning(warning::BADCONVERT).report();
}
Exemple #10
0
int main(int argc, char *argv[])
{
	clrscr();
	showCredits();
	checkUsages(argc);
	openFile2Write(argv[1]);
	readFromFile(argv[1]);
	genCode();
	readData();
	printStatus("DONE",8);
	return 0;
}
void PrologEpilogGenerator::genPrologEpilog() {
    
    buildSets();

    IPF_LOG << endl << "  Generate Code" << endl;
    genCode();

    IPF_LOG << "  Reassign OutRegArgs" << endl;
    reassignOutRegArgs();

    IPF_LOG << endl; opndManager->printStackInfo(); 
    IPF_LOG << endl; printRegMasks(); IPF_LOG << endl; 
}
Exemple #12
0
void condition(){
  token operation;
 
  if(currentToken == oddsym){
    readToken();
    
    expression();

    genCode(OPR, 0, ODD);
  }
  else{
    expression();
    
    /*******************************************/
    /* rel-op ::= "="|"!="|"<"|"<="|">"|">="   */
    /*******************************************/
    if(currentToken != eqsym
       && currentToken != neqsym
       && currentToken != lessym
       && currentToken != leqsym
       && currentToken != gtrsym
       && currentToken != geqsym){

      if(currentToken == becomessym)
        throwError(EQ_NOT_BECOMES);
 
      throwError(REL_OP_EXPEC);
 
    }else{
      operation = currentToken;
    }
    
    readToken();
    
    expression();
 
    if(operation == eqsym)
      genCode(OPR, 0, EQL);
    else if(operation == neqsym)
      genCode(OPR, 0, NEQ);
    else if(operation == lessym)
      genCode(OPR, 0, LSS);
    else if(operation == leqsym)
      genCode(OPR, 0, LEQ);
    else if(operation == gtrsym)
      genCode(OPR, 0, GTR);
    else if(operation == geqsym)
      genCode(OPR, 0, GEQ);
 
  }
  
  return;
}
int main(int argc, char** argv) {
    Parser parser(argv[1]);

    Program prog;
    if(!parser.Parse(&prog)) {
        return -1;
    }
    
    if (!genCode(argv[2], prog)) {
        return -1;
    }

    return 0;
}
Exemple #14
0
int main(int argc, char *argv[])
{
	clrscr();
	showCredits();
	checkUsages(argc);
	readFromFile(argv[1]);
	genTree();
	openFile2Write(argv[1]);
	genCode();
	closeFile2Write();
	printProc("Closing destination file... ");
	printStatus("DONE",1);
	printf("\n");
	return 0;
}
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
    QDialog(parent), ui(new Ui::QRCodeDialog), address(addr)
{
    ui->setupUi(this);
    setWindowTitle(QString("%1").arg(address));
    setAttribute(Qt::WA_DeleteOnClose);

    ui->chkReqPayment->setVisible(enableReq);
    ui->lnReqAmount->setVisible(enableReq);
    ui->lblAmount->setVisible(enableReq);
    ui->lblBTC->setVisible(enableReq);

    ui->lnLabel->setText(label);

    genCode();
}
Exemple #16
0
TCA genFuncPrologue(TransID transID, Func* func, int argc) {
  auto context = prologue_context(transID, func,
                                  func->getEntryForNumArgs(argc));
  IRGS env{context, TransFlags{}};

  auto& cb = mcg->code.main();

  // Dump the func guard in the TC before anything else.
  emitFuncGuard(func, cb);
  auto const start = cb.frontier();

  irgen::emitFuncPrologue(env, argc, transID);
  irgen::sealUnit(env);
  genCode(env.unit, CodeKind::CrossTrace);

  return start;
}
Exemple #17
0
void parse(FILE *i, FILE *o){
    time_t now;

    time(&now);

    peektok = NONE;

    fputs("/* Generated by re2c 0.9.1-C on ", o);
    fprintf(o, "%-24s", ctime(&now));
    fputs(" */\n", o); oline+=2;

    in = Scanner_new(i);

    line_source(o, Scanner_line(in));

    while(Scanner_echo(in, o)){
	yyparse();
	if(spec)
	    genCode(o, spec);
	line_source(o, Scanner_line(in));
    }
}
void QRCodeDialog::on_lnMessage_textChanged(const QString &arg1)
{
    genCode();
}
void QRCodeDialog::on_lnLabel_textChanged(const QString &arg1)
{
    genCode();
}
void QRCodeDialog::on_lnReqAmount_textChanged(const QString &arg1)
{
    genCode();
}
Exemple #21
0
 void NodeUnaryOp::genCodeToStoreInto(File * fp, UVPass& uvpass)
 {
   genCode(fp,uvpass);
 }
Exemple #22
0
void statement(){
  int l;
  int m;
  symTableEntry* symbol;
  int tempLabels[2];
 
  if(currentToken == identsym){
    symbol = findSymbol(symTable, VAR, tokenVal.string, scope);
    if(!findVar(tokenVal.string, scope, &l, &m)){
      if(findConst(tokenVal.string, scope, &m))
        throwError(CANNOT_ASSIGN_TO_CONST_OR_PROC);
      else
        throwError(UNDEC_ID);
    }
    
    readToken();
    
    if(currentToken != becomessym)
      throwError(ASSIGN_EXPEC);
    
    readToken();
    
    expression();
 
    genCode(STO, l, m);
  }
  else if(currentToken == syawsym){
    readToken();
    
    if(currentToken != identsym)
      throwError(ID_FOLLOW_SYAW);

    if(!findFunc(tokenVal.string, scope, &l, &m))
      throwError(UNDEC_ID);

    genCode(CAL, l, m);
    
    readToken();
  }
  else if(currentToken == sngaisym){ // 'beginsym'
    readToken();
    
    statement();
    
    while(currentToken == semicolonsym){
      readToken();
      
      statement();
    }
      
    if(currentToken != fpesym && 
        (currentToken != identsym && currentToken != sngaisym
        && currentToken != txosym && currentToken != tengkrrsym)) // 'endsym'
      //throwError(WRONG_SYM_AFTER_STATE);
      throwError(SEMICOL_OR_RBRACK_EXPEC);
    else if(currentToken == identsym || currentToken == sngaisym
        || currentToken == txosym || currentToken == tengkrrsym)
      throwError(SEMICOL_BW_STATE_MISS);
    
    readToken();
  }
  else if(currentToken == txosym){ // 'ifsym'
    tempLabels[1] = 0;

    readToken();
    
    condition();
    
    tempLabels[0] = reserveCode(); //Conditional jump will go here
 
    if(currentToken != tsakrrsym) // 'thensym'
      throwError(TSAKRR_EXPEC);
    
    readToken();
    
    statement();

    if(currentToken == txokefyawsym){
      tempLabels[1] = reserveCode();
      readToken();
    }
 
    backPatch(tempLabels[0], JPC, 0, genLabel());
    
    if(tempLabels[1]){
      statement();
      backPatch(tempLabels[1], JMP, 0, genLabel());
    }

  }
  else if(currentToken == tengkrrsym){ // 'whilesym'
 
    readToken();
    
    tempLabels[0] = genLabel(); //Jump back up to here at the end of the loop
 
    condition();
 
    tempLabels[1] = reserveCode(); //Stick the conditional jump here
 
    if(currentToken != sisym) // 'dosym'
      throwError(SI_EXPEC);
    
    readToken();
      
    statement();
    
    genCode(JMP, 0, tempLabels[0]);
    backPatch(tempLabels[1], JPC, 0, genLabel());
  }
  else if(currentToken == misym){ // Input
    genCode(SIO, 0, 2);
    
    readToken();
    
    if(currentToken == identsym){
      if(findVar(tokenVal.string, scope, &l, &m))
        genCode(STO, l, m);
      else if(findConst(tokenVal.string, scope, &m)
              || findFunc(tokenVal.string, scope, &l, &m))
        throwError(CANNOT_STORE_IN_CONST_OR_PROC);
      else
        throwError(UNDEC_ID);
      
      readToken();
    }
  }
  else if(currentToken == wrrpasym){ // Output
    readToken();
    
    if(currentToken == identsym){
      if(findVar(tokenVal.string, scope, &l, &m))
        genCode(LOD, l, m);
      else if(findConst(tokenVal.string, scope, &m))
        genCode(LIT, 0, m);
      else
        throwError(UNDEC_ID);
      
      readToken();
    }
    
    genCode(SOI, 0, 1);
  }
  else if(currentToken == fpesym){
    return;
  }
  else{
    if(currentToken == periodsym)
      throwError(RBRACK_EXPEC_AT_END);
    else
      throwError(STATEMENT_EXPEC);
  }
  
  return;
}
Exemple #23
0
void genCode(astree* root, SymbolTable* table){
   if (root == NULL) {
	  return;
   }
   
   string currsym = get_yytname(root->symbol);

   if (currsym == "program") {
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currsymbol = get_yytname(root->children[child]->symbol);
		 
         if (currsymbol == "vardecl") {
            string child2 = get_yytname(root->children[child]->children[2]->symbol);
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string declt = root->children[child]->children[0]->children[0]->children[0]->lexinfo->c_str();
            string newtype = converter(declt);
			
            if(root->children[child]->children[0]->children.size() == 2){
               declt = declt + "[]";
               newtype = converter(declt);
               fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
            } else {
               fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
            }
         }
         if (currsymbol == "struct_") {
			genCode(root->children[child], table);
		 }
      }

      fprintf(oilFile, "void __ocmain ()\n{\n");

      for (size_t child = 0; child < root->children.size(); ++child) {
         string currsymbol = get_yytname(root->children[child]->symbol);
         if (currsymbol != "vardecl" && currsymbol != "struct_") {
			genCode(root->children[child], table);
		 }
      }
      fprintf(oilFile, "}\n");
   }

   if (currsym == "vardecl") {
      string ident = root->children[1]->lexinfo->c_str();
      string dect = checker(root->children[1], table);
      if (root->children[0]->children.size() == 2) dect = dect + "[]";
      dect = converter(dect);
      string child2 = get_yytname(root->children[2]->symbol);
      if (child2 == "constant") {
         fprintf(oilFile, "%s_%d_%s = __%s\n", dect.c_str(),table->numBack(), ident.c_str(), root->children[2]->children[0]->lexinfo->c_str());
	  }
      if (child2 == "variable") {
         fprintf(oilFile, "%s_%d_%s = _%d_%s\n", dect.c_str(),table->numBack(), ident.c_str(), table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
	  }
   }

   if (currsym == "binop") {
      string op = root->children[1]->lexinfo->c_str();
      if (op == "+" || op == "-" || op == "/" || op == "%" || op == "*") {
         int counter = icount++;
         string child0 = get_yytname(root->children[0]->symbol);
         string child2 = get_yytname(root->children[2]->symbol);
         if (child0 != "constant" && child0 != "constant") {
            genCode(root->children[0], table);
            fprintf(oilFile, "i%d = i%d ", counter, counter-1);
         }
         else if (child2 != "constant" && child2 != "constant") {
            genCode(root->children[2], table);
            fprintf(oilFile, "i%d = i%d ", counter, counter-1);
         } else {
			fprintf(oilFile, "i%d = ", counter);
		 }

         if(child0 == "constant") {
			fprintf(oilFile, "%s ", root->children[0]->children[0]->lexinfo->c_str());
		 }
         if(child0 == "variable") {
			fprintf(oilFile, "_%d_%s ", table->numBack(), root->children[0]->children[0]->lexinfo->c_str());
		 }
         fprintf(oilFile, "%s ", root->children[1]->lexinfo->c_str());
         if(child2 == "constant") {
			fprintf(oilFile, "%s;\n", root->children[2]->children[0]->lexinfo->c_str());
		 }
         if(child2 == "variable") {
			fprintf(oilFile, "_%d_%s;\n", table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
		 }      
      }
	  
      if (op == ">" || op == "<" || op == ">=" || op == "<=" || op == "!=" || op == "==") {
         int counter = bcount++;
         string child0 = get_yytname(root->children[0]->symbol);
         string child2 = get_yytname(root->children[2]->symbol);
         if (child0 != "constant" && child0 != "constant") {
            genCode(root->children[0], table);
            fprintf(oilFile, "b%d = b%d ", counter, counter-1);
         }
         else if (child2 != "constant" && child2 != "constant") {
            genCode(root->children[2], table);
            fprintf(oilFile, "b%d = b%d ", counter, counter-1);
         } else {
			fprintf(oilFile, "b%d = ", counter);
		 }

         if(child0 == "constant") {
			fprintf(oilFile, "%s ", root->children[0]->children[0]->lexinfo->c_str());
		 }
         if(child0 == "variable") {
			fprintf(oilFile, "_%d_%s ", table->numBack(), root->children[0]->children[0]->lexinfo->c_str());
		 }
         fprintf(oilFile, "%s ", root->children[1]->lexinfo->c_str());
         if(child2 == "constant") {
			fprintf(oilFile, "%s;\n", root->children[2]->children[0]->lexinfo->c_str());
		 }
         if(child2 == "variable") { 
			fprintf(oilFile, "_%d_%s;\n", table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
		 }
      }
   }

   if (currsym == "while_") {
      int currb = bcount;
      int currcount = controlcount++;
      fprintf(oilFile, "while_%d:;\n", currcount);
      genCode(root->children[0], table);
      fprintf(oilFile, "if(!b%d) goto break_%d;\n", currb, currcount);
      genCode(root->children[1],table);
      fprintf(oilFile, "goto while_%d;\n", currcount);
      fprintf(oilFile, "break_%d:;\n", currcount);
   }

   if (currsym == "if_") {
      int currb = bcount;
      int currcount = controlcount++;
      genCode(root->children[0],table);
      fprintf(oilFile, "if(!b%d) goto else_%d;\n", currb, currcount);
      genCode(root->children[1],table);
      fprintf(oilFile, "goto fi_%d;\n", currcount);
      fprintf(oilFile, "else_%d:;\n", currcount);
      if(root->children.size() == 3) genCode(root->children[2],table);
      fprintf(oilFile, "fi_%d:;\n", currcount);
   }

   if (currsym == "block") {
      SymbolTable* currblock = root->blockpt;
      for(size_t child = 0; child < root->children.size(); ++child){
         genCode(root->children[child], currblock);
      }
   }

   if (currsym == "struct_") {
      string structname;
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);  
         if (currchild == "TOK_IDENT") {
            structname = root->children[child]->lexinfo->c_str();
         }
      }
      fprintf(oilFile, "struct %s{\n", structname.c_str());

      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "decl") {
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string declt = root->children[child]->children[0]->children[0]->children[0]->lexinfo->c_str();
            string newtype = converter(declt);
            if (root->children[child]->children[0]->children.size() == 2) {
               declt = declt + "[]";
               newtype = converter(declt);
               fprintf(oilFile, "        %s%s;\n", newtype.c_str(), ident.c_str());
            } else {
               fprintf(oilFile, "        %s%s;\n", newtype.c_str(), ident.c_str());
            }
         }
      }
      fprintf(oilFile, "};\n");
   }

   if (currsym == "decl") {
      string ident = root->children[1]->lexinfo->c_str();
      string declt = root->children[0]->children[0]->children[0]->lexinfo->c_str();
      string newtype = converter(declt);
      if (root->children[0]->children.size() == 2) {
         declt = declt + "[]";
         newtype = converter(declt);
         fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
      } else {
         fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
      }
   }

   if (currsym == "function") {
      string funcname;
      string rettype;
      SymbolTable* currblock;
      astree* blockroot;
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "TOK_IDENT") {
            funcname = root->children[child]->lexinfo->c_str();
            rettype = checker(root->children[child], table);
            int firstparen = rettype.find_first_of('(',0);
            rettype = rettype.substr(0,firstparen);
         }
         if (currchild == "block") {
            currblock = root->children[child]->blockpt;
            blockroot = root->children[child];
            if (blockroot->children.size() == 0) return;
         }
      }
      fprintf(oilFile, "%s\n__%s(", converter(rettype).c_str(), funcname.c_str());

      for (size_t child = 0; child < root->children.size(); ++child) {
         int counter = 0;
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "decl") {
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string dectype = checker(root->children[child]->children[1], currblock);
            if (root->children[child]->children[0]->children.size() == 2) {
				dectype = dectype + "[]";
			}
            dectype = converter(dectype);
            if (counter != 0) {
				fprintf(oilFile, ",");
			}
            fprintf(oilFile, "\n   %s_%d_%s", dectype.c_str(), currblock->numBack(), ident.c_str());
         }
      }
      fprintf(oilFile, ")\n");
      genCode(blockroot, table);
   }
}
Exemple #24
0
int main( int argc, char **argv )
{
	/*	Set up the code for debugging.
		This allows the user to see the code.
	*/
	int newCode[CODELENGTH];
	genCode(newCode);

	/* If there's 2 inputs, then there's a flag. */
	if( argc == 2 )
	{
		int debugMode;

		printf( "Debugging Information.\n"
				"The code is: " );

		/* Display the code. */
		for( debugMode=0; debugMode<CODELENGTH; debugMode++ )
		{
			printf( " %d", newCode[debugMode]);
		}

	}

	/*	Get user guesses.
		Display an error message if the user inputs a value
		that's not between 1-6.
	*/
	printf( "\nGuess the code by entering 4 numbers between 1-6.\n"
			"	Example: 5 3 2 6\n"
			"You may use repeating variables if you wish.\n");

	int newGuess[CODELENGTH];
	getGuess(newGuess);

	/* Check validity of guess. */
	int g, state;
	state = FALSE;

	for( g=0; g<CODELENGTH; g++ )
	{
		if( newGuess[g] > 1 && newGuess[g] < 7 )
		{
			state = TRUE;
		}
		else
		{
			state = FALSE;
		}
	}

	/*	If the guess is valid, then continue.
		If invalid, prompt error message.
		Otherwise, pass the code and guess to checkGuess for comparison.
	*/
	if( state == FALSE )
	{
		printf( "Invalid guess! Your guess must be a number between 1-6.\n"
				"Please try again.");
	}
	else
	{
		checkGuess( newCode, newGuess );
	}

}//end main
Exemple #25
0
void block(){

  int jmpLoc = reserveCode();

  int thisScope;
  int numVars = 0;
  char tempSymbol[MAX_IDENT_LENGTH + 1];
 
  if(currentToken == constsym){
    /***************************************************************/
    /* const-declaration ::= [ "const" ident "=" number            */
    /*                               {"," ident "=" number} ";"]   */
    /***************************************************************/
    do{
      readToken();
      
      if(currentToken != identsym){
        throwError(ID_FOLLOW_CONST_VAR_PROC);
      }else{
        strcpy(tempSymbol, tokenVal.string);
      }
 
      readToken();
      
      if(currentToken != eqsym){
        if(currentToken == becomessym)
          throwError(EQ_NOT_BECOMES);
        else
          throwError(EQ_FOLLOW_ID);
      }
      
      readToken();
    
      if(currentToken != numbersym){
        throwError(NUM_FOLLOW_EQ);
      }else{
        insertSymbol(symTable, newSymbol(CONST, tempSymbol, scope, 0,
                                         tokenVal.numeric));
      }
    
      readToken();
    }while(currentToken == commasym);
    
    if(currentToken != semicolonsym)
      throwError(SEMICOL_COMMA_MISS);
 
    readToken();
  }
  
  if(currentToken == intsym){
    /*******************************************************/
    /* var-declaration ::= ["int" ident {"," ident} ";"] */
    /*******************************************************/
    do{
      readToken();
      
      if(currentToken != identsym){
        throwError(ID_FOLLOW_CONST_VAR_PROC);
      }else{
        insertSymbol(symTable, newSymbol(VAR, tokenVal.string,
                                         scope, BASE_OFFSET + numVars++, 0));
      }
        
      readToken();
    }while(currentToken == commasym);
    
    if(currentToken != semicolonsym)
      throwError(SEMICOL_COMMA_MISS);
      
    readToken();
  }
  
  //Saving the scope before moving into procedure declarations
  thisScope = scope;

  while(currentToken == procsym){
    /**********************************************************************/
    /* proc-declaration ::= {"procedure" ident ";" block ";"} statement   */
    /**********************************************************************/

    readToken();
    
    if(currentToken != identsym)
      throwError(ID_FOLLOW_CONST_VAR_PROC);

    //Storing the function name in the symbol table
    insertSymbol(symTable, newSymbol(FUNC, tokenVal.string, thisScope, 
                                     genLabel(), 0));

    
    readToken();
    
    if(currentToken != semicolonsym)
      throwError(SEMICOL_COMMA_MISS);
      
    readToken();

    //Incrementing the scope for our new function and saving its parent
    //in the disjoint set
    scope++;
    scopeParent[scope] = thisScope;

    block();
    
    if(currentToken != semicolonsym)
      throwError(WRONG_SYM_AFTER_PROC);
    
    readToken();
  }

  //Restoring the scope
  scope = thisScope;

  backPatch(jmpLoc, JMP, 0, genLabel());
  genCode(INC, 0, BASE_OFFSET + numVars);
 
  statement();
  
  genCode(OPR, 0, RET);
 
  return;
}
void QRCodeDialog::on_chkReqPayment_toggled(bool)
{
    genCode();
}
void genCode(pnode* ast,FILE* fp){
	if(ast == NULL)
		return;
	int i;
	pnode* temp;
	if(ast -> val == 12)
		return;
	if(ast -> val ==  28){  // SCAN statements // 
		for(i = 0 ; i < 200 ; i++){
			if(ast -> child[i] != NULL){
				temp = ast -> child[i];
				break;
			}	
		}
		fprintf(fp,"\tmov eax,3\n"); // sys_read
		fprintf(fp,"\tmov ebx,2\n"); // std_in
		fprintf(fp,"\tmov ecx,%s\n",temp -> name);
		fprintf(fp,"\tmov edx,4\n");
		fprintf(fp,"\tint 80h\n\n");
		return;
	}
	if(ast -> val == 29){ // PRINT Statemets
		for(i = 0 ; i < 200 ; i++){
			if(ast -> child[i] != NULL){
				temp = ast -> child[i];
				break;
			}	
		}
		fprintf(fp,"\tmov eax,4\n"); // sys_write
		fprintf(fp,"\tmov ebx,1\n"); // std_out
		fprintf(fp,"\tmov edx,4\n"); // std_out
		fprintf(fp,"\tint 80h\n\n");
				
				
		fprintf(fp,"\tmov eax,4\n"); // sys_write
		fprintf(fp,"\tmov ebx,1\n"); // std_out
		fprintf(fp,"\tmov ecx,NL\n");
		fprintf(fp,"\tmov edx,1\n");
		fprintf(fp,"\tint 80h\n\n");
		return;
	}
	if(ast -> val == 25 || ast -> val == 26){ // IF statements
		int lfcnt = ifcnt++;
		pnode* cond =NULL;
		pnode* conds= NULL;
		pnode* condf = NULL;
		int cnt = 0;
		int i;
		for(i = 0; i< 200 ; i++){
			if(ast -> child[i] != NULL && cnt == 0){
				cond =  ast -> child[i];
				cnt ++;
			}
			else if(ast -> child[i] != NULL && cnt == 1){
				conds =  ast -> child[i];
				cnt ++;
			}
			else if(ast -> child[i] != NULL && cnt == 2){
				condf =  ast -> child[i];
				break;
			}
			
		}
		//printf("%s %s %s \n", cond-> name , conds -> name , condf -> name);
		pnode* left = NULL;
		pnode* right = NULL;
		cnt =0;
		for(i = 0 ; i< 200 ; i++){
			if(cond -> child[i] != NULL && cnt == 0){
				left = cond -> child[i];
				cnt++;
			}
			else if(cond-> child[i] != NULL && cnt == 1){
				right =  cond -> child[i];
				break;
			}
		}
		//printf("%s %s \n", left -> name, right -> name);
		// TODO: Add optimization 
		int optflag1 = 0 , optflag2 = 0;
		if(left -> val == 7)
			fprintf(fp,"\tmov ecx,[%s]\n",left->name);
		else{
			fprintf(fp,"\tmov ecx,%s\n", left-> name);
			optflag1 = 1 ;
			//fprintf(fp,"\tsub ecx,'0'\n");
		}
		if(right -> val == 7)
			fprintf(fp,"\tmov edx,[%s]\n",right->name);
		else{
			fprintf(fp,"\tmov edx,%s\n", right-> name);
			optflag2 = 1;
			//fprintf(fp,"\tsub edx,'0'\n");
		}
		fprintf(fp,"\tcmp ecx,edx\n");
		
		if(cond -> val == 39){
			fprintf(fp,"\tje IFLABEL_%d\n",lfcnt);
		}
		if(cond -> val == 40){
			fprintf(fp,"\tjg IFLABEL_%d\n",lfcnt);
		}
		if(cond -> val == 41){
			fprintf(fp,"\tjge IFLABEL_%d\n",lfcnt);
		}
		if(cond -> val == 42){
			fprintf(fp,"\tjl IFLABEL_%d\n",lfcnt);
		}
		if(cond -> val == 43){
			fprintf(fp,"\tjle IFLABEL_%d\n",lfcnt);
		}
		if(cond -> val == 44){
			fprintf(fp,"\tjne IFLABEL_%d\n",lfcnt);
		}
		genCode(condf,fp);
		fprintf(fp,"\t jmp EXITIF_%d\n",lfcnt);
		fprintf(fp,"IFLABEL_%d:\n",lfcnt);
		genCode(conds,fp);
		fprintf(fp,"EXITIF_%d:\n",lfcnt);
		return;	
	}
	if(ast -> val ==  45){  // LOOP statements
		pnode* left = NULL;
		pnode* right = NULL;
		int cnt= 0;
		int i;
		for(i = 0 ; i< 200 ; i++){
			if(ast -> child[i] != NULL && cnt == 0){
				left = ast -> child[i];
				cnt++;
			}
			else if(ast-> child[i] != NULL && cnt == 1){
				right =  ast -> child[i];
				break;
			}
		}	
		fprintf(fp,"Loop_%d:\n", lpcnt);
		genCode(right,fp);
		if(left -> val == 39 || left -> val == 40 ||left -> val == 41 ||left -> val == 42 ||left -> val == 43 || left-> val == 44){
			pnode* lt;
			pnode* rt;
			int c =0;
			for(i = 0 ; i< 200  ; i++){
				if(left -> child[i] != NULL && c ==0){
					lt = left -> child[i];
					c++;
				}
				else if(left -> child[i] != NULL && c == 1){
					rt = left -> child[i];
					break;
				}
			}
			fprintf(fp,"\tmov ecx , [%s]\n",lt -> name);
			//fprintf(fp,"\tmov edx , [%s]\n",rt -> name);
			if(rt -> val == 7)
				fprintf(fp,"\tcmp ecx,[%s]\n",rt->name);
			else{
				//fprintf(fp,"\tsub ecx,'0'\n");
				fprintf(fp,"\tcmp ecx,%s\n",rt->name);
				
			}
			if(left -> val == 39)
				fprintf(fp,"\tje Loop_%d\n",lpcnt++);
			if(left -> val == 40)
				fprintf(fp,"\tjg Loop_%d\n",lpcnt++);
			if(left -> val == 41)
				fprintf(fp,"\tjge Loop_%d\n",lpcnt++);
			if(left -> val == 42)
				fprintf(fp,"\tjl Loop_%d\n",lpcnt++);
			if(left -> val == 43)
				fprintf(fp,"\tjle Loop_%d\n",lpcnt++);
			if(left -> val == 44)
				fprintf(fp,"\tjne Loop_%d\n",lpcnt++);
			
		}
		
		lpcnt++;
		return;
	}
	if(ast -> val == 14){  // assignment statement
			pnode* left = NULL;
			pnode* right = NULL;
			int cnt = 0,i;
			for(i = 0 ; i< 200 ;i++){
				if(ast -> child[i] != NULL && cnt == 0){
					left = ast -> child[i];
					cnt ++;
				}
				else if(ast -> child[i]!= NULL && cnt == 1){
					right =  ast -> child[i];
					break;
				}
			}
			if(right -> numChild == 0 && right -> val != 7){
				fprintf(fp,"\tmov eax, %s\n", right -> name);	
			}
			else if(right -> numChild == 0 && right -> val == 7){
				fprintf(fp,"\tmov eax, [%s]\n", right -> name);	
			}
			else if(right -> numChild == 2 && right -> val ==  148){
					
			}
			else{
				
				if(right -> val == 33 || right -> val == 32 || right -> val == 34 || right -> val == 35){
					pnode* leftT;
					pnode* rightT;
					int cnt = 0;
					int i;
					for(i = 0 ; i< 200 ; i++){
						if(right -> child[i] != NULL && cnt == 0){
							leftT =  right -> child[i];
							cnt ++;
						}
						else if(right -> child[i] != NULL && cnt == 1){
							rightT = right -> child[i];
							break;
						}
					}
					if(leftT -> val ==  19){
						fprintf(fp,"\tmov [acc1],%s\n", leftT -> name);
					}
					else if(leftT -> val == 7){
						fprintf(fp,"\tmov eax,[%s]\n", leftT -> name);
						fprintf(fp,"\tmov [acc1],eax\n", leftT -> name);
					}
					if(rightT -> val ==  19){
						fprintf(fp,"\tmov eax,%s\n", rightT -> name);
					}
					else if(rightT -> val == 7){
						fprintf(fp,"\tmov eax,[%s]\n", rightT -> name);
						//fprintf(fp,"\tmov [acc2],eax\n", leftT -> name);
					}
					else if(rightT -> val == 33 || rightT -> val == 32 || rightT -> val == 34 || rightT -> val == 35 ){
						fprintf(fp,"\tmov ebx,[acc1]\n");
						fprintf(fp,"\tpush ebx\n");
						genCode(rightT,fp);
						
						fprintf(fp,"\tpop ebx\n");
						fprintf(fp,"\tmov [acc1],ebx\n");
					}
					//fprintf(fp,"\tsub eax,'0'\n");
					if(right -> val == 33)
						fprintf(fp,"\tadd eax, [acc1]\n");
					else if(right ->val == 32){
						fprintf(fp,"\tmov ebx,[acc1]\n");
						//fprintf(fp,"\tsub ebx,eax\n");
						fprintf(fp,"\tmov eax,ebx\n");
					}	
					else if(right -> val ==  35){
						fprintf(fp,"\tmov ebx,[acc1]\n");
						//fprintf(fp,"\tsub ebx,'0'\n");
						fprintf(fp,"\tmul ebx\n");
						fprintf(fp,"\tadd eax,'0'\n");
					}
					else if(right -> val ==  34){
						fprintf(fp,"\tmov ebx,eax\n");
						fprintf(fp,"\tmov eax,[acc1]\n");
						//fprintf(fp,"\tsub eax,'0'\n");
						fprintf(fp,"\tmov edx,0D\n");
						fprintf(fp,"\tdiv ebx\n");
						//fprintf(fp,"\tadd eax,'0'\n");
					}									
				}
			}
			fprintf(fp,"\tmov [%s],eax\n", left -> name);
			return;
			
	}
	else if(ast -> val == 33 || ast -> val == 32 || ast -> val == 34 || ast -> val == 35 ){
		pnode* leftT = NULL;
		pnode* rightT = NULL;
		int cnt = 0,i;
		for(i = 0 ; i < 200 ; i++){
			if(ast -> child[i] != NULL && cnt == 0){
				leftT = ast -> child[i];
				cnt ++;
			}
			else if(ast -> child[i] != NULL && cnt == 1){
				rightT = ast -> child[i];
				break;
			}
		}
		if(leftT -> val ==  19){
			fprintf(fp,"\tmov [acc1],%s\n", leftT -> name);
		}
		else if(leftT -> val == 7){
			fprintf(fp,"\tmov eax,[%s]\n", leftT -> name);
			fprintf(fp,"\tmov [acc1],eax\n", leftT -> name);
		}
		if(rightT -> val ==  19){
			fprintf(fp,"\tmov eax,%s\n", rightT -> name);
		}
		else if(rightT -> val == 7){
			fprintf(fp,"\tmov eax,[%s]\n", rightT -> name);
			//fprintf(fp,"\tmov [acc2],eax\n", leftT -> name);
		}
		else if(rightT -> val == 33 || rightT -> val == 32 || rightT -> val == 34 || rightT -> val == 35){
			fprintf(fp,"\tmov ebx,[acc1]\n");
			fprintf(fp,"\tpush ebx\n");
			genCode(rightT,fp);
			
			fprintf(fp,"\tpop ebx\n");
			fprintf(fp,"\tmov [acc1],ebx\n");
		}
		//fprintf(fp,"\tsub eax,'0'\n");
		if(ast -> val == 33)
			fprintf(fp,"\tadd eax, [acc1]\n");
		else if(ast ->val == 32){
			fprintf(fp,"\tmov ebx,[acc1]\n");
			fprintf(fp,"\tsub ebx,eax\n");
			fprintf(fp,"\tmov eax,ebx\n");
		}
		else if(ast -> val ==  35){
			fprintf(fp,"\tmov ebx,[acc1]\n");
			fprintf(fp,"\tsub ebx,'0'\n");
			fprintf(fp,"\tmul ebx\n");
			//fprintf(fp,"\tadd eax,'0'\n");
		}	
		else if(ast -> val ==  34){
			fprintf(fp,"\tmov ebx,eax\n");
			fprintf(fp,"\tmov eax,[acc1]\n");
			//fprintf(fp,"\tsub eax,'0'\n");
			fprintf(fp,"\tmov edx,0D\n");
			fprintf(fp,"\tdiv ebx\n");
			//fprintf(fp,"\tadd eax,'0'\n");
		}	
		return;
	}
	for(i = 0 ; i< 200 ; i++){
		genCode(ast -> child[i] , fp);
	}
}
Exemple #28
0
int compile(int debug, int printSource, int printAssembly, int optimisation, char *fname)
{
    wchar_t *InputBuf;
    struct TokenStruct *Token;
    struct ContextStruct Context;
    int Result;

    /* Load the inputfile into memory. */
    InputBuf = LoadInputFile(fname);
    if (InputBuf == NULL) exit(1);
    
    if(printSource)
        printf("Input MAlice program:\n-- %s --\n%ls---\n\n",fname,InputBuf);

    /* Run the Parser. */
    Result = Parse(InputBuf,wcslen(InputBuf),TRIMREDUCTIONS,DEBUG,&Token);
    /* Interpret the results. */
    if (Result != PARSEACCEPT) {
        ShowErrorMessage(Token,Result);
        
        printf("\n[EXIT] Syntax Error\n");
        return 255;
    } else {
        /* Initialize the Context. */
        Context.Debug = DEBUG;
        Context.Indent = 0;
        Context.ReturnValue = NULL;

        /* Start execution by calling the subroutine of the first Token on
           the TokenStack. It's the "Start Symbol" that is defined in the
           grammar. */
        RuleJumpTable[Token->ReductionRule](Token,&Context);
    }
    
    //printTree(Token,0);
    
    int error = debug; // Used as debug flag and error reporting during CFG gen
    CFG * cfg = makeCFG(Token, optimisation, &error);
    if(error || cfg == 0)
    {
        printf("\n[EXIT] Compilation Error\n");
        return 255;
    }
    char* asmfname;
    asmfname = asmName(fname);
    
    genCode(cfg, asmfname);
    if(printAssembly)
    {
        printf("Generated assembly code:\n-- %s --\n",asmfname);
        printFile(asmfname);
        printf("---\n\n");
    }
    free(asmfname);

    char* exefname;
    exefname = exeName(fname);
    char fc[128];
    char sc[128];

    sprintf(fc ,"nasm -f elf32 %s.s -o %s.o", exefname, exefname);
    sprintf(sc ,"gcc -m32 %s.o -o %s", exefname, exefname);

    char * firstCommand = (char *)malloc(sizeof(char) * strlen(fc));
    char * secondCommand = (char *)malloc(sizeof(char) * strlen(sc));
    strcpy(firstCommand, fc);
    strcpy(secondCommand, sc);

    system(firstCommand);
    system(secondCommand);
    
    /* Cleanup. */
    DeleteTokens(Token);
    free(InputBuf);
    return 0;
}