All pastes #818742 Raw Edit

Xenius

public text v1 · immutable
·published 2007-12-16 14:35 UTC
rendered paste body
/* BrainFuck compiler C v2.1.1.  Copyright 1997 Ben Olmstead, 2007 Xenius.
/* This program is governed by the GNU General Public License. See the file COPYING for details.
/*
/* This compiler generates native machine code for whatever processor.
/* It is currently configured to generate an MS-DOS .COM file, but it
/* should be relatively easy to alter.
/************************************************************************/
#include <stdio.h>
/************************************************************************/
#define NEXT "\x46"
#define PREV "\x4e"
#define INCR "\xfe\x04"
#define DECR "\xfe\x0c"
#define PUTC "\xb4\x40\xbb\x01\x00\x89\xd9\x89\xf2\xcd\x21"
#define GETC "\xb4\x01\xcd\x21\x3c\x0d\x75\x07\xb8\x0a\x02\xb2\x0a\xcd\x21\x88\x04"
#define J_FW "\x80\x3c\x00\x75\x03\xe9\x00\x00"
#define J_BW "\x80\x3c\x00\x74\x03\xe9"
#define PREF "\xbe\x00\x00\x31\xc0\xb9\x00\x00\x89\xf7\xf3\xaa"
#define PSFX "\xb8\x00\x4c\xcd\x21"
/************************************************************************/
void compile();
/************************************************************************/
unsigned short location=12;
FILE *z, *Z;
char b, *filename="a.com";
int n;
/************************************************************************/
main(int argc, char *argv[])
{
  if (argc==3) filename=argv[2];
  if (z=fopen(argv[1],"r"))
  {
    if (Z=fopen(filename, "wb"))
    {
      fwrite(PREF, 1, 12, Z);
      compile();
      fwrite(PSFX, 1, 5, Z);
      location += 261;
      fseek(Z, 1, SEEK_SET);
      fwrite(&location, 1, 2, Z);
      fseek(Z, 6, SEEK_SET);
      location=-location;
      fwrite(&location, 1, 2, Z);
      fclose(Z);
    }
    fclose(z);
  }
}
/************************************************************************/
void compile()
{
  unsigned short m;
  while((b=getc(z))!=EOF)
  {
    switch(b)
    {
      case '<': fwrite(PREV, 1, 1, Z); location++; break;
      case '>': fwrite(NEXT, 1, 1, Z); location++; break;
      case '+': fwrite(INCR, 1, 2, Z); location+=2; break;
      case '-': fwrite(DECR, 1, 2, Z); location+=2; break;
      case '.': fwrite(PUTC, 1, 11,Z); location+=11; break;
      case ',': fwrite(GETC, 1, 17,Z); location+=17; break;
      case '[': fwrite(J_FW, 1, 8, Z); location+=8;
        m=location;
        compile();
        fwrite(J_BW, 1, 6, Z); location+=8; n=m-location;
        fwrite(&n, 1, 2, Z);
        fseek(Z, m-2, SEEK_SET); n=-n;
        fwrite(&n, 1, 2, Z);
        fseek(Z, 0, SEEK_END);
        break;
      case ']': return;
    }
  }
}