diff options
-rw-r--r-- | bfcomp.c | 49 |
1 files changed, 39 insertions, 10 deletions
@@ -160,15 +160,14 @@ void writeprologue(FILE *asmf){ params.memsize); } -void writeprogram(FILE *srcf,FILE *asmf){ +void writeprogram(char *source,FILE *asmf){ int addc=0,shiftc=0; //int lastshiftc=0; struct stackitem {int id; struct stackitem *next;} *loopstack=NULL; - bool eof=false; - while(!eof){ - char c=fgetc(srcf); - if(feof(srcf))eof=1; - if(!eof&&strchr("+-><[].,",c)==NULL)continue; + int i=0; + do { + char c=source[i]; + if(c&&strchr("+-><[].,",c)==NULL)continue; if(addc&&c!='+'&&c!='-'){ addc=(addc%256)+256%256; if(addc==1)fprintf(asmf,"\tinc byte [rbx] ; 1 +\n"); @@ -198,6 +197,7 @@ void writeprogram(FILE *srcf,FILE *asmf){ case '-': addc--; break; case '>': shiftc++; break; case '<': shiftc--; break; + case '[':{ struct stackitem *ls=malloc(sizeof(struct stackitem)); assert(ls); @@ -212,6 +212,7 @@ void writeprogram(FILE *srcf,FILE *asmf){ ls->id,ls->id,ls->id); break; } + case ']':{ assert(loopstack); fprintf(asmf, @@ -224,21 +225,24 @@ void writeprogram(FILE *srcf,FILE *asmf){ loopstack=ls; break; } + case '.': fprintf(asmf, "\tmov edi, 0 ; .\n" "\tmov dil, byte [rbx]\n" "\tcall _putchar\n"); break; + case ',': fprintf(asmf, "\tcall _getchar ; ,\n" "\tmov byte [rbx], al\n"); break; + default: - if(!eof)assert(false); + if(c)assert(false); } - } + } while(source[i++]); assert(!loopstack); } @@ -289,22 +293,47 @@ void writeepilogue(FILE *asmf){ "buf: resq 1\n"); } +void readsource(FILE *f,char **sourcep){ + int sz=1024; + char *source=malloc(sz); + assert(source); + int i=0; + while(true){ + if(i==sz-1){ + sz*=2; + source=realloc(source,sz); + assert(source); + } + char c=fgetc(f); + if(feof(f))break; + if(!strchr("+-><[].,",c))continue; + source[i++]=c; + } + source[i]='\0'; + *sourcep=source; +} + int main(int argc,char **argv){ parseargs(argc,argv); FILE *srcf=fopen(params.srcfname,"r"); assert(srcf); + char *source; + readsource(srcf,&source); + assert(source); + + fclose(srcf); + char asmfname[20]; FILE *asmf=gettempfilew(asmfname); if(params.verbose)fprintf(stderr,"asm -> %s\n",asmfname); DBGTIME("writeprologue",writeprologue(asmf);); - DBGTIME("writeprogram",writeprogram(srcf,asmf);); + DBGTIME("writeprogram",writeprogram(source,asmf);); DBGTIME("writeepilogue",writeepilogue(asmf);); fclose(asmf); - fclose(srcf); int ret=compilechain(asmfname,params.dstfname); unlink(asmfname); |