-
Notifications
You must be signed in to change notification settings - Fork 3
/
parse.go
132 lines (118 loc) · 3.31 KB
/
parse.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package glitch
import (
"fmt"
"strings"
"unicode"
)
type Expression struct {
infix string
toks []string
}
func (expr *Expression) String() string {
return expr.infix
}
// shunting yard algorithm
func CompileExpression(input string) (exp *Expression, err error){
defer func() {
if r := recover(); r != nil {
exp = nil
err = fmt.Errorf("invalid expression: %s", input)
}
}()
lastWasDigit := false
output := ""
opers := make([]rune, 0, len(input))
nOpers, nOperands := 0, 0
for _,tok := range []rune(input) {
switch {
default:
return nil, fmt.Errorf("invalid expression: %s", input)
case unicode.IsSpace(tok):
continue
case tok == '(':
if lastWasDigit {
lastWasDigit = false
output += " "
}
opers = append(opers, tok)
case tok == ')':
if lastWasDigit {
lastWasDigit = false
output += " "
}
for {
// pop front
op := opers[len(opers)-1]
opers = opers[:len(opers)-1]
if op == '(' {
break
} else {
output += string(op) + " "
}
}
case operMap[tok] != nil:
nOpers++
op := operMap[tok]
if lastWasDigit {
lastWasDigit = false
output += " "
}
for {
if len(opers) == 0 {
break
}
opTok := opers[len(opers)-1]
if op2, ok := operMap[opTok]; !ok || !op2.hasPrecedence(op) {
break
}
// pop front
opers = opers[:len(opers)-1]
output += string(opTok) + " "
}
opers = append(opers, tok)
case validTok(tok):
nOperands++
if lastWasDigit {
lastWasDigit = false
output += " "
}
output += string(tok) + " "
case unicode.IsDigit(rune(tok)):
if !lastWasDigit {
nOperands++
lastWasDigit = true
}
output += string(tok)
}
}
// insufficient number of operands
if nOpers != nOperands - 1 {
return nil, fmt.Errorf("invalid expression: %s", input)
}
// try to find unmatched parenthesis
// while reversing oper order to insert
// in postfix expression
l := len(opers)
rev := make([]string, l)
l--
for i, tok := range opers {
if tok == '(' {
rev = nil
return nil, fmt.Errorf("invalid expression: %s", input)
}
rev[l - i] = string(tok)
}
// success
return &Expression{
infix: input,
toks: append(strings.Split(output, " "), rev...),
}, nil
}
func validTok(tok rune) bool {
return tok == 'c' || tok == 's' || tok == 'Y' ||
tok == 'r' || tok == 'x' || tok == 'y' ||
tok == 'N' || tok == 'R' || tok == 'G' ||
tok == 'B' || tok == 'e' || tok == 'b' ||
tok == 'H' || tok == 'L' || tok == 'h' ||
tok == 'v' || tok == 'd'
}