-
Notifications
You must be signed in to change notification settings - Fork 1
/
ast.go
408 lines (350 loc) · 7.75 KB
/
ast.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package parser
import (
"strings"
"unicode/utf8"
"github.com/pkg/errors"
"github.com/szabado/multiglob/internal/parser/lexer"
)
type NodeType int
//go:generate stringer -type=NodeType
const (
TypeRoot NodeType = iota
TypeAny
TypeText
TypeRange
)
func newBounds(low, high rune) (*Bounds, error) {
if high < low {
return nil, errors.Errorf("character range (%s, %s) is out of order",
string(low),
string(high))
}
return &Bounds{
Low: low,
High: high,
}, nil
}
type Bounds struct {
Low, High rune
}
func (b *Bounds) Contains(r rune) bool {
return b.Low <= r && r <= b.High
}
type Range struct {
Repeated bool
Inverse bool
Bounds []*Bounds
CharList string
}
func (r *Range) addValidChar(ru rune) {
r.CharList += string(ru)
}
// Matches returns true if the rune is matched by the Range.
func (r *Range) Matches(ru rune) bool {
if strings.ContainsRune(r.CharList, ru) {
return !r.Inverse
}
for _, bound := range r.Bounds {
if bound.Contains(ru) {
return !r.Inverse
}
}
return r.Inverse
}
type Node struct {
Type NodeType
Value string
Children []*Node
Leaf bool
Name []string // Only valid on leaf nodes. List of names of patterns terminate that on this leaf node
Range *Range
}
func (n *Node) canMerge(n2 *Node) bool {
if n == nil || n2 == nil {
return true
}
if n.Type != n2.Type {
return false
}
switch n.Type {
case TypeRoot:
// Do nothing, Root nodes can always merge
case TypeAny:
// Do nothing, Any nodes can always merge
case TypeText:
return n.Value == n2.Value
case TypeRange:
// Merging ranges can be messy. Avoid it.
return false
}
return true
}
func (n *Node) merge(n2 *Node) *Node {
if n == nil {
return n2
} else if n2 == nil {
return n
}
var children []*Node
if len(n.Children)+len(n2.Children) != 0 {
children = make([]*Node, len(n.Children), len(n.Children)+len(n2.Children))
copy(children, n.Children)
children = append(children, n2.Children...)
}
for i := 0; i < len(children); i++ {
for j := i + 1; j < len(children); j++ {
child1, child2 := children[i], children[j]
if !child1.canMerge(child2) {
continue
}
if j+1 >= len(children) {
children = children[:j]
} else {
children = append(children[:j], children[j+1:]...)
}
children[i] = child1.merge(child2)
}
}
return &Node{
Children: children,
Type: n.Type,
Value: n.Value,
Leaf: n.Leaf || n2.Leaf,
Name: mergeNames(n, n2),
}
}
func (n *Node) compress() {
if len(n.Children) != 1 {
for _, child := range n.Children {
child.compress()
}
return
}
child := n.Children[0]
child.compress()
if n.Type != TypeText || child.Type != TypeText || n.Leaf {
return
}
n.Value += child.Value
n.Children = child.Children
n.Leaf = child.Leaf
n.Name = mergeNames(n, child)
}
// Index returns the first index of the Node's expression in the string.
func (n *Node) Index(s string) int {
switch n.Type {
case TypeAny:
return 0
case TypeText:
return strings.Index(s, n.Value)
case TypeRange:
i := 0
for r, l := utf8.DecodeRuneInString(s); !(r == utf8.RuneError && l < 2); r, l = utf8.DecodeRuneInString(s[i:]) {
if n.Range.Matches(r) {
return i
}
i += l
}
}
return -1
}
// LastIndex returns the last index of the Node's expression in the string.
// For ranges, it returns the beginning of the last blob
func (n *Node) LastIndex(s string) int {
switch n.Type {
case TypeAny:
return len(s) - 1
case TypeText:
return strings.LastIndex(s, n.Value)
case TypeRange:
i := len(s)
inBlob := false
for r, l := utf8.DecodeLastRuneInString(s); !(r == utf8.RuneError && l < 2); r, l = utf8.DecodeLastRuneInString(s[:i]) {
contains := n.Range.Matches(r)
if contains && !inBlob {
inBlob = true
} else if !contains && inBlob {
return i
}
i -= l
}
}
return -1
}
func mergeNames(n1, n2 *Node) []string {
if n1.Leaf && n2.Leaf {
return append(n1.Name, n2.Name...)
} else if n1.Leaf {
return n1.Name
} else {
return n2.Name
}
}
func parse(name string, l *lexer.Lexer) (*Node, error) {
if !l.Next() {
return nil, nil
}
node := &Node{}
token := l.Scan()
switch token.Type {
case lexer.Asterisk:
node.Type = TypeAny
node.Value = "*"
case lexer.Bracket:
if token.Value == "]" {
node.Value = token.Value
node.Type = TypeText
break
}
var (
rnge = &Range{}
charCount = 0
previous rune
previousValid = false
parsingBounds = false
normalChar = false
escaped = false
)
for finished := false; !finished; charCount++ {
if !l.Next() {
return nil, errors.New("unclosed range missing ]")
}
token = l.Scan()
switch token.Type {
case lexer.Caret:
if charCount == 0 {
rnge.Inverse = true
normalChar = false
} else {
normalChar = true
}
escaped = false
case lexer.Dash:
if charCount == 0 || charCount == 1 && rnge.Inverse || escaped {
normalChar = true
} else {
parsingBounds = true
previousValid = false
normalChar = false
}
escaped = false
case lexer.Bracket:
if charCount == 0 || charCount == 1 && rnge.Inverse || escaped {
normalChar = true
} else if token.Value == "]" {
// Close this, handle error cases
if parsingBounds {
return nil, errors.Errorf("invalid range syntax %s-", string(previous))
}
if previousValid {
rnge.addValidChar(previous)
}
normalChar = false
finished = true
} else {
normalChar = true
}
escaped = false
case lexer.Backslash:
escaped = true
normalChar = false
default:
// Treat anything unhandled as text
fallthrough
case lexer.Text:
normalChar = true
if escaped {
return nil, errors.Errorf(`unknown escaping: \%s`, string(token.Value[0]))
}
}
if !normalChar {
continue
}
r := rune(token.Value[0])
if parsingBounds {
b, err := newBounds(previous, r)
if err != nil {
return nil, err
}
rnge.Bounds = append(rnge.Bounds, b)
parsingBounds = false
} else {
if previousValid {
rnge.addValidChar(previous)
}
previous = r
previousValid = true
}
}
node.Type = TypeRange
node.Range = rnge
if nextToken := l.Peek(); nextToken != nil {
if nextToken.Type == lexer.Plus {
l.Next() // consume the plus
node.Range.Repeated = true
}
}
case lexer.Backslash:
if !l.Next() {
return nil, errors.New("escape found at end of pattern")
}
nextToken := l.Scan()
switch nextToken.Type {
case lexer.Bracket, lexer.Asterisk, lexer.Backslash:
node.Value = nextToken.Value
node.Type = TypeText
default:
r, _ := utf8.DecodeRuneInString(nextToken.Value)
return nil, errors.Errorf(`unknown character escaping: \%s`, string(r))
}
// anything other than asterisk, bracket, backslash is an error
case lexer.Caret, lexer.Dash, lexer.Text:
node.Value = token.Value
node.Type = TypeText
}
child, err := parse(name, l)
if err != nil {
return nil, err
}
if child != nil {
node.Children = []*Node{
child,
}
}
node.Leaf = node.Children == nil
if node.Leaf {
node.Name = []string{name}
}
return node, nil
}
func Parse(name, input string) (*Node, error) {
root := newRootNode(nil)
if n, err := parse(name, lexer.New(input)); err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", input)
} else if n != nil {
root.Children = []*Node{n}
} else {
root.Children = []*Node{
{
Children: nil,
Value: "",
Type: TypeText,
Leaf: true,
Name: []string{name},
},
}
}
root.compress()
return root, nil
}
func newRootNode(children []*Node) *Node {
return &Node{
Value: "",
Type: TypeRoot,
Children: children,
Leaf: false,
}
}
func Merge(root1, root2 *Node) *Node {
return root1.merge(root2)
}