]> git.lizzy.rs Git - nothing.git/blob - src/ebisp/repl.c
Merge pull request #559 from tsoding/514
[nothing.git] / src / ebisp / 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 #include "repl_runtime.h"
9
10 #define REPL_BUFFER_MAX 1024
11
12 static void eval_line(Gc *gc, Scope *scope, const char *line)
13 {
14     /* TODO(#465): eval_line could be implemented with read_all_exprs_from_string */
15     while (*line != 0) {
16         gc_collect(gc, scope->expr);
17
18         struct ParseResult parse_result = read_expr_from_string(gc, line);
19         if (parse_result.is_error) {
20             print_parse_error(stderr, line, parse_result);
21             return;
22         }
23
24         struct EvalResult eval_result = eval(gc, scope, parse_result.expr);
25         if (eval_result.is_error) {
26             fprintf(stderr, "Error:\t");
27             print_expr_as_sexpr(stderr, eval_result.expr);
28             fprintf(stderr, "\n");
29             return;
30         }
31
32         print_expr_as_sexpr(stderr, eval_result.expr);
33         fprintf(stdout, "\n");
34
35         line = next_token(parse_result.end).begin;
36     }
37 }
38
39 int main(int argc, char *argv[])
40 {
41     (void) argc;
42     (void) argv;
43
44     char buffer[REPL_BUFFER_MAX + 1];
45
46     Gc *gc = create_gc();
47     struct Scope scope = {
48         .expr = CONS(gc, NIL(gc), NIL(gc))
49     };
50
51     load_std_library(gc, &scope);
52     load_repl_runtime(gc, &scope);
53
54     while (true) {
55         printf("> ");
56
57         if (fgets(buffer, REPL_BUFFER_MAX, stdin) == NULL) {
58             return -1;
59         }
60
61         eval_line(gc, &scope, buffer);
62     }
63
64     destroy_gc(gc);
65
66     return 0;
67 }