dasm.cpp/* \file dasm.cpp
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <string>
using namespace std;
#include "strtoken.h"
void parse(FILE *in, FILE *out);
int main(int argc, char *argv[])
{
FILE *in, *out;
string filename;
errno_t nerr;
if (argc<2) {
cout << "usage: dasm csvfile [ outfile ]\n";
return EXIT_FAILURE;
}
filename = argv[1];
nerr = fopen_s(&in,filename.c_str(),"r");
if (nerr) {
cout << "file: " << filename << " not found\n";
return EXIT_FAILURE;
}
if (argc<3) out = stdout;
else {
filename = argv[2];
nerr = fopen_s(&out,filename.c_str(),"wt");
if (nerr) {
cout << "file: " << filename << " creation error\n";
return EXIT_FAILURE;
}
}
parse(in,out);
fclose(in);
return EXIT_SUCCESS;
}
int opcode_ndx[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 9, 9, 10, 11 };
int decode(string token)
{
string cmd[] = { "HALT", "LWI", "SWI", "LI", "LUI",
"LW", "SW", "ADDI", "ADD", "SUB", "AND", "OR", "XOR", "NOR", "BNE", "JALR"};
int ncmd = 16;
int n;
for (n=0; n<ncmd; n++) {
if (token.compare(cmd[n])==0) return n;
}
return -1;
}
void parse(FILE *in, FILE *out)
{
char buf[512];
char *inp, *next;
int opcode, ndx, ra, rb, rd, field;
int count, code, n;
int upper, opx;
string token;
bool done = false;
/*
* Go through input file, line by line
*/
n = 0;
while (!done) {
fgets(buf,511,in);
if (feof(in)) break;
//fprintf(out,"%s",buf);
if (*buf=='#') continue;
next = buf;
/*
* parse current line
*/
count = 0;
opcode = ra = rb = rd = 0;
ndx = 0;
while (next) {
/*
* search for '<', and copy prior text to
* output stream
*/
inp = next;
next = strqtrm(inp,',');
if (*inp=='r' || *inp=='R') inp++;
sscanf_s(inp,"%d",&field);
//fprintf(out,"count %d field %d\n",count,field);
switch (count) {
case 0:
token = inp;
ndx = decode(token);
if (ndx<0) opcode = 0;
else opcode = opcode_ndx[ndx];
//fprintf(out,"%s %d\n",token.c_str(),opcode);
count = 1;
break;
case 1:
rd = field;
count = 2;
break;
case 2:
ra = field;
count = 3;
break;
case 3:
rb = field;
count = 4;
break;
default:
break;
}
}
if (opcode==0) {
fprintf(out,"0000");
}
else {
upper = (opcode<<11) | (rd&0x7)<<8;
if (opcode<5 || opcode==11)
code = upper | (ra&0xFF);
else if (opcode<8 || opcode==10)
code = upper | (ra&0x7)<<5 | (rb&0x1F);
else if (opcode==8) {
opx = ndx - 8;
code = upper | (ra&0x7)<<5 | (rb&0x7)<<2 | (opx&0x3);
}
else if (opcode==9) {
opx = ndx-10;
code = upper | (ra&0x7)<<5 | (rb&0x7)<<2 | (opx&0x3);
}
else code = 0;
fprintf(out,"%04X",code);
}
if (n%8==7) fprintf(out,"\n");
else fprintf(out," ");
n++;
}
while (n < 32) {
fprintf(out,"0000");
if (n%8==7) fprintf(out,"\n");
else fprintf(out," ");
n++;
}
fprintf(out,"\n");
}
Maintained by John Loomis, updated Tue Apr 05 14:06:57 2011