diff options
author | tomsmeding <tom.smeding@gmail.com> | 2016-08-19 20:44:53 +0200 |
---|---|---|
committer | tomsmeding <tom.smeding@gmail.com> | 2016-08-19 20:52:28 +0200 |
commit | c9127b2bd399ce5d3e9483a82434948202592309 (patch) | |
tree | 7a6f682fb2fc47c83191fab0b7ad00c5dd45e604 /main.c | |
parent | 15fb03902ff5550b3a8c44bde3e08df876449f7a (diff) |
Parsing and stringification works
Diffstat (limited to 'main.c')
-rw-r--r-- | main.c | 87 |
1 files changed, 87 insertions, 0 deletions
@@ -0,0 +1,87 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <assert.h> + +#include "parser.h" +#include "util.h" + + +char* readfile(const char *fname,size_t *length){ + FILE *f=fopen(fname,"rb"); + if(!f)return NULL; + if(fseek(f,0,SEEK_END)==-1){fclose(f); return NULL;} + long flen=ftell(f); + if(flen==-1){fclose(f); return NULL;} + rewind(f); + + char *buf=malloc(flen+1,char); + fread(buf,1,flen,f); + if(ferror(f)){fclose(f); free(buf); return NULL;} + if(memchr(buf,'\0',flen)!=NULL){ + fprintf(stderr,"Invalid null char in file '%s'\n",fname); + exit(1); + } + buf[flen]='\0'; + fclose(f); + + *length=flen; + return buf; +} + +char *readstdin(size_t *length){ + int bufsz=1024,cursor=0; + char *buf=malloc(bufsz,char); + while(true){ + if(cursor==bufsz-1){ + bufsz*=2; + buf=realloc(buf,bufsz,char); + } + int nread=fread(buf,1,bufsz-cursor-1,stdin); + if(nread>0&&memchr(buf,'\0',nread)!=NULL){ + fprintf(stderr,"Invalid null char on stdin file\n"); + exit(1); + } + cursor+=nread; + if(nread<bufsz-cursor-1){ + if(feof(stdin))break; + if(ferror(stdin)){ + free(buf); + return NULL; + } + } + } + buf[cursor]='\0'; + *length=cursor; + return buf; +} + + +int main(int argc,char **argv){ + if(argc!=2){ + fprintf(stderr,"Pass source file (or '-') as a command-line argument.\n"); + return 1; + } + char *source; + size_t length; + if(strcmp(argv[1],"-")==0)source=readstdin(&length); + else source=readfile(argv[1],&length); + + if((size_t)(int)length!=length){ + fprintf(stderr,"Source file too long!\n"); + return 2; + } + + ParseRet pr=parse(source,length); + if(pr.errstr){ + fprintf(stderr,"\x1B[1;31m%s\x1B[0m\n",pr.errstr); + free(pr.errstr); + return 1; + } + assert(pr.ast); + printf("%p\n",pr.ast); + char *s=ast_stringify(pr.ast); + printf("%s\n",s); + free(s); + ast_free(pr.ast); +} |