-
Notifications
You must be signed in to change notification settings - Fork 79
/
main.go
77 lines (71 loc) · 1.34 KB
/
main.go
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
package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
"github.com/dengsgo/math-engine/engine"
)
func main() {
loop()
}
// input loop
func loop() {
engine.RegFunction("double", 1, func(expr ...engine.ExprAST) float64 {
return engine.ExprASTResult(expr[0]) * 2
})
for {
fmt.Print("input /> ")
f := bufio.NewReader(os.Stdin)
s, err := f.ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
s = strings.TrimSpace(s)
if s == "" {
continue
}
if s == "exit" || s == "quit" || s == "q" {
fmt.Println("bye")
break
}
start := time.Now()
exec(s)
cost := time.Since(start)
fmt.Println("time: " + cost.String())
}
}
// call engine
func exec(exp string) {
// input text -> []token
toks, err := engine.Parse(exp)
if err != nil {
fmt.Println("ERROR: " + err.Error())
return
}
// []token -> AST Tree
ast := engine.NewAST(toks, exp)
if ast.Err != nil {
fmt.Println("ERROR: " + ast.Err.Error())
return
}
// AST builder
ar := ast.ParseExpression()
if ast.Err != nil {
fmt.Println("ERROR: " + ast.Err.Error())
return
}
fmt.Printf("ExprAST: %+v\n", ar)
// catch runtime errors
defer func() {
if e := recover(); e != nil {
fmt.Println("ERROR: ", e)
}
}()
// AST traversal -> result
r := engine.ExprASTResult(ar)
fmt.Println("progressing ...\t", r)
fmt.Printf("%s = %v\n", exp, r)
}