forked from flyingmutant/rapid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrings.go
459 lines (394 loc) · 11.7 KB
/
strings.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright 2019 Gregory Petrosyan <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package rapid
import (
"bytes"
"fmt"
"math"
"regexp"
"regexp/syntax"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
var (
defaultRunes = []rune{
'A', 'a', '?',
'~', '!', '@', '#', '$', '%', '^', '&', '*', '_', '-', '+', '=',
'.', ',', ':', ';',
' ', '\t', '\r', '\n',
'/', '\\', '|',
'(', '[', '{', '<',
'\'', '"', '`',
'\x00', '\x0B', '\x1B', '\x7F', // NUL, VT, ESC, DEL
'\uFEFF', '\uFFFD', '\u202E', // BOM, replacement character, RTL override
'Ⱥ', // In UTF-8, Ⱥ increases in length from 2 to 3 bytes when lowercased
}
// unicode.Categories without surrogates (which are not allowed in UTF-8), ordered by taste
defaultTables = []*unicode.RangeTable{
unicode.Lu, // Letter, uppercase (1781)
unicode.Ll, // Letter, lowercase (2145)
unicode.Lt, // Letter, titlecase (31)
unicode.Lm, // Letter, modifier (250)
unicode.Lo, // Letter, other (121212)
unicode.Nd, // Number, decimal digit (610)
unicode.Nl, // Number, letter (236)
unicode.No, // Number, other (807)
unicode.P, // Punctuation (788)
unicode.Sm, // Symbol, math (948)
unicode.Sc, // Symbol, currency (57)
unicode.Sk, // Symbol, modifier (121)
unicode.So, // Symbol, other (5984)
unicode.Mn, // Mark, nonspacing (1805)
unicode.Me, // Mark, enclosing (13)
unicode.Mc, // Mark, spacing combining (415)
unicode.Z, // Separator (19)
unicode.Cc, // Other, control (65)
unicode.Cf, // Other, format (152)
unicode.Co, // Other, private use (137468)
}
expandedTables = sync.Map{} // *unicode.RangeTable / regexp name -> []rune
compiledRegexps = sync.Map{} // regexp -> compiledRegexp
regexpNames = sync.Map{} // *regexp.Regexp -> string
charClassGens = sync.Map{} // regexp name -> *Generator
anyRuneGen = Rune()
anyRuneGenNoNL = Rune().Filter(func(r rune) bool { return r != '\n' })
)
type compiledRegexp struct {
syn *syntax.Regexp
re *regexp.Regexp
}
// Rune creates a rune generator. Rune is equivalent to [RuneFrom] with default set of runes and tables.
func Rune() *Generator[rune] {
return runesFrom(true, defaultRunes, defaultTables...)
}
// RuneFrom creates a rune generator from provided runes and tables.
// RuneFrom panics if both runes and tables are empty. RuneFrom panics if tables contain an empty table.
func RuneFrom(runes []rune, tables ...*unicode.RangeTable) *Generator[rune] {
return runesFrom(false, runes, tables...)
}
func runesFrom(default_ bool, runes []rune, tables ...*unicode.RangeTable) *Generator[rune] {
if len(tables) == 0 {
assertf(len(runes) > 0, "at least one rune should be specified")
}
if len(runes) == 0 {
assertf(len(tables) > 0, "at least one *unicode.RangeTable should be specified")
}
var weights []int
if len(runes) > 0 {
weights = append(weights, len(tables))
}
for range tables {
weights = append(weights, 1)
}
tables_ := make([][]rune, len(tables))
for i := range tables {
tables_[i] = expandRangeTable(tables[i], tables[i])
assertf(len(tables_[i]) > 0, "empty *unicode.RangeTable %v", i)
}
return newGenerator[rune](&runeGen{
die: newLoadedDie(weights),
runes: runes,
tables: tables_,
default_: default_,
})
}
type runeGen struct {
die *loadedDie
runes []rune
tables [][]rune
default_ bool
}
func (g *runeGen) String() string {
if g.default_ {
return "Rune()"
} else {
return fmt.Sprintf("Rune(%v runes, %v tables)", len(g.runes), len(g.tables))
}
}
func (g *runeGen) value(t *T) rune {
n := g.die.roll(t.s)
runes := g.runes
if len(g.runes) == 0 {
runes = g.tables[n]
} else if n > 0 {
runes = g.tables[n-1]
}
return runes[genIndex(t.s, len(runes), true)]
}
// String is a shorthand for [StringOf]([Rune]()).
func String() *Generator[string] {
return StringOf(anyRuneGen)
}
// StringN is a shorthand for [StringOfN]([Rune](), minRunes, maxRunes, maxLen).
func StringN(minRunes int, maxRunes int, maxLen int) *Generator[string] {
return StringOfN(anyRuneGen, minRunes, maxRunes, maxLen)
}
// StringOf is a shorthand for [StringOfN](elem, -1, -1, -1).
func StringOf(elem *Generator[rune]) *Generator[string] {
return StringOfN(elem, -1, -1, -1)
}
// StringOfN creates a UTF-8 string generator.
// If minRunes >= 0, generated strings have minimum minRunes runes.
// If maxRunes >= 0, generated strings have maximum maxRunes runes.
// If maxLen >= 0, generates strings have maximum length of maxLen.
// StringOfN panics if maxRunes >= 0 and minRunes > maxRunes.
// StringOfN panics if maxLen >= 0 and maxLen < maxRunes.
func StringOfN(elem *Generator[rune], minRunes int, maxRunes int, maxLen int) *Generator[string] {
assertValidRange(minRunes, maxRunes)
assertf(maxLen < 0 || maxLen >= maxRunes, "maximum length (%v) should not be less than maximum number of runes (%v)", maxLen, maxRunes)
return newGenerator[string](&stringGen{
elem: elem,
minRunes: minRunes,
maxRunes: maxRunes,
maxLen: maxLen,
})
}
type stringGen struct {
elem *Generator[rune]
minRunes int
maxRunes int
maxLen int
}
func (g *stringGen) String() string {
if g.elem == anyRuneGen {
if g.minRunes < 0 && g.maxRunes < 0 && g.maxLen < 0 {
return "String()"
} else {
return fmt.Sprintf("StringN(minRunes=%v, maxRunes=%v, maxLen=%v)", g.minRunes, g.maxRunes, g.maxLen)
}
} else {
if g.minRunes < 0 && g.maxRunes < 0 && g.maxLen < 0 {
return fmt.Sprintf("StringOf(%v)", g.elem)
} else {
return fmt.Sprintf("StringOfN(%v, minRunes=%v, maxRunes=%v, maxLen=%v)", g.elem, g.minRunes, g.maxRunes, g.maxLen)
}
}
}
func (g *stringGen) value(t *T) string {
repeat := newRepeat(g.minRunes, g.maxRunes, -1, g.elem.String())
var b strings.Builder
b.Grow(repeat.avg())
maxLen := g.maxLen
if maxLen < 0 {
maxLen = math.MaxInt
}
for repeat.more(t.s) {
r := g.elem.value(t)
n := utf8.RuneLen(r)
if n < 0 || b.Len()+n > maxLen {
repeat.reject()
} else {
b.WriteRune(r)
}
}
return b.String()
}
// StringMatching creates a UTF-8 string generator matching the provided [syntax.Perl] regular expression.
func StringMatching(expr string) *Generator[string] {
compiled, err := compileRegexp(expr)
assertf(err == nil, "%v", err)
return newGenerator[string](®expStringGen{
regexpGen{
expr: expr,
syn: compiled.syn,
re: compiled.re,
},
})
}
// SliceOfBytesMatching creates a UTF-8 byte slice generator matching the provided [syntax.Perl] regular expression.
func SliceOfBytesMatching(expr string) *Generator[[]byte] {
compiled, err := compileRegexp(expr)
assertf(err == nil, "%v", err)
return newGenerator[[]byte](®expSliceGen{
regexpGen{
expr: expr,
syn: compiled.syn,
re: compiled.re,
},
})
}
type runeWriter interface {
WriteRune(r rune) (int, error)
}
type regexpGen struct {
expr string
syn *syntax.Regexp
re *regexp.Regexp
}
type regexpStringGen struct{ regexpGen }
type regexpSliceGen struct{ regexpGen }
func (g *regexpStringGen) String() string {
return fmt.Sprintf("StringMatching(%q)", g.expr)
}
func (g *regexpSliceGen) String() string {
return fmt.Sprintf("SliceOfBytesMatching(%q)", g.expr)
}
func (g *regexpStringGen) maybeString(t *T) (string, bool) {
b := &strings.Builder{}
g.build(b, g.syn, t)
v := b.String()
if g.re.MatchString(v) {
return v, true
} else {
return "", false
}
}
func (g *regexpSliceGen) maybeSlice(t *T) ([]byte, bool) {
b := &bytes.Buffer{}
g.build(b, g.syn, t)
v := b.Bytes()
if g.re.Match(v) {
return v, true
} else {
return nil, false
}
}
func (g *regexpStringGen) value(t *T) string {
return find(g.maybeString, t, small)
}
func (g *regexpSliceGen) value(t *T) []byte {
return find(g.maybeSlice, t, small)
}
func (g *regexpGen) build(w runeWriter, re *syntax.Regexp, t *T) {
i := t.s.beginGroup(re.Op.String(), false)
switch re.Op {
case syntax.OpNoMatch:
panic(invalidData("no possible regexp match"))
case syntax.OpEmptyMatch:
t.s.drawBits(0)
case syntax.OpLiteral:
t.s.drawBits(0)
for _, r := range re.Rune {
_, _ = w.WriteRune(maybeFoldCase(t.s, r, re.Flags))
}
case syntax.OpCharClass, syntax.OpAnyCharNotNL, syntax.OpAnyChar:
sub := anyRuneGen
switch re.Op {
case syntax.OpCharClass:
sub = charClassGen(re)
case syntax.OpAnyCharNotNL:
sub = anyRuneGenNoNL
}
r := sub.value(t)
_, _ = w.WriteRune(maybeFoldCase(t.s, r, re.Flags))
case syntax.OpBeginLine, syntax.OpEndLine,
syntax.OpBeginText, syntax.OpEndText,
syntax.OpWordBoundary, syntax.OpNoWordBoundary:
t.s.drawBits(0) // do nothing and hope that find() is enough
case syntax.OpCapture:
g.build(w, re.Sub[0], t)
case syntax.OpStar, syntax.OpPlus, syntax.OpQuest, syntax.OpRepeat:
min, max := re.Min, re.Max
switch re.Op {
case syntax.OpStar:
min, max = 0, -1
case syntax.OpPlus:
min, max = 1, -1
case syntax.OpQuest:
min, max = 0, 1
}
repeat := newRepeat(min, max, -1, regexpName(re.Sub[0]))
for repeat.more(t.s) {
g.build(w, re.Sub[0], t)
}
case syntax.OpConcat:
for _, sub := range re.Sub {
g.build(w, sub, t)
}
case syntax.OpAlternate:
ix := genIndex(t.s, len(re.Sub), true)
g.build(w, re.Sub[ix], t)
default:
assertf(false, "invalid regexp op %v", re.Op)
}
t.s.endGroup(i, false)
}
func maybeFoldCase(s bitStream, r rune, flags syntax.Flags) rune {
n := uint64(0)
if flags&syntax.FoldCase != 0 {
n, _, _ = genUintN(s, 4, false)
}
for i := 0; i < int(n); i++ {
r = unicode.SimpleFold(r)
}
return r
}
func expandRangeTable(t *unicode.RangeTable, key any) []rune {
cached, ok := expandedTables.Load(key)
if ok {
return cached.([]rune)
}
n := 0
for _, r := range t.R16 {
n += int(r.Hi-r.Lo)/int(r.Stride) + 1
}
for _, r := range t.R32 {
n += int(r.Hi-r.Lo)/int(r.Stride) + 1
}
ret := make([]rune, 0, n)
for _, r := range t.R16 {
for i := uint32(r.Lo); i <= uint32(r.Hi); i += uint32(r.Stride) {
ret = append(ret, rune(i))
}
}
for _, r := range t.R32 {
for i := uint64(r.Lo); i <= uint64(r.Hi); i += uint64(r.Stride) {
ret = append(ret, rune(i))
}
}
expandedTables.Store(key, ret)
return ret
}
func compileRegexp(expr string) (compiledRegexp, error) {
cached, ok := compiledRegexps.Load(expr)
if ok {
return cached.(compiledRegexp), nil
}
syn, err := syntax.Parse(expr, syntax.Perl)
if err != nil {
return compiledRegexp{}, fmt.Errorf("failed to parse regexp %q: %v", expr, err)
}
re, err := regexp.Compile(expr)
if err != nil {
return compiledRegexp{}, fmt.Errorf("failed to compile regexp %q: %v", expr, err)
}
ret := compiledRegexp{syn, re}
compiledRegexps.Store(expr, ret)
return ret, nil
}
func regexpName(re *syntax.Regexp) string {
cached, ok := regexpNames.Load(re)
if ok {
return cached.(string)
}
s := re.String()
regexpNames.Store(re, s)
return s
}
func charClassGen(re *syntax.Regexp) *Generator[rune] {
cached, ok := charClassGens.Load(regexpName(re))
if ok {
return cached.(*Generator[rune])
}
t := &unicode.RangeTable{R32: make([]unicode.Range32, 0, len(re.Rune)/2)}
for i := 0; i < len(re.Rune); i += 2 {
// not a valid unicode.Range32, since it requires that Lo and Hi must always be >= 1<<16
// however, we don't really care, since the only use of these ranges is as input to expandRangeTable
t.R32 = append(t.R32, unicode.Range32{
Lo: uint32(re.Rune[i]),
Hi: uint32(re.Rune[i+1]),
Stride: 1,
})
}
g := newGenerator[rune](&runeGen{
die: newLoadedDie([]int{1}),
tables: [][]rune{expandRangeTable(t, regexpName(re))},
})
charClassGens.Store(regexpName(re), g)
return g
}