Debian Codegraph @

internal/re2.go

raw symbols SCIP
1 package internal
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "runtime"
8 "strconv"
9 "strings"
10 "sync"
11 "sync/atomic"
12 "unicode"
13 "unicode/utf8"
14 )
15
16 // Use same max size as regexp package.
17 // https://github.com/golang/go/blob/master/src/regexp/syntax/parse.go#L95
18 const maxSize = 128 << 20
19
20 type Regexp struct {
21 ptr wasmPtr
22
23 opts CompileOptions
24
25 expr string
26
27 numMatches int
28 groupNames []string
29 groupNamesOnce sync.Once
30
31 abi *libre2ABI
32
33 released uint32
34 }
35
36 // Copy returns a new Regexp object copied from re.
37 // Calling Longest on one copy does not affect another.
38 //
39 // Deprecated: In earlier releases, when using a Regexp in multiple goroutines,
40 // giving each goroutine its own copy helped to avoid lock contention.
41 // As of Go 1.12, using Copy is no longer necessary to avoid lock contention.
42 // Copy may still be appropriate if the reason for its use is to make
43 // two copies with different Longest settings.
44 func (re *Regexp) Copy() *Regexp {
45 // Recompiling is slower than this should be but for a deprecated method it
46 // is probably fine. The alternative would be to have reference counting to
47 // make sure regex is only deleted when the last reference is gone.
48
49 // Recompiling regex, no chance of err so don't bother checking it.
50 c, _ := Compile(re.expr, re.opts)
51 return c
52 }
53
54 type CompileOptions struct {
55 Posix bool
56 Longest bool
57 CaseInsensitive bool
58 Latin1 bool
59 }
60
61 func Compile(expr string, opts CompileOptions) (*Regexp, error) {
62 abi := newABI()
63 alloc := abi.startOperation(len(expr) + 2)
64 defer abi.endOperation(alloc)
65
66 cs := alloc.newCString(expr)
67
68 rePtr := newRE(abi, cs, opts)
69 errCode, errArg := reError(abi, rePtr)
70 switch errCode {
71 case 0:
72 // No error.
73 case 1:
74 return nil, fmt.Errorf("error parsing regexp: unexpected error: %#q", errArg)
75 case 2:
76 return nil, fmt.Errorf("error parsing regexp: invalid escape sequence: %#q", errArg)
77 case 3:
78 return nil, fmt.Errorf("error parsing regexp: bad character class: %#q", errArg)
79 case 4:
80 return nil, fmt.Errorf("error parsing regexp: invalid character class range: %#q", errArg)
81 case 5:
82 return nil, fmt.Errorf("error parsing regexp: missing closing ]: %#q", errArg)
83 case 6:
84 return nil, fmt.Errorf("error parsing regexp: missing closing ): %#q", errArg)
85 case 7:
86 return nil, fmt.Errorf("error parsing regexp: unexpected ): %#q", errArg)
87 case 8:
88 return nil, fmt.Errorf("error parsing regexp: trailing backslash at end of expression: %#q", errArg)
89 case 9:
90 return nil, fmt.Errorf("error parsing regexp: missing argument to repetition operator: %#q", errArg)
91 case 10:
92 return nil, fmt.Errorf("error parsing regexp: bad repitition argument: %#q", errArg)
93 case 11:
94 return nil, fmt.Errorf("error parsing regexp: invalid nested repetition operator: %#q", errArg)
95 case 12:
96 return nil, fmt.Errorf("error parsing regexp: bad perl operator: %#q", errArg)
97 case 13:
98 return nil, fmt.Errorf("error parsing regexp: invalid UTF-8 in regexp: %#q", errArg)
99 case 14:
100 return nil, fmt.Errorf("error parsing regexp: bad named capture group: %#q", errArg)
101 case 15:
102 // TODO(anuraaga): While the unit test passes, it is likely that the actual limit is currently
103 // different than regexp.
104 return nil, errors.New("error parsing regexp: expression too large")
105 }
106
107 // Does not include whole expression match, e.g. $0
108 numGroups := numCapturingGroups(abi, rePtr)
109
110 re := &Regexp{
111 ptr: rePtr,
112 opts: opts,
113 expr: expr,
114 numMatches: numGroups + 1,
115 abi: abi,
116 }
117
118 // Use func(interface{}) form for nottinygc compatibility.
119 runtime.SetFinalizer(re, func(obj interface{}) {
120 if r, ok := obj.(*Regexp); ok {
121 r.release()
122 }
123 })
124
125 return re, nil
126 }
127
128 // Expand appends template to dst and returns the result; during the
129 // append, Expand replaces variables in the template with corresponding
130 // matches drawn from src. The match slice should have been returned by
131 // FindSubmatchIndex.
132 //
133 // In the template, a variable is denoted by a substring of the form
134 // $name or ${name}, where name is a non-empty sequence of letters,
135 // digits, and underscores. A purely numeric name like $1 refers to
136 // the submatch with the corresponding index; other names refer to
137 // capturing parentheses named with the (?P<name>...) syntax. A
138 // reference to an out of range or unmatched index or a name that is not
139 // present in the regular expression is replaced with an empty slice.
140 //
141 // In the $name form, name is taken to be as long as possible: $1x is
142 // equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.
143 //
144 // To insert a literal $ in the output, use $$ in the template.
145 func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte {
146 return re.expand(dst, string(template), src, "", match)
147 }
148
149 // ExpandString is like Expand but the template and source are strings.
150 // It appends to and returns a byte slice in order to give the calling
151 // code control over allocation.
152 func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte {
153 return re.expand(dst, template, nil, src, match)
154 }
155
156 func (re *Regexp) expand(dst []byte, template string, bsrc []byte, src string, match []int) []byte {
157 for len(template) > 0 {
158 before, after, ok := strings.Cut(template, "$")
159 if !ok {
160 break
161 }
162 dst = append(dst, before...)
163 template = after
164 if template != "" && template[0] == '$' {
165 // Treat $$ as $.
166 dst = append(dst, '$')
167 template = template[1:]
168 continue
169 }
170 name, num, rest, ok := extract(template)
171 if !ok {
172 // Malformed; treat $ as raw text.
173 dst = append(dst, '$')
174 continue
175 }
176 template = rest
177 if num >= 0 {
178 if 2*num+1 < len(match) && match[2*num] >= 0 {
179 if bsrc != nil {
180 dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...)
181 } else {
182 dst = append(dst, src[match[2*num]:match[2*num+1]]...)
183 }
184 }
185 } else {
186 for i, namei := range re.SubexpNames() {
187 if name == namei && 2*i+1 < len(match) && match[2*i] >= 0 {
188 if bsrc != nil {
189 dst = append(dst, bsrc[match[2*i]:match[2*i+1]]...)
190 } else {
191 dst = append(dst, src[match[2*i]:match[2*i+1]]...)
192 }
193 break
194 }
195 }
196 }
197 }
198
199 runtime.KeepAlive(re) // don't allow finalizer to run during method
200
201 dst = append(dst, template...)
202 return dst
203 }
204
205 // Find returns a slice holding the text of the leftmost match in b of the regular expression.
206 // A return value of nil indicates no match.
207 func (re *Regexp) Find(b []byte) []byte {
208 alloc := re.abi.startOperation(len(b) + 8)
209 defer re.abi.endOperation(alloc)
210
211 cs := alloc.newCStringFromBytes(b)
212
213 var dstCap [2]int
214
215 dst := re.find(&alloc, cs, dstCap[:0])
216 return matchedBytes(b, dst)
217 }
218
219 // FindIndex returns a two-element slice of integers defining the location of
220 // the leftmost match in b of the regular expression. The match itself is at
221 // b[loc[0]:loc[1]].
222 // A return value of nil indicates no match.
223 func (re *Regexp) FindIndex(b []byte) (loc []int) {
224 alloc := re.abi.startOperation(len(b) + 8)
225 defer re.abi.endOperation(alloc)
226 cs := alloc.newCStringFromBytes(b)
227
228 res := re.find(&alloc, cs, nil)
229 runtime.KeepAlive(b)
230 return res
231 }
232
233 // FindString returns a string holding the text of the leftmost match in s of the regular
234 // expression. If there is no match, the return value is an empty string,
235 // but it will also be empty if the regular expression successfully matches
236 // an empty string. Use FindStringIndex or FindStringSubmatch if it is
237 // necessary to distinguish these cases.
238 func (re *Regexp) FindString(s string) string {
239 alloc := re.abi.startOperation(len(s) + 8)
240 defer re.abi.endOperation(alloc)
241 cs := alloc.newCString(s)
242
243 var dstCap [2]int
244
245 dst := re.find(&alloc, cs, dstCap[:0])
246 return matchedString(s, dst)
247 }
248
249 // FindStringIndex returns a two-element slice of integers defining the
250 // location of the leftmost match in s of the regular expression. The match
251 // itself is at s[loc[0]:loc[1]].
252 // A return value of nil indicates no match.
253 func (re *Regexp) FindStringIndex(s string) (loc []int) {
254 alloc := re.abi.startOperation(len(s) + 8)
255 defer re.abi.endOperation(alloc)
256 cs := alloc.newCString(s)
257
258 res := re.find(&alloc, cs, nil)
259 runtime.KeepAlive(s)
260 return res
261 }
262
263 func (re *Regexp) find(alloc *allocation, cs cString, dstCap []int) []int {
264 matchArr := alloc.newCStringArray(1)
265 defer matchArr.free()
266
267 res := match(re, cs, matchArr.ptr, 1)
268 if !res {
269 return nil
270 }
271
272 m := readMatch(alloc, cs, matchArr.ptr, dstCap)
273 runtime.KeepAlive(matchArr)
274
275 runtime.KeepAlive(re) // don't allow finalizer to run during method
276
277 return m
278 }
279
280 // FindAll is the 'All' version of Find; it returns a slice of all successive
281 // matches of the expression, as defined by the 'All' description in the
282 // package comment.
283 // A return value of nil indicates no match.
284 func (re *Regexp) FindAll(b []byte, n int) [][]byte {
285 alloc := re.abi.startOperation(len(b) + 16)
286 defer re.abi.endOperation(alloc)
287
288 cs := alloc.newCStringFromBytes(b)
289
290 var matches [][]byte
291
292 re.findAll(&alloc, b, "", cs, n, func(match []int) {
293 matches = append(matches, matchedBytes(b, match))
294 })
295
296 return matches
297 }
298
299 // FindAllIndex is the 'All' version of FindIndex; it returns a slice of all
300 // successive matches of the expression, as defined by the 'All' description
301 // in the package comment.
302 // A return value of nil indicates no match.
303 func (re *Regexp) FindAllIndex(b []byte, n int) [][]int {
304 alloc := re.abi.startOperation(len(b) + 16)
305 defer re.abi.endOperation(alloc)
306
307 cs := alloc.newCStringFromBytes(b)
308
309 var matches [][]int
310
311 re.findAll(&alloc, b, "", cs, n, func(match []int) {
312 matches = append(matches, append([]int(nil), match...))
313 })
314
315 res := matches
316 runtime.KeepAlive(b)
317 return res
318 }
319
320 // FindAllString is the 'All' version of FindString; it returns a slice of all
321 // successive matches of the expression, as defined by the 'All' description
322 // in the package comment.
323 // A return value of nil indicates no match.
324 func (re *Regexp) FindAllString(s string, n int) []string {
325 alloc := re.abi.startOperation(len(s) + 16)
326 defer re.abi.endOperation(alloc)
327
328 cs := alloc.newCString(s)
329
330 var matches []string
331
332 re.findAll(&alloc, nil, s, cs, n, func(match []int) {
333 matches = append(matches, matchedString(s, match))
334 })
335
336 return matches
337 }
338
339 // FindAllStringIndex is the 'All' version of FindStringIndex; it returns a
340 // slice of all successive matches of the expression, as defined by the 'All'
341 // description in the package comment.
342 // A return value of nil indicates no match.
343 func (re *Regexp) FindAllStringIndex(s string, n int) [][]int {
344 alloc := re.abi.startOperation(len(s) + 16)
345 defer re.abi.endOperation(alloc)
346
347 cs := alloc.newCString(s)
348
349 var matches [][]int
350
351 re.findAll(&alloc, nil, s, cs, n, func(match []int) {
352 matches = append(matches, append([]int(nil), match...))
353 })
354
355 res := matches
356 runtime.KeepAlive(s)
357 return res
358 }
359
360 func (re *Regexp) findAll(alloc *allocation, bsrc []byte, src string, cs cString, n int, deliver func(match []int)) {
361 var dstCap [2]int
362
363 if n < 0 {
364 n = cs.length + 1
365 }
366
367 matchArr := alloc.newCStringArray(1)
368 defer matchArr.free()
369
370 count := 0
371 prevMatchEnd := -1
372 pos := 0
373 for pos < cs.length+1 {
374 if !matchFrom(re, cs, pos, matchArr.ptr, 1) {
375 break
376 }
377
378 match := readMatch(alloc, cs, matchArr.ptr, dstCap[:0])
379 accept := true
380 // Check if it's an empty match following a match, which we ignore.
381 if match[0] == match[1] && match[0] == prevMatchEnd { //nolint:gocritic
382 // We don't allow an empty match right
383 // after a previous match, so ignore it.
384 accept = false
385 }
386
387 pos = nextPos(bsrc, src, pos, match[1])
388
389 if accept {
390 deliver(match)
391 count++
392 }
393 prevMatchEnd = match[1]
394
395 if count == n {
396 break
397 }
398 }
399
400 runtime.KeepAlive(matchArr)
401
402 runtime.KeepAlive(re) // don't allow finalizer to run during method
403 }
404
405 // FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice
406 // of all successive matches of the expression, as defined by the 'All'
407 // description in the package comment.
408 // A return value of nil indicates no match.
409 func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte {
410 alloc := re.abi.startOperation(len(b) + 8*re.numMatches + 8)
411 defer re.abi.endOperation(alloc)
412
413 cs := alloc.newCStringFromBytes(b)
414
415 var matches [][][]byte
416
417 re.findAllSubmatch(&alloc, b, "", cs, re.numMatches, n, func(match []int) {
418 matched := make([][]byte, len(match)/2)
419 for i := 0; i < len(match); i += 2 {
420 matched[i/2] = matchedBytes(b, match[i:i+2])
421 }
422 matches = append(matches, matched)
423 })
424
425 return matches
426 }
427
428 // FindAllSubmatchIndex is the 'All' version of FindSubmatchIndex; it returns
429 // a slice of all successive matches of the expression, as defined by the
430 // 'All' description in the package comment.
431 // A return value of nil indicates no match.
432 func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int {
433 alloc := re.abi.startOperation(len(b) + 8*re.numMatches + 8)
434 defer re.abi.endOperation(alloc)
435
436 cs := alloc.newCStringFromBytes(b)
437
438 var matches [][]int
439
440 re.findAllSubmatch(&alloc, b, "", cs, re.numMatches, n, func(match []int) {
441 matches = append(matches, match)
442 })
443
444 res := matches
445 runtime.KeepAlive(b)
446 return res
447 }
448
449 // FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it
450 // returns a slice of all successive matches of the expression, as defined by
451 // the 'All' description in the package comment.
452 // A return value of nil indicates no match.
453 func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string {
454 alloc := re.abi.startOperation(len(s) + 8*re.numMatches + 8)
455 defer re.abi.endOperation(alloc)
456
457 cs := alloc.newCString(s)
458
459 var matches [][]string
460
461 re.findAllSubmatch(&alloc, nil, s, cs, re.numMatches, n, func(match []int) {
462 matched := make([]string, len(match)/2)
463 for i := 0; i < len(match); i += 2 {
464 matched[i/2] = matchedString(s, match[i:i+2])
465 }
466 matches = append(matches, matched)
467 })
468
469 return matches
470 }
471
472 // FindAllStringSubmatchIndex is the 'All' version of
473 // FindStringSubmatchIndex; it returns a slice of all successive matches of
474 // the expression, as defined by the 'All' description in the package
475 // comment.
476 // A return value of nil indicates no match.
477 func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int {
478 alloc := re.abi.startOperation(len(s) + 8*re.numMatches + 8)
479 defer re.abi.endOperation(alloc)
480
481 cs := alloc.newCString(s)
482
483 var matches [][]int
484
485 re.findAllSubmatch(&alloc, nil, s, cs, re.numMatches, n, func(match []int) {
486 matches = append(matches, match)
487 })
488
489 res := matches
490 runtime.KeepAlive(s)
491 return res
492 }
493
494 func (re *Regexp) findAllSubmatch(alloc *allocation, bsrc []byte, src string, cs cString, nmatch, n int, deliver func(match []int)) {
495 if n < 0 {
496 n = cs.length + 1
497 }
498
499 matchArr := alloc.newCStringArray(nmatch)
500 defer matchArr.free()
501
502 count := 0
503 prevMatchEnd := -1
504 pos := 0
505 for pos < cs.length+1 {
506 if !matchFrom(re, cs, pos, matchArr.ptr, uint32(nmatch)) {
507 break
508 }
509
510 var matches []int
511 accept := true
512 readMatches(alloc, cs, matchArr.ptr, nmatch, func(match []int) bool {
513 if len(matches) == 0 {
514 // First match, check if it's an empty match following a match, which we ignore.
515 if match[0] == match[1] && match[0] == prevMatchEnd { //nolint:gocritic
516 accept = false
517 }
518
519 pos = nextPos(bsrc, src, pos, match[1])
520 prevMatchEnd = match[1]
521 }
522 if accept {
523 matches = append(matches, match...)
524 return true
525 }
526 return false
527 })
528 if accept {
529 deliver(matches)
530 }
531 count++
532
533 if count == n {
534 break
535 }
536 }
537
538 runtime.KeepAlive(matchArr)
539
540 runtime.KeepAlive(re) // don't allow finalizer to run during method
541 }
542
543 // FindSubmatch returns a slice of slices holding the text of the leftmost
544 // match of the regular expression in b and the matches, if any, of its
545 // subexpressions, as defined by the 'Submatch' descriptions in the package
546 // comment.
547 // A return value of nil indicates no match.
548 func (re *Regexp) FindSubmatch(b []byte) [][]byte {
549 alloc := re.abi.startOperation(len(b) + 8*re.numMatches)
550 defer re.abi.endOperation(alloc)
551
552 cs := alloc.newCStringFromBytes(b)
553
554 var matches [][]byte
555
556 re.findSubmatch(&alloc, cs, func(match []int) bool {
557 matches = append(matches, matchedBytes(b, match))
558 return true
559 })
560
561 return matches
562 }
563
564 // FindSubmatchIndex returns a slice holding the index pairs identifying the
565 // leftmost match of the regular expression in b and the matches, if any, of
566 // its subexpressions, as defined by the 'Submatch' and 'Index' descriptions
567 // in the package comment.
568 // A return value of nil indicates no match.
569 func (re *Regexp) FindSubmatchIndex(b []byte) []int {
570 alloc := re.abi.startOperation(len(b) + 8*re.numMatches)
571 defer re.abi.endOperation(alloc)
572
573 cs := alloc.newCStringFromBytes(b)
574
575 var matches []int
576
577 re.findSubmatch(&alloc, cs, func(match []int) bool {
578 matches = append(matches, match...)
579 return true
580 })
581
582 res := matches
583 runtime.KeepAlive(b)
584 return res
585 }
586
587 func (re *Regexp) FindStringSubmatch(s string) []string {
588 alloc := re.abi.startOperation(len(s) + 8*re.numMatches)
589 defer re.abi.endOperation(alloc)
590
591 cs := alloc.newCString(s)
592
593 var matches []string
594
595 re.findSubmatch(&alloc, cs, func(match []int) bool {
596 matches = append(matches, matchedString(s, match))
597 return true
598 })
599
600 return matches
601 }
602
603 // FindStringSubmatchIndex returns a slice holding the index pairs
604 // identifying the leftmost match of the regular expression in s and the
605 // matches, if any, of its subexpressions, as defined by the 'Submatch' and
606 // 'Index' descriptions in the package comment.
607 // A return value of nil indicates no match.
608 func (re *Regexp) FindStringSubmatchIndex(s string) []int {
609 alloc := re.abi.startOperation(len(s) + 8*re.numMatches)
610 defer re.abi.endOperation(alloc)
611
612 cs := alloc.newCString(s)
613
614 var matches []int
615
616 re.findSubmatch(&alloc, cs, func(match []int) bool {
617 matches = append(matches, match...)
618 return true
619 })
620
621 res := matches
622 runtime.KeepAlive(s)
623 return res
624 }
625
626 func (re *Regexp) findSubmatch(alloc *allocation, cs cString, deliver func(match []int) bool) {
627 numGroups := re.numMatches
628 matchArr := alloc.newCStringArray(numGroups)
629 defer matchArr.free()
630
631 if !match(re, cs, matchArr.ptr, uint32(numGroups)) {
632 return
633 }
634
635 readMatches(alloc, cs, matchArr.ptr, numGroups, deliver)
636
637 runtime.KeepAlive(matchArr)
638
639 runtime.KeepAlive(re) // don't allow finalizer to run during method
640 }
641
642 // Longest makes future searches prefer the leftmost-longest match.
643 // That is, when matching against text, the regexp returns a match that
644 // begins as early as possible in the input (leftmost), and among those
645 // it chooses a match that is as long as possible.
646 // This method modifies the Regexp and may not be called concurrently
647 // with any other methods.
648 func (re *Regexp) Longest() {
649 alloc := re.abi.startOperation(len(re.expr) + 2)
650 defer re.abi.endOperation(alloc)
651
652 if re.opts.Longest {
653 return
654 }
655
656 // longest is not a mutable option in re2 so we must release and recompile.
657 deleteRE(re.abi, re.ptr)
658
659 cs := alloc.newCString(re.expr)
660 newOpts := re.opts
661 newOpts.Longest = true
662 re.ptr = newRE(re.abi, cs, newOpts)
663 }
664
665 // NumSubexp returns the number of parenthesized subexpressions in this Regexp.
666 func (re *Regexp) NumSubexp() int {
667 return re.numMatches - 1
668 }
669
670 // Split slices s into substrings separated by the expression and returns a slice of
671 // the substrings between those expression matches.
672 //
673 // The slice returned by this method consists of all the substrings of s
674 // not contained in the slice returned by FindAllString. When called on an expression
675 // that contains no metacharacters, it is equivalent to strings.SplitN.
676 //
677 // Example:
678 //
679 // s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
680 // // s: ["", "b", "b", "c", "cadaaae"]
681 //
682 // The count determines the number of substrings to return:
683 //
684 // n > 0: at most n substrings; the last substring will be the unsplit remainder.
685 // n == 0: the result is nil (zero substrings)
686 // n < 0: all substrings
687 func (re *Regexp) Split(s string, n int) []string {
688 // Copied as is from
689 // https://github.com/golang/go/blob/78472603c6bac7a52d42d565558b9c0cb12c3f9a/src/regexp/regexp.go#L1253
690 // The logic in this function is only for taking match indexes to split the string, regex itself
691 // delegates to our implementation.
692
693 if n == 0 {
694 return nil
695 }
696
697 if len(re.expr) > 0 && len(s) == 0 {
698 return []string{""}
699 }
700
701 matches := re.FindAllStringIndex(s, n)
702 strings := make([]string, 0, len(matches))
703
704 beg := 0
705 end := 0
706 for _, match := range matches {
707 if n > 0 && len(strings) >= n-1 {
708 break
709 }
710
711 end = match[0]
712 if match[1] != 0 {
713 strings = append(strings, s[beg:end])
714 }
715 beg = match[1]
716 }
717
718 if end != len(s) {
719 strings = append(strings, s[beg:])
720 }
721
722 return strings
723 }
724
725 // SubexpNames returns the names of the parenthesized subexpressions
726 // in this Regexp. The name for the first sub-expression is names[1],
727 // so that if m is a match slice, the name for m[i] is SubexpNames()[i].
728 // Since the Regexp as a whole cannot be named, names[0] is always
729 // the empty string. The slice should not be modified.
730 func (re *Regexp) SubexpNames() []string {
731 re.groupNamesOnce.Do(func() {
732 re.groupNames = subexpNames(re.abi, re.ptr, re.numMatches)
733 })
734 return re.groupNames
735 }
736
737 // SubexpIndex returns the index of the first subexpression with the given name,
738 // or -1 if there is no subexpression with that name.
739 //
740 // Note that multiple subexpressions can be written using the same name, as in
741 // (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob".
742 // In this case, SubexpIndex returns the index of the leftmost such subexpression
743 // in the regular expression.
744 func (re *Regexp) SubexpIndex(name string) int {
745 if name != "" {
746 for i, s := range re.SubexpNames() {
747 if name == s {
748 return i
749 }
750 }
751 }
752 return -1
753 }
754
755 // Match reports whether the byte slice b
756 // contains any match of the regular expression re.
757 func (re *Regexp) Match(b []byte) bool {
758 alloc := re.abi.startOperation(len(b))
759 defer re.abi.endOperation(alloc)
760
761 cs := alloc.newCStringFromBytes(b)
762 res := match(re, cs, nilWasmPtr, 0)
763 runtime.KeepAlive(b)
764
765 runtime.KeepAlive(re) // don't allow finalizer to run during method
766
767 return res
768 }
769
770 // MatchString reports whether the string s
771 // contains any match of the regular expression re.
772 func (re *Regexp) MatchString(s string) bool {
773 alloc := re.abi.startOperation(len(s))
774 defer re.abi.endOperation(alloc)
775
776 cs := alloc.newCString(s)
777 res := match(re, cs, nilWasmPtr, 0)
778 runtime.KeepAlive(s)
779
780 runtime.KeepAlive(re) // don't allow finalizer to run during method
781
782 return res
783 }
784
785 func (re *Regexp) release() {
786 if !atomic.CompareAndSwapUint32(&re.released, 0, 1) {
787 return
788 }
789 release(re)
790 }
791
792 func Release(re *Regexp) {
793 re.release()
794 }
795
796 // ReplaceAll returns a copy of src, replacing matches of the Regexp
797 // with the replacement text repl. Inside repl, $ signs are interpreted as
798 // in Expand, so for instance $1 represents the text of the first submatch.
799 func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
800 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
801 defer re.abi.endOperation(alloc)
802
803 cs := alloc.newCStringFromBytes(src)
804
805 n := 2
806 if bytes.IndexByte(repl, '$') >= 0 {
807 n = re.numMatches
808 }
809
810 srepl := ""
811 b := re.replaceAll(&alloc, src, "", cs, n, func(dst []byte, m []int) []byte {
812 if len(srepl) != len(repl) {
813 srepl = string(repl)
814 }
815 return re.expand(dst, srepl, src, "", m)
816 })
817 return b
818 }
819
820 // ReplaceAllFunc returns a copy of src in which all matches of the
821 // [Regexp] have been replaced by the return value of function repl applied
822 // to the matched byte slice. The replacement returned by repl is substituted
823 // directly, without using [Regexp.Expand].
824 func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte {
825 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
826 defer re.abi.endOperation(alloc)
827
828 cs := alloc.newCStringFromBytes(src)
829
830 return re.replaceAll(&alloc, src, "", cs, 2, func(dst []byte, m []int) []byte {
831 return append(dst, repl(src[m[0]:m[1]])...)
832 })
833 }
834
835 // ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp
836 // with the replacement bytes repl. The replacement repl is substituted directly,
837 // without using Expand.
838 func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte {
839 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
840 defer re.abi.endOperation(alloc)
841
842 cs := alloc.newCStringFromBytes(src)
843
844 return re.replaceAll(&alloc, src, "", cs, 2, func(dst []byte, _ []int) []byte {
845 return append(dst, repl...)
846 })
847 }
848
849 // ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp
850 // with the replacement string repl. The replacement repl is substituted directly,
851 // without using Expand.
852 func (re *Regexp) ReplaceAllLiteralString(src, repl string) string {
853 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
854 defer re.abi.endOperation(alloc)
855
856 cs := alloc.newCString(src)
857
858 b := re.replaceAll(&alloc, nil, src, cs, 2, func(dst []byte, _ []int) []byte {
859 return append(dst, repl...)
860 })
861
862 return string(b)
863 }
864
865 // ReplaceAllString returns a copy of src, replacing matches of the Regexp
866 // with the replacement string repl. Inside repl, $ signs are interpreted as
867 // in Expand, so for instance $1 represents the text of the first submatch.
868 func (re *Regexp) ReplaceAllString(src, repl string) string {
869 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
870 defer re.abi.endOperation(alloc)
871
872 cs := alloc.newCString(src)
873
874 n := 2
875 if strings.Contains(repl, "$") {
876 n = re.numMatches
877 }
878
879 b := re.replaceAll(&alloc, nil, src, cs, n, func(dst []byte, m []int) []byte {
880 return re.expand(dst, repl, nil, src, m)
881 })
882
883 return string(b)
884 }
885
886 // ReplaceAllStringFunc returns a copy of src in which all matches of the
887 // [Regexp] have been replaced by the return value of function repl applied
888 // to the matched substring. The replacement returned by repl is substituted
889 // directly, without using [Regexp.Expand].
890 func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string {
891 alloc := re.abi.startOperation(len(src) + 8*re.numMatches + 8)
892 defer re.abi.endOperation(alloc)
893
894 cs := alloc.newCString(src)
895
896 b := re.replaceAll(&alloc, nil, src, cs, 2, func(dst []byte, m []int) []byte {
897 return append(dst, repl(src[m[0]:m[1]])...)
898 })
899
900 return string(b)
901 }
902
903 func (re *Regexp) replaceAll(alloc *allocation, bsrc []byte, src string, cs cString, nmatch int, repl func(dst []byte, m []int) []byte) []byte {
904 lastMatchEnd := 0
905 var buf []byte
906
907 re.findAllSubmatch(alloc, bsrc, src, cs, nmatch, -1, func(a []int) {
908 // Copy the unmatched characters before this match.
909 if bsrc != nil {
910 buf = append(buf, bsrc[lastMatchEnd:a[0]]...)
911 } else {
912 buf = append(buf, src[lastMatchEnd:a[0]]...)
913 }
914
915 if a[1] > lastMatchEnd || a[0] == 0 {
916 buf = repl(buf, a)
917 }
918 lastMatchEnd = a[1]
919 })
920
921 if bsrc != nil {
922 buf = append(buf, bsrc[lastMatchEnd:]...)
923 } else {
924 buf = append(buf, src[lastMatchEnd:]...)
925 }
926
927 return buf
928 }
929
930 // String returns the source text used to compile the regular expression.
931 func (re *Regexp) String() string {
932 return re.expr
933 }
934
935 func subexpNames(abi *libre2ABI, rePtr wasmPtr, numMatches int) []string {
936 res := make([]string, numMatches)
937
938 iter := namedGroupsIter(abi, rePtr)
939 defer namedGroupsIterDelete(abi, iter)
940
941 for {
942 name, index, ok := namedGroupsIterNext(abi, iter)
943 if !ok {
944 break
945 }
946 res[index] = name
947 }
948
949 return res
950 }
951
952 // extract returns the name from a leading "name" or "{name}" in str.
953 // (The $ has already been removed by the caller.)
954 // If it is a number, extract returns num set to that number; otherwise num = -1.
955 // Copied as is from
956 // https://github.com/golang/go/blob/0fd7be7ee5f36215b5d6b8f23f35d60bf749805a/src/regexp/regexp.go#L981
957 func extract(str string) (name string, num int, rest string, ok bool) {
958 if str == "" {
959 return name, num, rest, ok
960 }
961 brace := false
962 if str[0] == '{' {
963 brace = true
964 str = str[1:]
965 }
966 i := 0
967 for i < len(str) {
968 r, size := utf8.DecodeRuneInString(str[i:])
969 if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' {
970 break
971 }
972 i += size
973 }
974 if i == 0 {
975 // empty name is not okay
976 return name, num, rest, ok
977 }
978 name = str[:i]
979 if brace {
980 if i >= len(str) || str[i] != '}' {
981 // missing closing brace
982 return name, num, rest, ok
983 }
984 i++
985 }
986
987 // Parse number.
988 num = 0
989 for i := range len(name) {
990 if name[i] < '0' || '9' < name[i] || num >= 1e8 {
991 num = -1
992 break
993 }
994 num = num*10 + int(name[i]) - '0'
995 }
996 // Disallow leading zeros.
997 if name[0] == '0' && len(name) > 1 {
998 num = -1
999 }
1000
1001 rest = str[i:]
1002 ok = true
1003 return name, num, rest, ok
1004 }
1005
1006 func matchedBytes(s []byte, match []int) []byte {
1007 if len(match) < 2 || match[0] == -1 {
1008 return nil
1009 }
1010 return s[match[0]:match[1]:match[1]]
1011 }
1012
1013 func matchedString(s string, match []int) string {
1014 if len(match) < 2 || match[0] == -1 {
1015 return ""
1016 }
1017 return s[match[0]:match[1]]
1018 }
1019
1020 func nextPos(bsrc []byte, src string, pos int, matchEnd int) int {
1021 // Advance past the match; always advance at least one character.
1022 var width int
1023 if bsrc != nil {
1024 _, width = utf8.DecodeRune(bsrc[pos:])
1025 } else {
1026 _, width = utf8.DecodeRuneInString(src[pos:])
1027 }
1028
1029 switch {
1030 case pos+width > matchEnd:
1031 return pos + width
1032 case pos+1 > matchEnd:
1033 // This clause is only needed at the end of the input
1034 // string. In that case, DecodeRuneInString returns width=0.
1035 return pos + 1
1036 default:
1037 return matchEnd
1038 }
1039 }
1040
1041 func QuoteForError(s string) string {
1042 if strconv.CanBackquote(s) {
1043 return "`" + s + "`"
1044 }
1045 return strconv.Quote(s)
1046 }