-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern.go
365 lines (315 loc) · 7.67 KB
/
pattern.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package zzglob
import (
"errors"
"fmt"
"io"
"slices"
)
// Pattern is a parsed glob pattern.
type Pattern struct {
root string
initial *state
}
// Parse parses a pattern.
func Parse(pattern string, opts ...ParseOption) (*Pattern, error) {
cfg := defaultParseConfig
for _, o := range opts {
o(&cfg)
}
// tokenise classifies each rune as literal or punctuation, interprets
// escape chars, etc.
tks := tokenise(pattern, &cfg)
// Preprocessing, for example replace ~/ with homedir.
*tks = preprocess(*tks)
// If the pattern is all literals, then it's a specific path.
if root := tks.allLiteral(); root != "" {
return &Pattern{
root: root,
initial: nil,
}, nil
}
// Find the root of the path. This is where directory walking starts.
root := findRoot(tks)
// Convert the rest of the sequence into a state machine.
initial, terminal, _, err := parseSequence(tks, false)
if err != nil {
return nil, err
}
// The terminal state is terminal.
terminal.Terminal = true
// Remove redundant nil edges, where possible. This should only ever remove
// edges and possibly redundant intermediate states.
reduce(initial)
// Done! Here's the machine.
return &Pattern{
root: root,
initial: initial,
}, nil
}
// MustParse calls Parse, and panics if unable to parse the pattern.
func MustParse(pattern string) *Pattern {
p, err := Parse(pattern)
if err != nil {
panic(err)
}
return p
}
// WriteDot writes a digraph representing the state machine to the writer
// (in GraphViz syntax).
func (p *Pattern) WriteDot(w io.Writer, hilite stateSet) error {
if _, err := fmt.Fprintln(w, "digraph {\n\trankdir=LR;"); err != nil {
return err
}
if _, err := fmt.Fprintln(w, "\tinitial [label=\"\", style=invis];"); err != nil {
return err
}
if p.initial == nil {
if _, err := fmt.Fprintln(w, "\tterminal [label=\"\", shape=doublecircle];"); err != nil {
return err
}
if _, err := fmt.Fprintf(w, "\tinitial -> terminal [label=\"%s\"];\n", p.root); err != nil {
return err
}
if _, err := fmt.Fprintln(w, "}"); err != nil {
return err
}
return nil
}
if _, err := fmt.Fprintf(w, "\tinitial -> state_%p [label=\"%s\"];\n", p.initial, p.root); err != nil {
return err
}
seen := make(map[*state]bool)
q := []*state{p.initial}
for len(q) > 0 {
s := q[0]
q = q[1:]
if seen[s] {
continue
}
seen[s] = true
shape := "circle"
if s.Terminal {
shape = "doublecircle"
}
fill := "white"
if _, ok := hilite[s]; ok {
fill = "green"
}
if _, err := fmt.Fprintf(w, "\tstate_%p [label=\"\", shape=%s, style=filled, fillcolor=%s];\n", s, shape, fill); err != nil {
return err
}
for _, e := range s.Out {
if _, err := fmt.Fprintf(w, "\tstate_%p -> state_%p [label=\"%v\"];\n", s, e.State, e.Expr); err != nil {
return err
}
if seen[e.State] {
continue
}
q = append(q, e.State)
}
}
if _, err := fmt.Fprintln(w, "}"); err != nil {
return err
}
return nil
}
// reduce tries to safely eliminate any edges with nil expression that it can
// find. "Safely" means both correctness (not changing which inputs the
// machine accepts or rejects) and complexity (e.g. not adding O(n^2) edges to
// replace the nil edges it eliminates).
func reduce(initial *state) {
seen := make(map[*state]bool)
q := []*state{initial}
for len(q) > 0 {
s := q[0]
q = q[1:]
if seen[s] {
continue
}
seen[s] = true
for i := range s.Out {
e := &s.Out[i]
// These optimisations only apply if the destination state is valid
// and has out-degree 1.
for {
// If e has nil Expr, then replace both the expression and
// target of e with the next edge:
//
// s --e(<nil>)--> s' --e'--> s''
// becomes
// s --e'--> s''
if e.State != nil && len(e.State.Out) == 1 && e.Expr == nil {
*e = e.State.Out[0]
continue
}
// If the next edge has nil expression, then replace the target
// state of e with the target of that subsequent edge.
//
// s --e--> s' --e'(<nil>)--> s''
// becomes
// s --e--> s''
if e.State != nil && len(e.State.Out) == 1 && e.State.Out[0].Expr == nil {
e.State = e.State.Out[0].State
continue
}
break
}
}
for _, e := range s.Out {
if !seen[e.State] {
q = append(q, e.State)
}
}
}
}
// parseSequence parses a sequence.
func parseSequence(tkns *tokens, insideAlt bool) (start, end *state, endedWith token, err error) {
start = &state{}
end = start
appendExp := func(e expression) {
next := &state{}
end.Out = append(end.Out, edge{
Expr: e,
State: next,
})
end = next
}
for {
t := tkns.next()
if t == nil {
return start, end, nil, nil
}
switch t := t.(type) {
case literal:
appendExp(literalExp(t))
case punctuation:
switch t {
case '*':
end.Out = append(end.Out, edge{
Expr: starExp{},
State: end,
})
case '⁑':
end.Out = append(end.Out, edge{
Expr: doubleStarExp{},
State: end,
})
case '?':
appendExp(questionExp{})
case '{':
ed, err := parseAlternation(tkns, end)
if err != nil {
return nil, nil, nil, err
}
end = ed
case '}':
if insideAlt {
return start, end, t, nil
}
appendExp(literalExp('}'))
case ',':
if insideAlt {
return start, end, t, nil
}
appendExp(literalExp(','))
case '[':
ed, err := parseCharClass(tkns, end)
if err != nil {
return nil, nil, nil, err
}
end = ed
default:
return nil, nil, nil, fmt.Errorf("invalid punctuation %c", t)
}
default:
return nil, nil, nil, fmt.Errorf("invalid token type %T", t)
}
}
}
// parseAlternation appends a branch to the automaton, a sequence in each
// branch, then a merge.
func parseAlternation(tks *tokens, from *state) (end *state, err error) {
end = &state{}
for {
st, ed, done, err := parseSequence(tks, true)
if err != nil {
return nil, err
}
from.Out = append(from.Out, edge{
Expr: nil,
State: st,
})
ed.Out = append(ed.Out, edge{
Expr: nil,
State: end,
})
switch done {
case punctuation(','):
continue
case punctuation('}'):
return end, nil
default:
return nil, errors.New("unterminated alternation - missing closing brace")
}
}
}
// parseCharClass is like parseAlternation, except each branch only matches
// exactly one character.
func parseCharClass(tks *tokens, from *state) (end *state, err error) {
end = &state{}
for {
t := tks.next()
if t == nil {
return nil, errors.New("unterminated char class - missing closing square bracket")
}
switch t := t.(type) {
case literal:
from.Out = append(from.Out, edge{
Expr: literalExp(t),
State: end,
})
case punctuation:
switch t {
case '^':
// Char class is actually negated!
return parseNegatedCharClass(tks, from)
case ']':
return end, nil
default:
return nil, fmt.Errorf("invalid %c within char class", t)
}
}
}
}
// parseNegatedCharClass parses a negated char class. tks should start with the
// the first token following `[^`.
func parseNegatedCharClass(tks *tokens, from *state) (*state, error) {
runes := make(map[rune]struct{})
for {
t := tks.next()
if t == nil {
return nil, errors.New("unterminated negated char class - missing closing square bracket")
}
switch t := t.(type) {
case literal:
runes[rune(t)] = struct{}{}
case punctuation:
switch t {
case ']':
expr := make(negatedCCExp, 0, len(runes))
for r := range runes {
expr = append(expr, r)
}
slices.Sort(expr)
end := &state{}
from.Out = append(from.Out, edge{
Expr: expr,
State: end,
})
return end, nil
default:
return nil, fmt.Errorf("invalid %c within negated char class", t)
}
}
}
}