forked from splatspace/wombat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_form.c
85 lines (79 loc) · 1.58 KB
/
read_form.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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "types.h"
#include "read_form.h"
void* _read_integer(FILE* f) {
char buf[17]; /* 16 digit limit on numbers */
memset(buf, '\0', 17);
int n = 0;
char c;
while ((c = getc(f))) {
if(isdigit(c)) {
buf[n++] = c;
} else {
ungetc(c,f);
break;
}
}
return (void*)integer(atoi(buf));
}
void* _read_symbol(FILE *f) {
char buf[17]; /* 16 character limit on symbols */
memset(buf, '\0', 17);
int n = 0;
char c;
while ((c = getc(f))) {
if(isalpha(c)) {
buf[n++] = c;
} else {
ungetc(c,f);
break;
}
}
return (void*)sym(buf);
}
int _is_whitespace(char c) {
return isspace(c);
}
void _gobble_whitespace(FILE* f) {
char c;
while(_is_whitespace(c = (getc(f))));
ungetc(c, f);
}
void* _read_list(FILE* f) {
char c;
Cons *list, *cell;
list = cell = empty();
void* form;
while ((c = getc(f)) != ')'){
ungetc(c, f);
form = read_form(f);
if(CAR(cell) && !CDR(cell)) {
cell->cdr = form;
} else if (CAR(cell) && CDR(cell)){
cell->cdr = cons(cell->cdr, form);
cell = cell->cdr;
} else {
cell->car = form;
}
_gobble_whitespace(f);
}
return (void*)list;
}
void* read_form(FILE* f) {
char c = getc(f);
if(isdigit(c)) {
ungetc(c, f);
return _read_integer(f);
} else if(isalpha(c)) {
ungetc(c, f);
return _read_symbol(f);
} else if(c == '(') {
return _read_list(f);
} else if(c == '\'') {
return cons(sym("quote"), read_form(f));
}
return read_form(f);
}