-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathread.c
103 lines (76 loc) · 2.2 KB
/
read.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
#include "read.h"
char code[BUFSIZ];
Obj read_code(void) {
while (!lib_loaded()) {
char* lib_code = load_library();
Obj result = parse(lib_code);
return result;
}
if (LIB) toggle_LIB();
input_prompt();
while (isSpecial(code)) {
if (isFlag(code)) {
switch_flag(code);
print_flags();
} else if (isHelp(code))
print_help();
input_prompt();
}
if (DEBUG) printf("\nLISP CODE: %s\n", code);
Obj result = parse(code);
return result;
}
/* input prompt */
void input_prompt(void) {
print_prompt();
get_input();
if (isIrregular(code)) {
if (badSyntax(code)) printf("Bad syntax! Try again!\n");
input_prompt();
}
}
void print_prompt(void) {
NL;
printf("lispinc >>> ");
}
/* NB: fgets add an extra newline at the end of input */
void get_input(void) {
fgets(code, BUFSIZ, stdin);
// code[strlen(code) - 1] = '\0';
}
bool isIrregular(char* code) { return badSyntax(code) || isEnter(code); }
bool isEnter(char* code) { return streq(code, "\n"); }
// other bad syntax conditions can be added later
bool badSyntax(char* code) { return !parens_balanced(code); }
bool parens_balanced(char* code) {
int op = 0;
int cp = 0;
int len = strlen(code);
for (int i = 0; i < len; i++) {
if (OPENPAREN(code[i])) op++;
if (CLOSEPAREN(code[i])) cp++;
}
return op == cp;
}
/* check for user commands (see flags.h) */
int isSpecial(char* code) {
if (DEBUG) printf("isSpecial\n");
return isFlag(code) || isHelp(code); // || isQuit(code);
}
// inelegant
int isFlag(char* code) {
if (DEBUG) printf("isFlag\n");
return streq(code, DEBUG_COMMAND) || streq(code, DEMO_COMMAND)
|| streq(code, INFO_COMMAND) || streq(code, REPL_COMMAND)
|| streq(code, STATS_COMMAND) || streq(code, STEP_COMMAND)
|| streq(code, TAIL_COMMAND);
}
int isHelp(char* code) {
if (DEBUG) printf("isHelp\n");
return streq(code, HELP_COMMAND);
}
// bool isQuit(char* code) {
// if (DEBUG) printf("isQuit\n");
// return streq(code, _QUIT);
// }
int streq(char* str1, char* str2) { return strcmp(str1, str2) == 0; }