Skip to content

Instantly share code, notes, and snippets.

@wsuzume
Last active March 24, 2016 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wsuzume/cc7827169948b247da7d to your computer and use it in GitHub Desktop.
Save wsuzume/cc7827169948b247da7d to your computer and use it in GitHub Desktop.
useage: ./compiler source dest
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int rmindent(char *buf)
{
int i;
for (i = 0; ; i++) {
if (buf[i] != ' ') {
break;
}
}
return i;
}
int getop(char *dest, char *src)
{
int i;
for (i = 0; i < 64; i++) {
if (src[i] == '\0') {
return 0;
}
if (src[i] == ' ') {
dest[i] = '\0';
break;
}
dest[i] = src[i];
}
return i + 1;
}
int getoperand(int *dest, char *src)
{
int i;
char buf[256];
for (i = 0; i < 256; i++) {
if (src[i] == ' ' ||
src[i] == '\0' ||
src[i] == '\n') {
buf[i] = '\0';
break;
}
buf[i] = src[i];
}
//puts(buf);
*dest = atoi(buf);
return i + 1;
}
int counter;
int program[256];
void pushop(int op)
{
program[counter++] = op;
}
void makeop(char *op, int operand1, int operand2)
{
if (strcmp(op, "add") == 0) {
pushop(1);
}
if (strcmp(op, "sub") == 0) {
pushop(2);
}
if (strcmp(op, "pro") == 0) {
pushop(3);
}
if (strcmp(op, "div") == 0) {
pushop(4);
}
if (strcmp(op, "mod") == 0) {
pushop(5);
}
pushop(operand1);
pushop(operand2);
}
void writeprogram(FILE *dest)
{
fwrite((void *)program, sizeof(int), counter, dest);
}
int compile(FILE *fp)
{
char buf[256];
char op[64];
int chaser = 0;
int operand1, operand2;
char *s;
while (1) {
s = fgets(buf, 256, fp);
if (s == NULL) {
break;
}
chaser += rmindent(&buf[chaser]);
chaser += getop(op, &buf[chaser]);
chaser += getoperand(&operand1, &buf[chaser]);
chaser += getoperand(&operand2, &buf[chaser]);
chaser = 0;
makeop(op, operand1, operand2);
}
return 0;
}
int main(int argc, char *argv[])
{
FILE *fp = fopen(argv[1], "r");
FILE *dest = fopen(argv[2], "wb");
compile(fp);
writeprogram(dest);
fclose(dest);
fclose(fp);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment