forked from codeplea/tinyexpr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.c
84 lines (73 loc) · 1.69 KB
/
repl.c
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "tinyexpr.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#else
static char *readline(const char *prompt) {
fprintf(stderr, "%s", prompt);
char buf[1024];
char *line = fgets(buf, sizeof(buf), stdin);
if (line == NULL && feof(stdin)) {
return NULL;
} else if (line == NULL) {
perror("fgets");
return NULL;
}
size_t len = strlen(line);
if (len < 1)
return NULL;
if (line[len - 1] == '\n') {
line[len - 1] = '\0';
len -= 1;
}
line = malloc(len + 1);
strcpy(line, buf);
return line;
}
static void add_history(const char *line) {}
#endif
static int eval(const char *str) {
int err = 0;
double r = te_interp(str, &err);
if (err != 0) {
printf("Error at position %i\n", err);
return -1;
} else {
printf("%g\n", r);
return 0;
}
}
static void repl() {
while (1) {
char *line = readline("> ");
if (line == NULL) {
break;
} else if (strcmp(line, "q") == 0 || strcmp(line, "quit") == 0) {
free(line);
break;
}
if (eval(line) != -1) {
add_history(line);
}
free(line);
}
}
int main(int argc, char **argv) {
if (argc == 3 && strcmp(argv[1], "-e") == 0) {
if (eval(argv[2]) == -1) {
return 1;
} else {
return 0;
}
} else if (argc == 1) {
repl();
return 0;
} else {
printf("Usage: %s\n", argv[0]);
printf(" %s -e <expression>\n", argv[0]);
return 1;
}
}