-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
252 lines (215 loc) · 7.1 KB
/
parser.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"fmt"
"regexp"
"strings"
"strconv"
"math/rand"
"time"
"errors"
"slices"
)
/* Struct representing the result(s) of a dice roll
*/
type DiceRoll struct {
Expression string
Results []int
}
/* Randomly rolls based on the given dice notation
*/
func rollDice(diceNotation string) (int, []int) {
lastChar := diceNotation[len(diceNotation)-1]
mode := "sum"
if lastChar == '!' {
mode = "highest"
diceNotation = diceNotation[:len(diceNotation)-1]
} else if lastChar == '?' {
mode = "lowest"
diceNotation = diceNotation[:len(diceNotation)-1]
}
parts := strings.Split(diceNotation, "d")
numRolls, _ := strconv.Atoi(parts[0])
sides, _ := strconv.Atoi(parts[1])
if sides < 1 || sides > 200 || numRolls < 1 || numRolls > 20 {
return 0, []int{}
}
rand.Seed(time.Now().UnixNano())
rolls := []int{}
result := 0
for i := 0; i < numRolls; i++ {
rollValue := rand.Intn(sides) + 1
rolls = append(rolls, rollValue)
switch mode {
case "sum":
result += rollValue
case "highest":
if rollValue > result {
result = rollValue
}
case "lowest":
if result == 0 || rollValue < result {
result = rollValue
}
}
}
return result, rolls
}
/* Given two operators, op1 and op2, checks if op1 has greater precedence.
* Returns true if op1 has greater precedence (should come first)
*/
func hasGreaterPrecedence(op1 string, op2 string) bool {
precedence := map[string]int{"+": 1, "-": 1, "*": 2, "/": 2}
return precedence[op1] >= precedence[op2]
}
/* Convert the input string into an array of tokens.
* Tokens can be one of three things:
* - An integer
* - An operator: + - / * ( )
* - Dice notation (XdY): ex. 4d12, 3d20
*/
func tokenize(input string) []string {
integerPattern := `\d+`
operatorPattern := `[+\-*/()]`
dicePattern := `\d*d\d+[!?]?`
tokenPattern := fmt.Sprintf("(%s)|(%s)|(%s)", dicePattern, integerPattern, operatorPattern)
re := regexp.MustCompile(tokenPattern)
matches := re.FindAllString(input, -1)
return matches
}
/* Parses an array of tokens into a final value.
* First, use shunting yard to change the array of tokens into reverse polish notation.
* Then, use a stack procedure to evaluate the reverse polish notation,
* rolling dice as we go!
*/
func parse(tokens []string) (int, []DiceRoll, error) {
// An array to contain the results of dice rolls
rollResults := []DiceRoll{}
// Regex we'll need a little further down
diePattern := regexp.MustCompile(`^d\d+[!?]?`)
dicePattern := regexp.MustCompile(`\d+d\d+[!?]?`)
integerPattern := regexp.MustCompile(`\d+`)
valuePattern := regexp.MustCompile(fmt.Sprintf(
"(%s)|(%s)|(%s)", dicePattern, diePattern, integerPattern,
))
operatorPattern := regexp.MustCompile(`[+\-*/]`)
leftParenPattern := regexp.MustCompile(`\(`)
rightParenPattern := regexp.MustCompile(`\)`)
// First, do the shunting yard algorithm to get it into reverse polish notation
operatorStack := []string{}
outputQueue := []string{}
for _, token := range tokens {
switch {
case valuePattern.MatchString(token):
outputQueue = append(outputQueue, token)
case operatorPattern.MatchString(token):
for len(operatorStack) > 0 && hasGreaterPrecedence(operatorStack[len(operatorStack)-1], token) {
outputQueue = append(outputQueue, operatorStack[len(operatorStack)-1])
operatorStack = operatorStack[:len(operatorStack)-1]
}
operatorStack = append(operatorStack, token)
case leftParenPattern.MatchString(token):
operatorStack = append(operatorStack, token)
case rightParenPattern.MatchString(token):
if len(operatorStack) == 0 {
return 0, rollResults, errors.New("Unable to parse: mismatched parens")
}
for operatorStack[len(operatorStack)-1] != "(" {
outputQueue = append(outputQueue, operatorStack[len(operatorStack)-1])
operatorStack = operatorStack[:len(operatorStack)-1]
}
if len(operatorStack) == 0 {
return 0, rollResults, errors.New("Unable to parse: mismatched parens")
}
operatorStack = operatorStack[:len(operatorStack)-1]
}
}
if slices.Contains(operatorStack, "(") {
return 0, rollResults, errors.New("Unable to parse: mismatched parens")
}
for len(operatorStack) > 0 {
outputQueue = append(outputQueue, operatorStack[len(operatorStack)-1])
operatorStack = operatorStack[:len(operatorStack)-1]
}
// Now, parse the reverse polish notation
stack := []int{}
for _, token := range outputQueue {
switch {
case diePattern.MatchString(token):
rollResult, rolls := rollDice("1" + token)
rollResults = append(rollResults, DiceRoll{
Expression: token,
Results: rolls,
})
stack = append(stack, rollResult)
case dicePattern.MatchString(token):
rollResult, rolls := rollDice(token)
rollResults = append(rollResults, DiceRoll{
Expression: token,
Results: rolls,
})
stack = append(stack, rollResult)
case integerPattern.MatchString(token):
n, _ := strconv.Atoi(token)
stack = append(stack, n)
case operatorPattern.MatchString(token):
if len(stack) == 0 {
return 0, rollResults, errors.New("Unable to parse: too many operators")
}
num2 := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if len(stack) == 0 {
return 0, rollResults, errors.New("Unable to parse: too many operators")
}
num1 := stack[len(stack)-1]
stack = stack[:len(stack)-1]
switch token {
case "+":
stack = append(stack, num1 + num2)
case "-":
stack = append(stack, num1 - num2)
case "*":
stack = append(stack, num1 * num2)
case "/":
stack = append(stack, num1 / num2)
}
}
}
if len(stack) != 1 {
return 0, rollResults, errors.New("Unable to parse malformed input")
}
return stack[0], rollResults, nil
}
/* Parses the given expression.
* Expression must contain only integers and dice notation,
* and may only use the operators + - * / and ()
*/
func ParseExpression(input string) (int, []DiceRoll, error) {
// Tokenize
tokenized := tokenize(input)
// Quick validation: Only valid tokens in input string
inputToCompare := strings.ReplaceAll(input, " ", "")
inputFromTokenized := strings.Join(tokenized, "")
if inputToCompare != inputFromTokenized {
return 0, []DiceRoll{}, errors.New(fmt.Sprintf("Invalid tokens found %v %v", inputToCompare, inputFromTokenized))
}
// Parse
return parse(tokenized)
}
/* Given a macro and a list of values, substitutes them into
* the macro to produce an expression with the values filled in.
*/
func FillMacro(input string, variables[]string) string {
// Set up variables for macros (A, B, C, etc..)
variablesMap := make(map[string]string)
for i, v := range variables {
if i < 26 {
key := string(rune('A' + i))
variablesMap[key] = v
}
}
// Replace variables in the input string
for key, value := range variablesMap {
input = strings.Replace(input, key, value, -1)
}
return input
}