]> git.lizzy.rs Git - nothing.git/blob - src/script/repl.c
Quit function for REPL
[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(Gc *gc, struct Scope *scope, struct Expr args)
12 {
13     assert(scope);
14     (void) args;
15
16     exit(0);
17
18     return eval_success(NIL(gc));
19 }
20
21 char buffer[REPL_BUFFER_MAX + 1];
22
23 int main(int argc, char *argv[])
24 {
25     (void) argc;
26     (void) argv;
27
28     Gc *gc = create_gc();
29     struct Scope scope = {
30         .expr = CONS(gc, NIL(gc), NIL(gc))
31     };
32
33     set_scope_value(gc, &scope, SYMBOL(gc, "quit"), NATIVE(gc, quit));
34
35     while (true) {
36         printf("> ");
37
38         if (fgets(buffer, REPL_BUFFER_MAX, stdin) == NULL) {
39             return -1;
40         }
41
42         printf("Before parse:\t");
43         gc_inspect(gc);
44
45         struct ParseResult parse_result = read_expr_from_string(gc, buffer);
46         if (parse_result.is_error) {
47             print_parse_error(stderr, buffer, parse_result);
48             continue;
49         }
50         printf("After parse:\t");
51         gc_inspect(gc);
52
53         struct EvalResult eval_result = eval(gc, &scope, parse_result.expr);
54         printf("After eval:\t");
55         gc_inspect(gc);
56
57         gc_collect(gc, CONS(gc, scope.expr, eval_result.expr));
58         printf("After collect:\t");
59         gc_inspect(gc);
60
61         printf("Scope:\t");
62         print_expr_as_sexpr(scope.expr);
63         printf("\n");
64
65         if (eval_result.is_error) {
66             printf("Error:\t");
67         }
68
69         print_expr_as_sexpr(eval_result.expr);
70         printf("\n");
71     }
72
73     destroy_gc(gc);
74
75     return 0;
76 }