1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "memory.h"
#include "parser.h"
char* readfile(const char *fname){
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);
if(!buf){fclose(f); return NULL;}
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);
return buf;
}
char *readstdin(void){
int bufsz=1024,cursor=0;
char *buf=malloc(bufsz);
if(!buf)return NULL;
while(true){
if(cursor==bufsz-1){
bufsz*=2;
char *newbuf=realloc(buf,bufsz);
if(!newbuf){
free(buf);
return NULL;
}
buf=newbuf;
}
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';
return buf;
}
void usage(const char *argv0){
fprintf(stderr,"Usage: %s <source file>\n",argv0);
}
int main(int argc,char **argv){
if(argc!=2){
usage(argv[0]);
return 1;
}
char *source;
if(strcmp(argv[1],"-")==0)source=readstdin();
else source=readfile(argv[1]);
if(!source){
fprintf(stderr,"Error reading %s\n",strcmp(argv[1],"-")==0?"from stdin":argv[1]);
return 1;
}
char *errmsg;
AST *ast=parse(source,&errmsg);
if(ast==NULL){
fprintf(stderr,"%s\n",errmsg);
free(errmsg);
return 1;
}
ast_debug(stderr,ast);
ast_free(ast);
}
|