-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.c
125 lines (105 loc) · 2.12 KB
/
parse.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include "types.c"
#define BUFFSIZE 256
atom *read (FILE*);
static char readchar (void);
static void putback (char c);
static char *next (void);
static atom *parse (char*);
static atom *parselist (void);
FILE *i;
atom *read (FILE *input) {
i = input;
return parse(next());
}
static char readchar (void) {
int c = getc(i);
if (c != EOF)
return c;
printf("read error: unexpected EOF (check parens)\n");
exit(1);
}
static void putback (char c) {
ungetc(c, i);
}
static char *next (void) {
static char buff[BUFFSIZE];
char *c = buff;
while (isspace(*c = readchar()));
if (*c != ')' && *c != '(' && *c != '"') {
while( !isspace(*(c+1) = readchar()) && *(c+1) != '(' && *(c+1) != ')')
c++;
putback(*(c+1));
}
else if (*c == '"') {
while ( (*(++c) = readchar()) != '"' )
if (*c == '\\')
*(++c) = readchar();
}
*(c+1) = '\0';
return buff;
}
static atom *parselist (void) {
char *p = next();
atom *ret, *car, *cdr;
switch (*p) {
case ')':
return NULL;
case '.':
ret = parse(next());
if (*next() == ')')
return ret;
else
printf("invalid dotted list\n");
exit(1);
break;
default:
car = parse(p);
cdr = parselist();
return newcons(car, cdr);
}
}
static atom *parse (char *p) {
char *t = p;
if (!*p)
return NULL; /* we've reached the end */
switch (*p) {
case '(':
return parselist();
case '"':
while (*(++t));
*(t-1) = '\0';
return newstring(p+1);
case '#':
switch (*(p+1)) {
case '\\':
return newchar(*(p+2));
case 't':
return newbool(1);
case 'f':
return newbool(0);
default:
printf("invalid # syntax\n");
exit(1);
}
break;
case '\'':
return newcons(newsym("quote"), newcons(
*(p+1) ? parse(p+1) : parse(next())
, NULL));
case '`':
return newcons(newsym("quasiquote"), newcons(
*(p+1) ? parse(p+1) : parse(next())
, NULL));
case ',':
return newcons(newsym("unquote"), newcons(
*(p+1) ? parse(p+1) : parse(next())
, NULL));
case ')':
default:
if (isdigit(*p))
return newint(atoi(p));
else
return newsym(p);
}
}