From daf7dfedf0593b562c5fb3e8a023ef6c3924bb86 Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Sat, 13 Aug 2016 16:30:14 +0200 Subject: Read source before compiling --- bfcomp.c | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/bfcomp.c b/bfcomp.c index 2e25202..95a43f3 100644 --- a/bfcomp.c +++ b/bfcomp.c @@ -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); -- cgit v1.2.3-70-g09d2