-
Notifications
You must be signed in to change notification settings - Fork 1
/
repl.c
128 lines (108 loc) · 2.26 KB
/
repl.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
126
127
#include <stdio.h>
#include "config.h"
#include "object.h"
#include "reader.h"
#include "write.h"
#include "eval.h"
#include "repl.h"
#include "env.h"
#include "gc.h"
#define CORE_LIB_PATH APP_DIR "lib/core.scm"
static int keep_run = 1;
static object *global_env;
static int load_src(char *filename) {
FILE *in;
object *exp;
in = fopen(filename, "r");
if (in == NULL) {
return -1;
}
for (;;) {
exp = sc_read(in);
if (exp == NULL) {
fclose(in);
return -1;
}
if (is_eof_object(exp)) {
break;
}
gc_protect(exp);
exp = sc_eval(exp, global_env);
if (exp == NULL) {
fclose(in);
return -1;
}
gc_abandon();
}
fclose(in);
return 0;
}
static int load_core_lib() {
return load_src(CORE_LIB_PATH);
}
static int init(void) {
global_env = make_base_env();
if (global_env == NULL) {
return -1;
}
if (load_core_lib() != 0) {
fprintf(stderr, "failed to load core lib\n");
return -1;
}
return 0;
}
int sc_repl(char *run_file) {
object *exp, *val;
int ret = 0;
int err_cnt = 0;
FILE *in, *out;
if (init() != 0) {
return -1;
}
/* execute program */
if (run_file) {
int ret = load_src(run_file);
if (ret != 0) {
fprintf(stderr, "failed to load %s\n", run_file);
}
return ret;
}
/* inteactive mode */
in = stdin;
out = stdout;
printf("%s", WELCOME_STR);
while (keep_run) {
if (err_cnt > 0) {
printf("%d%s", err_cnt, PROMPT);
} else {
printf("%s", PROMPT);
}
exp = sc_read(in);
if (exp == NULL) {
err_cnt++;
continue;
}
if (is_eof_object(exp)) {
break;
}
gc_protect(exp);
val = sc_eval(exp, global_env);
gc_abandon();
if (val == NULL) {
err_cnt++;
continue;
}
ret = sc_write(out, val);
printf("\n");
if (ret != 0) {
break;
}
}
return ret;
}
void repl_exit(void) {
keep_run = 0;
}
object* get_repl_env(void) {
return global_env;
}