-
Notifications
You must be signed in to change notification settings - Fork 4
/
deskcalc.go
84 lines (76 loc) · 1.23 KB
/
deskcalc.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
package main
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"math/big"
"os"
"strings"
)
func main() {
log.SetFlags(0)
log.SetPrefix("deskcalc: ")
flag.Usage = usage
flag.Parse()
if flag.NArg() < 1 {
usage()
}
str := strings.Join(flag.Args(), " ")
expr, err := parser.ParseExpr(str)
ck(err)
v := eval(expr)
fmt.Println(v.RatString())
}
func ck(err error) {
if err != nil {
log.Fatal(err)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: deskcalc [options] expr")
flag.PrintDefaults()
os.Exit(2)
}
func eval(e ast.Expr) *big.Rat {
switch e := e.(type) {
case *ast.BinaryExpr:
x := eval(e.X)
y := eval(e.Y)
switch e.Op {
case token.ADD:
return x.Add(x, y)
case token.SUB:
return x.Sub(x, y)
case token.MUL:
return x.Mul(x, y)
case token.QUO:
return x.Quo(x, y)
default:
log.Fatal("invalid expression")
}
case *ast.UnaryExpr:
x := eval(e.X)
switch e.Op {
case token.ADD:
return x
case token.SUB:
return x.Neg(x)
}
case *ast.BasicLit:
return newrat(e.Value)
default:
log.Fatal("invalid expression!")
}
return nil
}
func newrat(s string) *big.Rat {
r := new(big.Rat)
_, ok := r.SetString(s)
if !ok {
log.Fatal("invalid expression")
}
return r
}