File tree 2 files changed +57
-2
lines changed
2 files changed +57
-2
lines changed Original file line number Diff line number Diff line change @@ -4,7 +4,7 @@ LFLAGS = -lm
4
4
5
5
.PHONY = all clean
6
6
7
- all : smoke smoke_pr bench example example2 example3
7
+ all : smoke smoke_pr repl bench example example2 example3
8
8
9
9
10
10
smoke : smoke.c tinyexpr.c
@@ -15,6 +15,9 @@ smoke_pr: smoke.c tinyexpr.c
15
15
$(CC ) $(CCFLAGS ) -DTE_POW_FROM_RIGHT -DTE_NAT_LOG -o $@ $^ $(LFLAGS )
16
16
./$@
17
17
18
+ repl : repl.o tinyexpr.o
19
+ $(CC ) $(CCFLAGS ) -o $@ $^ $(LFLAGS ) -lreadline
20
+
18
21
bench : benchmark.o tinyexpr.o
19
22
$(CC ) $(CCFLAGS ) -o $@ $^ $(LFLAGS )
20
23
@@ -31,4 +34,4 @@ example3: example3.o tinyexpr.o
31
34
$(CC ) -c $(CCFLAGS ) $< -o $@
32
35
33
36
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
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments