Skip to content

Commit cf49088

Browse files
committed
add simple REPL
1 parent f298485 commit cf49088

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

Makefile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ LFLAGS = -lm
44

55
.PHONY = all clean
66

7-
all: smoke smoke_pr bench example example2 example3
7+
all: smoke smoke_pr repl bench example example2 example3
88

99

1010
smoke: smoke.c tinyexpr.c
@@ -15,6 +15,9 @@ smoke_pr: smoke.c tinyexpr.c
1515
$(CC) $(CCFLAGS) -DTE_POW_FROM_RIGHT -DTE_NAT_LOG -o $@ $^ $(LFLAGS)
1616
./$@
1717

18+
repl: repl.o tinyexpr.o
19+
$(CC) $(CCFLAGS) -o $@ $^ $(LFLAGS) -lreadline
20+
1821
bench: benchmark.o tinyexpr.o
1922
$(CC) $(CCFLAGS) -o $@ $^ $(LFLAGS)
2023

@@ -31,4 +34,4 @@ example3: example3.o tinyexpr.o
3134
$(CC) -c $(CCFLAGS) $< -o $@
3235

3336
clean:
34-
rm -f *.o *.exe example example2 example3 bench smoke_pr smoke
37+
rm -f *.o *.exe example example2 example3 bench repl smoke_pr smoke

repl.c

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include "tinyexpr.h"
2+
#include <stdlib.h>
3+
#include <stdio.h>
4+
#include <readline/readline.h>
5+
#include <readline/history.h>
6+
7+
static int eval(const char *str) {
8+
int err = 0;
9+
double r = te_interp(str, &err);
10+
if (err != 0) {
11+
printf("Error at position %i\n", err);
12+
return -1;
13+
} else {
14+
printf("%g\n", r);
15+
return 0;
16+
}
17+
}
18+
19+
static void repl() {
20+
while (1) {
21+
char *line = readline("> ");
22+
if (line == NULL) {
23+
break;
24+
} else if (strcmp(line, "q") == 0 || strcmp(line, "quit") == 0) {
25+
free(line);
26+
break;
27+
}
28+
29+
if (eval(line) != -1) {
30+
add_history(line);
31+
}
32+
33+
free(line);
34+
}
35+
}
36+
37+
int main(int argc, char **argv) {
38+
if (argc == 3 && strcmp(argv[1], "-e") == 0) {
39+
if (eval(argv[2]) == -1) {
40+
return 1;
41+
} else {
42+
return 0;
43+
}
44+
} else if (argc == 1) {
45+
repl();
46+
return 0;
47+
} else {
48+
printf("Usage: %s\n", argv[0]);
49+
printf(" %s -e <expression>\n", argv[0]);
50+
return 1;
51+
}
52+
}

0 commit comments

Comments
 (0)