aboutsummaryrefslogtreecommitdiff
path: root/src/repl.c
blob: 236d9ecd86267bbbbd96a9fadfb1f6459191a8f4 (plain)
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
#include "repl.h"

#include "ast.h"
#include "object.h"
#include "token.h"
#include "vector.h"
#include "parser.h"
#include "eval.h"

#define PROMPT ">> "

static void
print_parser_errors(FILE *out, struct vector *errors)
{
	size_t i;
	char *msg;
	vector_foreach(errors, i, msg) {
		fprintf(out, "\t%s\n", msg);
	}
}

void
repl_start(FILE *in, FILE *out)
{
	char obuf[2048];
	struct parser *parser = parser_new();
	struct environment *env = environment_new();
	struct vector *history = vector_new();
	for (;;) {
		fprintf(out, PROMPT);
		char *input = malloc(1024);
		if (!fgets(input, 1024, in)) {
			if (ferror(in)) {
				perror("REPL: can't read");
				free(input);
				goto end;
			}
			fprintf(out, "EOF\n");
			free(input);
			goto end;
		}
		parser_reset(parser, input);
		struct program *prog = parser_parse_program(parser);
		if (parser->errors->len > 0) {
			print_parser_errors(out, parser->errors);
			goto skip;
		}
		struct object *res = eval(env, prog);
		if (res) {
			fprintf(out, "%s\n", object_sprint(res, obuf));
			object_unref(res);
		}
		vector_push(history, input);
skip:
		node_destroy(prog);
	}

end:;
	size_t i;
	char *input;
	vector_foreach(history, i, input) {
		free(input);
	}
	vector_free(history);
	environment_destroy(env);
	parser_destroy(parser);
}