-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (71 loc) · 1.21 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
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/madlambda/bwc/bwc"
)
var cmd string
func abortonerr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "err: %s\n", err)
os.Exit(1)
}
}
func printResult(res int) {
fmt.Printf("dec: %d\n", res)
fmt.Printf("bin: %b\n", res)
fmt.Printf("hex: %x\n", res)
}
func execCmd() (int, error) {
interp := bwc.NewInterp()
tree, err := bwc.Parse(cmd)
if err != nil {
return 0, err
}
res, err := interp.Eval(tree)
if err != nil {
return 0, err
}
return int(res), nil
}
func cli() {
interp := bwc.NewInterp()
for {
fmt.Printf("bwc> ")
var line [256]byte
n, err := os.Stdin.Read(line[:])
if err == io.EOF {
break
}
abortonerr(err)
buf := strings.TrimSpace(string(line[:n-1]))
if len(buf) == 0 {
fmt.Printf("\n")
continue
}
tree, err := bwc.Parse(buf)
if err != nil {
fmt.Printf("error: %s\n", err)
continue
}
res, err := interp.Eval(tree)
if err != nil {
fmt.Printf("error: %s\n", err)
}
printResult(int(res))
}
}
func main() {
flag.StringVar(&cmd, "c", "", "Evaluates a command")
flag.Parse()
if cmd != "" {
res, err := execCmd()
abortonerr(err)
printResult(res)
return
}
cli()
}