-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparse.go
202 lines (176 loc) · 6.29 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
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
package dice
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
)
// Regexes for parsing basic dice notation strings.
var (
// DiceNotationPattern is the base XdY notation pattern for matching dice
// strings.
DiceNotationPattern = `(?i)(?P<count>\d+)?d(?P<size>\d{1,}|f|F)`
// DiceNotationRegex is the compiled RegEx for parsing supported dice
// notations.
DiceNotationRegex = regexp.MustCompile(DiceNotationPattern)
// ComparePointpattern is the base pattern that matches compare points
// within dice modifiers.
ComparePointPattern = `(?P<compare>[=<>])?(?P<point>\d+)`
// ComparePointRegex is the compiled RegEx for parsing supported dice
// modifiers' core compare points.
ComparePointRegex = regexp.MustCompile(ComparePointPattern)
)
// DiceWithModifiersExpressionRegex is the compiled RegEx for parsing a dice
// notation with modifier strings appended.
var DiceWithModifiersExpressionRegex = regexp.MustCompile(
DiceNotationPattern + `(?P<modifiers>[!a-zA-Z=<>\d]*)`)
// Modifier regexes.
var (
rerollRegex = regexp.MustCompile(`(?i)r(?P<once>o)?` + ComparePointPattern + `?`)
sortRegex = regexp.MustCompile(`(?i)s(?P<sort>[ad])?`)
dropKeepRegex = regexp.MustCompile(`(?i)(?P<op>[dk][lh]?)(?P<num>\d+)?`)
criticalRegex = regexp.MustCompile(`(?i)c(?P<kind>[sf])` + ComparePointPattern)
explodeRegex = regexp.MustCompile(`(?i)!` + ComparePointPattern + `?`)
)
// Prefixes that indicate a modifier's start in a string
const (
rerollPrefix = "r"
sortPrefix = "s"
dropPrefix = "d"
keepPrefix = "k"
criticalPrefix = "c"
explodePrefix = "!"
compoundPrefix = "!!"
)
// ParseNotation parses the provided notation with updated regular expressions
// that also extract dice group modifiers.
func ParseNotation(ctx context.Context, notation string) (RollerProperties, error) {
props := RollerProperties{
DieModifiers: ModifierList{},
GroupModifiers: ModifierList{},
}
components := FindNamedCaptureGroups(DiceWithModifiersExpressionRegex, notation)
// Parse and cast dice properties from regex capture values
count64, err := strconv.ParseInt(components["count"], 10, 0)
count := int(count64)
if err != nil {
// either there was an implied count, ex 'd20', or count was invalid.
// parsing "0dX" should not result in a count of 1.
count = 1
}
props.Count = count
var size64 int64
if strings.EqualFold(components["size"], "f") {
props.Type = TypeFudge
props.Size = 1
} else if size64, err = strconv.ParseInt(components["size"], 10, 0); err != nil {
return props, &ErrParseError{notation, components["size"], "size", ": invalid size"}
} else if size64 < 0 {
return props, &ErrParseError{notation, components["size"], "size", ": invalid size"}
}
props.Size = int(size64)
// continuously loop through modifier string until we can't discern any more
// types. Once a modifier type is seen all modifiers of that type are
// searched out and added to the function sets in the order they appear in
// the string.
//
// There are circumstances where we have to discern potentially ambiguous
// modifier sets, like "2d6sdh" ("sort, drop highest" or "sort descending,
// unknown"?), so parsing should be left-to-right as with order of
// operations, and greedy
modifiers := components["modifiers"]
for modifiers != "" {
// check for context expiry
select {
default:
case <-ctx.Done():
panic(ctx.Err())
}
switch {
// rerolls
case strings.HasPrefix(modifiers, rerollPrefix):
remainingBytes := rerollRegex.ReplaceAllFunc([]byte(modifiers), func(matchBytes []byte) []byte {
captures := FindNamedCaptureGroups(rerollRegex, string(matchBytes))
point, _ := strconv.Atoi(captures["point"])
once := captures["once"] == "o"
props.DieModifiers = append(props.DieModifiers, &RerollModifier{
CompareTarget: &CompareTarget{
Compare: LookupCompareOp(captures["compare"]),
Target: point,
},
Once: once,
})
return []byte{}
})
modifiers = string(remainingBytes)
// sort
case strings.HasPrefix(modifiers, sortPrefix):
remainingBytes := sortRegex.ReplaceAllFunc([]byte(modifiers), func(matchBytes []byte) []byte {
captures := FindNamedCaptureGroups(sortRegex, string(matchBytes))
mod := new(SortModifier)
switch captures["sort"] {
case "d":
mod.Direction = SortDirectionDescending
default:
mod.Direction = SortDirectionAscending
}
props.GroupModifiers = append(props.GroupModifiers, mod)
return []byte(nil)
})
modifiers = string(remainingBytes)
// drop/keep
case strings.HasPrefix(modifiers, dropPrefix), strings.HasPrefix(modifiers, keepPrefix):
remainingBytes := dropKeepRegex.ReplaceAllFunc([]byte(modifiers), func(matchBytes []byte) []byte {
captures := FindNamedCaptureGroups(dropKeepRegex, string(matchBytes))
var num int
if captures["num"] == "" {
num = 1
} else {
num, _ = strconv.Atoi(captures["num"])
}
props.GroupModifiers = append(props.GroupModifiers, &DropKeepModifier{
Method: DropKeepMethod(captures["op"]),
Num: num,
})
return []byte(nil)
})
if modifiers == string(remainingBytes) {
fmt.Printf("invalid drop/keep: %s\n", modifiers)
modifiers = ""
break
}
modifiers = string(remainingBytes)
// critical success/failure
case strings.HasPrefix(modifiers, criticalPrefix):
remainingBytes := criticalRegex.ReplaceAllFunc([]byte(modifiers), func(matchBytes []byte) []byte {
// TODO
// captures := getNamedCaptures(criticalRegex, string(matchBytes))
return []byte(nil)
})
modifiers = string(remainingBytes)
// case strings.HasPrefix(modifiers, compoundPrefix):
// explode
case strings.HasPrefix(modifiers, explodePrefix):
remainingBytes := explodeRegex.ReplaceAllFunc([]byte(modifiers), func(matchBytes []byte) []byte {
// TODO
captures := FindNamedCaptureGroups(explodeRegex, string(matchBytes))
point, _ := strconv.Atoi(captures["point"])
// once := captures["once"] == "o"
props.DieModifiers = append(props.DieModifiers, &ExplodeModifier{
CompareTarget: &CompareTarget{
Compare: LookupCompareOp(captures["compare"]),
Target: point,
},
Once: false,
})
return []byte(nil)
})
modifiers = string(remainingBytes)
default:
fmt.Printf("invalid modifiers: %s\n", modifiers)
modifiers = ""
}
}
return props, nil
}