Files
imp/lib/repl.c

59 lines
992 B
C

#include "repl.h"
#include "eval.h"
#include "memory_stream.h"
#include "print.h"
#include "read.h"
#include <assert.h>
#include <stdio.h>
#define PROMPT "> "
static int read_line(char buffer[REPL_IO_BUFFER_SIZE])
{
for (unsigned i = 0; i < REPL_IO_BUFFER_SIZE; ++i) {
const int c = getchar();
switch (c) {
case EOF:
return EOF;
case '\n':
return (int)i;
default:
buffer[i] = (char)c;
break;
}
}
assert(false);
return -2;
}
void repl_init(repl_t *repl)
{
am_init(&repl->am);
}
int repl_run(repl_t *repl)
{
int len;
memory_stream_t input;
while (true) {
fputs(PROMPT, stdout);
len = read_line(repl->io_buffer);
if (len < 0) {
fputc('\n', stdout);
return 0;
}
memory_stream_init(&input, (const uint8_t *)repl->io_buffer, len);
read(&repl->am, (stream_t *)&input);
eval(&repl->am);
len = print(&repl->am, repl->io_buffer, REPL_IO_BUFFER_SIZE - 1);
repl->io_buffer[len] = '\n';
fwrite(repl->io_buffer, 1, len + 1, stdout);
}
}