]> git.lizzy.rs Git - nothing.git/blob - src/script/repl.c
9c3460ec308f3dbb385aff9b65d805ac443d15a0
[nothing.git] / src / script / repl.c
1 #include <assert.h>
2 #include <stdbool.h>
3
4 #include "parser.h"
5 #include "interpreter.h"
6 #include "scope.h"
7 #include "gc.h"
8
9 #define REPL_BUFFER_MAX 1024
10
11 static struct EvalResult quit(void *param, Gc *gc, struct Scope *scope, struct Expr args)
12 {
13     assert(scope);
14     (void) args;
15     (void) param;
16
17     exit(0);
18
19     return eval_success(NIL(gc));
20 }
21
22 static void eval_line(Gc *gc, Scope *scope, const char *line)
23 {
24     const char *read_iter = line;
25     while (*read_iter != 0) {
26         printf("Before parse:\t");
27         gc_inspect(gc);
28
29         struct ParseResult parse_result = read_expr_from_string(gc, read_iter);
30         if (parse_result.is_error) {
31             print_parse_error(stderr, line, parse_result);
32             return;
33         }
34         printf("After parse:\t");
35         gc_inspect(gc);
36
37         struct EvalResult eval_result = eval(gc, scope, parse_result.expr);
38         printf("After eval:\t");
39         gc_inspect(gc);
40
41         gc_collect(gc, CONS(gc, scope->expr, eval_result.expr));
42         printf("After collect:\t");
43         gc_inspect(gc);
44
45         printf("Scope:\t");
46         print_expr_as_sexpr(scope->expr);
47         printf("\n");
48
49         if (eval_result.is_error) {
50             printf("Error:\t");
51         }
52
53         print_expr_as_sexpr(eval_result.expr);
54         printf("\n");
55
56         read_iter = next_token(parse_result.end).begin;
57     }
58 }
59
60 int main(int argc, char *argv[])
61 {
62     (void) argc;
63     (void) argv;
64
65     char buffer[REPL_BUFFER_MAX + 1];
66
67     Gc *gc = create_gc();
68     struct Scope scope = {
69         .expr = CONS(gc, NIL(gc), NIL(gc))
70     };
71
72     set_scope_value(gc, &scope, SYMBOL(gc, "quit"), NATIVE(gc, quit, NULL));
73
74     while (true) {
75         printf("> ");
76
77         if (fgets(buffer, REPL_BUFFER_MAX, stdin) == NULL) {
78             return -1;
79         }
80
81         eval_line(gc, &scope, buffer);
82     }
83
84     destroy_gc(gc);
85
86     return 0;
87 }