Debian Codegraph @

exec_test.go

raw symbols SCIP
1 //go:build re2_test_exhaustive
2
3 package re2
4
5 import (
6 "bufio"
7 "compress/bzip2"
8 "fmt"
9 "io"
10 "os"
11 "path/filepath"
12 "regexp/syntax"
13 "strconv"
14 "strings"
15 "testing"
16 "unicode/utf8"
17
18 "github.com/betterleaks/go-re2/internal"
19 )
20
21 // TestRE2 tests this package's regexp API against test cases
22 // considered during RE2's exhaustive tests, which run all possible
23 // regexps over a given set of atoms and operators, up to a given
24 // complexity, over all possible strings over a given alphabet,
25 // up to a given size. Rather than try to link with RE2, we read a
26 // log file containing the test cases and the expected matches.
27 // The log file, re2-exhaustive.txt, is generated by running 'make log'
28 // in the open source RE2 distribution https://github.com/google/re2/.
29 //
30 // The test file format is a sequence of stanzas like:
31 //
32 // strings
33 // "abc"
34 // "123x"
35 // regexps
36 // "[a-z]+"
37 // 0-3;0-3
38 // -;-
39 // "([0-9])([0-9])([0-9])"
40 // -;-
41 // -;0-3 0-1 1-2 2-3
42 //
43 // The stanza begins by defining a set of strings, quoted
44 // using Go double-quote syntax, one per line. Then the
45 // regexps section gives a sequence of regexps to run on
46 // the strings. In the block that follows a regexp, each line
47 // gives the semicolon-separated match results of running
48 // the regexp on the corresponding string.
49 // Each match result is either a single -, meaning no match, or a
50 // space-separated sequence of pairs giving the match and
51 // submatch indices. An unmatched subexpression formats
52 // its pair as a single - (not illustrated above). For now
53 // each regexp run produces two match results, one for a
54 // “full match” that restricts the regexp to matching the entire
55 // string or nothing, and one for a “partial match” that gives
56 // the leftmost first match found in the string.
57 //
58 // Lines beginning with # are comments. Lines beginning with
59 // a capital letter are test names printed during RE2's test suite
60 // and are echoed into t but otherwise ignored.
61 //
62 // At time of writing, re2-exhaustive.txt is 59 MB but compresses to 385 kB,
63 // so we store re2-exhaustive.txt.bz2 in the repository and decompress it on the fly.
64 func TestRE2Search(t *testing.T) {
65 testRE2(t, "testdata/re2-search.txt")
66 }
67
68 func testRE2(t *testing.T, file string) {
69 f, err := os.Open(file)
70 if err != nil {
71 t.Fatal(err)
72 }
73 defer f.Close()
74 var txt io.Reader
75 if strings.HasSuffix(file, ".bz2") {
76 z := bzip2.NewReader(f)
77 txt = z
78 file = file[:len(file)-len(".bz2")] // for error messages
79 } else {
80 txt = f
81 }
82 lineno := 0
83 scanner := bufio.NewScanner(txt)
84 var (
85 str []string
86 input []string
87 inStrings bool
88 re *Regexp
89 reLongest *Regexp
90 refull *Regexp
91 refullLongest *Regexp
92 nfail int
93 ncase int
94 )
95 for lineno := 1; scanner.Scan(); lineno++ {
96 line := scanner.Text()
97 switch {
98 case line == "":
99 t.Fatalf("%s:%d: unexpected blank line", file, lineno)
100 case line[0] == '#':
101 continue
102 case 'A' <= line[0] && line[0] <= 'Z':
103 // Test name.
104 t.Logf("%s\n", line)
105 continue
106 case line == "strings":
107 str = str[:0]
108 inStrings = true
109 case line == "regexps":
110 inStrings = false
111 case line[0] == '"':
112 q, err := strconv.Unquote(line)
113 if err != nil {
114 // Fatal because we'll get out of sync.
115 t.Fatalf("%s:%d: unquote %s: %v", file, lineno, line, err)
116 }
117 if inStrings {
118 str = append(str, q)
119 continue
120 }
121 // Is a regexp.
122 if len(input) != 0 {
123 t.Fatalf("%s:%d: out of sync: have %d strings left before %#q", file, lineno, len(input), q)
124 }
125 re, err = tryCompile(q)
126 if err != nil {
127 if err.Error() == "error parsing regexp: invalid escape sequence: `\\C`" {
128 // We don't and likely never will support \C; keep going.
129 continue
130 }
131 t.Errorf("%s:%d: compile %#q: %v", file, lineno, q, err)
132 if nfail++; nfail >= 100 {
133 t.Fatalf("stopping after %d errors", nfail)
134 }
135 continue
136 }
137 reLongest = re.Copy()
138 reLongest.Longest()
139 full := `\A(?:` + q + `)\z`
140 refull, err = tryCompile(full)
141 refullLongest = refull.Copy()
142 refullLongest.Longest()
143 if err != nil {
144 // Fatal because q worked, so this should always work.
145 t.Fatalf("%s:%d: compile full %#q: %v", file, lineno, full, err)
146 }
147 input = str
148 case line[0] == '-' || '0' <= line[0] && line[0] <= '9':
149 // A sequence of match results.
150 ncase++
151 if re == nil {
152 // Failed to compile: skip results.
153 continue
154 }
155 if len(input) == 0 {
156 t.Fatalf("%s:%d: out of sync: no input remaining", file, lineno)
157 }
158 var text string
159 text, input = input[0], input[1:]
160 if !isSingleBytes(text) && strings.Contains(re.String(), `\B`) {
161 // RE2's \B considers every byte position,
162 // so it sees 'not word boundary' in the
163 // middle of UTF-8 sequences. This package
164 // only considers the positions between runes,
165 // so it disagrees. Skip those cases.
166 continue
167 }
168 res := strings.Split(line, ";")
169 if len(res) != len(run) {
170 t.Fatalf("%s:%d: have %d test results, want %d", file, lineno, len(res), len(run))
171 }
172 for i := range res {
173 have, suffix := run[i](re, reLongest, refull, refullLongest, text)
174 want := parseResult(t, file, lineno, res[i])
175 if !same(have, want) {
176 t.Errorf("%s:%d: %#q%s.FindSubmatchIndex(%#q) = %v, want %v", file, lineno, re, suffix, text, have, want)
177 if nfail++; nfail >= 100 {
178 t.Fatalf("stopping after %d errors", nfail)
179 }
180 continue
181 }
182 b, suffix := matchCases[i](re, reLongest, refull, refullLongest, text)
183 if b != (want != nil) {
184 t.Errorf("%s:%d: %#q%s.MatchString(%#q) = %v, want %v", file, lineno, re, suffix, text, b, !b)
185 if nfail++; nfail >= 100 {
186 t.Fatalf("stopping after %d errors", nfail)
187 }
188 continue
189 }
190 }
191
192 default:
193 t.Fatalf("%s:%d: out of sync: %s\n", file, lineno, line)
194 }
195 }
196 if err := scanner.Err(); err != nil {
197 t.Fatalf("%s:%d: %v", file, lineno, err)
198 }
199 if len(input) != 0 {
200 t.Fatalf("%s:%d: out of sync: have %d strings left at EOF", file, lineno, len(input))
201 }
202 t.Logf("%d cases tested", ncase)
203 }
204
205 var run = []func(*Regexp, *Regexp, *Regexp, *Regexp, string) ([]int, string){
206 runFull,
207 runPartial,
208 runFullLongest,
209 runPartialLongest,
210 }
211
212 func runFull(re, reLongest, refull, refullLongest *Regexp, text string) ([]int, string) {
213 return refull.FindStringSubmatchIndex(text), "[full]"
214 }
215
216 func runPartial(re, reLongest, refull, refullLongest *Regexp, text string) ([]int, string) {
217 return re.FindStringSubmatchIndex(text), ""
218 }
219
220 func runFullLongest(re, reLongest, refull, refullLongest *Regexp, text string) ([]int, string) {
221 return refullLongest.FindStringSubmatchIndex(text), "[full,longest]"
222 }
223
224 func runPartialLongest(re, reLongest, refull, refullLongest *Regexp, text string) ([]int, string) {
225 return reLongest.FindStringSubmatchIndex(text), "[longest]"
226 }
227
228 var matchCases = []func(*Regexp, *Regexp, *Regexp, *Regexp, string) (bool, string){
229 matchFull,
230 matchPartial,
231 matchFullLongest,
232 matchPartialLongest,
233 }
234
235 func matchFull(re, reLongest, refull, refullLongest *Regexp, text string) (bool, string) {
236 return refull.MatchString(text), "[full]"
237 }
238
239 func matchPartial(re, reLongest, refull, refullLongest *Regexp, text string) (bool, string) {
240 return re.MatchString(text), ""
241 }
242
243 func matchFullLongest(re, reLongest, refull, refullLongest *Regexp, text string) (bool, string) {
244 return refullLongest.MatchString(text), "[full,longest]"
245 }
246
247 func matchPartialLongest(re, reLongest, refull, refullLongest *Regexp, text string) (bool, string) {
248 return reLongest.MatchString(text), "[longest]"
249 }
250
251 func isSingleBytes(s string) bool {
252 for _, c := range s {
253 if c >= utf8.RuneSelf {
254 return false
255 }
256 }
257 return true
258 }
259
260 func tryCompile(s string) (re *Regexp, err error) {
261 // Protect against panic during Compile.
262 defer func() {
263 if r := recover(); r != nil {
264 err = fmt.Errorf("panic: %v", r)
265 }
266 }()
267 return Compile(s)
268 }
269
270 func parseResult(t *testing.T, file string, lineno int, res string) []int {
271 // A single - indicates no match.
272 if res == "-" {
273 return nil
274 }
275 // Otherwise, a space-separated list of pairs.
276 n := 1
277 for j := 0; j < len(res); j++ {
278 if res[j] == ' ' {
279 n++
280 }
281 }
282 out := make([]int, 2*n)
283 i := 0
284 n = 0
285 for j := 0; j <= len(res); j++ {
286 if j == len(res) || res[j] == ' ' {
287 // Process a single pair. - means no submatch.
288 pair := res[i:j]
289 if pair == "-" {
290 out[n] = -1
291 out[n+1] = -1
292 } else {
293 loStr, hiStr, _ := strings.Cut(pair, "-")
294 lo, err1 := strconv.Atoi(loStr)
295 hi, err2 := strconv.Atoi(hiStr)
296 if err1 != nil || err2 != nil || lo > hi {
297 t.Fatalf("%s:%d: invalid pair %s", file, lineno, pair)
298 }
299 out[n] = lo
300 out[n+1] = hi
301 }
302 n += 2
303 i = j + 1
304 }
305 }
306 return out
307 }
308
309 func same(x, y []int) bool {
310 if len(x) != len(y) {
311 return false
312 }
313 for i, xi := range x {
314 if xi != y[i] {
315 return false
316 }
317 }
318 return true
319 }
320
321 // TestFowler runs this package's regexp API against the
322 // POSIX regular expression tests collected by Glenn Fowler
323 // at http://www2.research.att.com/~astopen/testregex/testregex.html.
324 func TestFowler(t *testing.T) {
325 files, err := filepath.Glob("testdata/*.dat")
326 if err != nil {
327 t.Fatal(err)
328 }
329 for _, file := range files {
330 t.Log(file)
331 testFowler(t, file)
332 }
333 }
334
335 var notab *Regexp
336
337 func init() {
338 notab = MustCompilePOSIX(`[^\t]+`)
339 }
340
341 func testFowler(t *testing.T, file string) {
342 f, err := os.Open(file)
343 if err != nil {
344 t.Error(err)
345 return
346 }
347 defer f.Close()
348 b := bufio.NewReader(f)
349 lineno := 0
350 lastRegexp := ""
351 Reading:
352 for {
353 lineno++
354 line, err := b.ReadString('\n')
355 if err != nil {
356 if err != io.EOF {
357 t.Errorf("%s:%d: %v", file, lineno, err)
358 }
359 break Reading
360 }
361
362 // http://www2.research.att.com/~astopen/man/man1/testregex.html
363 //
364 // INPUT FORMAT
365 // Input lines may be blank, a comment beginning with #, or a test
366 // specification. A specification is five fields separated by one
367 // or more tabs. NULL denotes the empty string and NIL denotes the
368 // 0 pointer.
369 if line[0] == '#' || line[0] == '\n' {
370 continue Reading
371 }
372 line = line[:len(line)-1]
373 field := notab.FindAllString(line, -1)
374 for i, f := range field {
375 if f == "NULL" {
376 field[i] = ""
377 }
378 if f == "NIL" {
379 t.Logf("%s:%d: skip: %s", file, lineno, line)
380 continue Reading
381 }
382 }
383 if len(field) == 0 {
384 continue Reading
385 }
386
387 // Field 1: the regex(3) flags to apply, one character per REG_feature
388 // flag. The test is skipped if REG_feature is not supported by the
389 // implementation. If the first character is not [BEASKLP] then the
390 // specification is a global control line. One or more of [BEASKLP] may be
391 // specified; the test will be repeated for each mode.
392 //
393 // B basic BRE (grep, ed, sed)
394 // E REG_EXTENDED ERE (egrep)
395 // A REG_AUGMENTED ARE (egrep with negation)
396 // S REG_SHELL SRE (sh glob)
397 // K REG_SHELL|REG_AUGMENTED KRE (ksh glob)
398 // L REG_LITERAL LRE (fgrep)
399 //
400 // a REG_LEFT|REG_RIGHT implicit ^...$
401 // b REG_NOTBOL lhs does not match ^
402 // c REG_COMMENT ignore space and #...\n
403 // d REG_SHELL_DOT explicit leading . match
404 // e REG_NOTEOL rhs does not match $
405 // f REG_MULTIPLE multiple \n separated patterns
406 // g FNM_LEADING_DIR testfnmatch only -- match until /
407 // h REG_MULTIREF multiple digit backref
408 // i REG_ICASE ignore case
409 // j REG_SPAN . matches \n
410 // k REG_ESCAPE \ to escape [...] delimiter
411 // l REG_LEFT implicit ^...
412 // m REG_MINIMAL minimal match
413 // n REG_NEWLINE explicit \n match
414 // o REG_ENCLOSED (|&) magic inside [@|&](...)
415 // p REG_SHELL_PATH explicit / match
416 // q REG_DELIMITED delimited pattern
417 // r REG_RIGHT implicit ...$
418 // s REG_SHELL_ESCAPED \ not special
419 // t REG_MUSTDELIM all delimiters must be specified
420 // u standard unspecified behavior -- errors not counted
421 // v REG_CLASS_ESCAPE \ special inside [...]
422 // w REG_NOSUB no subexpression match array
423 // x REG_LENIENT let some errors slide
424 // y REG_LEFT regexec() implicit ^...
425 // z REG_NULL NULL subexpressions ok
426 // $ expand C \c escapes in fields 2 and 3
427 // / field 2 is a regsubcomp() expression
428 // = field 3 is a regdecomp() expression
429 //
430 // Field 1 control lines:
431 //
432 // C set LC_COLLATE and LC_CTYPE to locale in field 2
433 //
434 // ?test ... output field 5 if passed and != EXPECTED, silent otherwise
435 // &test ... output field 5 if current and previous passed
436 // |test ... output field 5 if current passed and previous failed
437 // ; ... output field 2 if previous failed
438 // {test ... skip if failed until }
439 // } end of skip
440 //
441 // : comment comment copied as output NOTE
442 // :comment:test :comment: ignored
443 // N[OTE] comment comment copied as output NOTE
444 // T[EST] comment comment
445 //
446 // number use number for nmatch (20 by default)
447 flag := field[0]
448 switch flag[0] {
449 case '?', '&', '|', ';', '{', '}':
450 // Ignore all the control operators.
451 // Just run everything.
452 flag = flag[1:]
453 if flag == "" {
454 continue Reading
455 }
456 case ':':
457 var ok bool
458 if _, flag, ok = strings.Cut(flag[1:], ":"); !ok {
459 t.Logf("skip: %s", line)
460 continue Reading
461 }
462 case 'C', 'N', 'T', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
463 t.Logf("skip: %s", line)
464 continue Reading
465 }
466
467 // TODO: Check if this is expected.
468 // GAP: re2 seems to be able to compile this
469 if strings.Contains(line, `a{9876543210}`) {
470 t.Logf("skip: %s", line)
471 continue Reading
472 }
473
474 // GAP: re2 ignores invalid utf-8
475 if strings.Contains(line, `\x01\xff`) {
476 t.Logf("skip: %s", line)
477 continue Reading
478 }
479
480 // Can check field count now that we've handled the myriad comment formats.
481 if len(field) < 4 {
482 t.Errorf("%s:%d: too few fields: %s", file, lineno, line)
483 continue Reading
484 }
485
486 // Expand C escapes (a.k.a. Go escapes).
487 if strings.Contains(flag, "$") {
488 f := `"` + field[1] + `"`
489 if field[1], err = strconv.Unquote(f); err != nil {
490 t.Errorf("%s:%d: cannot unquote %s", file, lineno, f)
491 }
492 f = `"` + field[2] + `"`
493 if field[2], err = strconv.Unquote(f); err != nil {
494 t.Errorf("%s:%d: cannot unquote %s", file, lineno, f)
495 }
496 }
497
498 // Field 2: the regular expression pattern; SAME uses the pattern from
499 // the previous specification.
500 //
501 if field[1] == "SAME" {
502 field[1] = lastRegexp
503 }
504 lastRegexp = field[1]
505
506 // Field 3: the string to match.
507 text := field[2]
508
509 // Field 4: the test outcome...
510 ok, shouldCompile, shouldMatch, pos := parseFowlerResult(field[3])
511 if !ok {
512 t.Errorf("%s:%d: cannot parse result %#q", file, lineno, field[3])
513 continue Reading
514 }
515
516 // Field 5: optional comment appended to the report.
517
518 Testing:
519 // Run test once for each specified capital letter mode that we support.
520 for _, c := range flag {
521 pattern := field[1]
522 syn := syntax.POSIX | syntax.ClassNL
523 switch c {
524 default:
525 continue Testing
526 case 'E':
527 // extended regexp (what we support)
528 case 'L':
529 // literal
530 pattern = QuoteMeta(pattern)
531 }
532
533 caseInsensitive := false
534 for _, c := range flag {
535 switch c {
536 case 'i':
537 syn |= syntax.FoldCase
538 caseInsensitive = true
539 }
540 }
541
542 re, err := internal.Compile(pattern, internal.CompileOptions{Longest: true, Posix: true, CaseInsensitive: caseInsensitive})
543 if err != nil {
544 if shouldCompile {
545 t.Errorf("%s:%d: %#q did not compile", file, lineno, pattern)
546 }
547 continue Testing
548 }
549 if !shouldCompile {
550 t.Errorf("%s:%d: %#q should not compile", file, lineno, pattern)
551 continue Testing
552 }
553 match := re.MatchString(text)
554 if match != shouldMatch {
555 t.Errorf("%s:%d: %#q.Match(%#q) = %v, want %v", file, lineno, pattern, text, match, shouldMatch)
556 continue Testing
557 }
558 have := re.FindStringSubmatchIndex(text)
559 if (len(have) > 0) != match {
560 t.Errorf("%s:%d: %#q.Match(%#q) = %v, but %#q.FindSubmatchIndex(%#q) = %v", file, lineno, pattern, text, match, pattern, text, have)
561 continue Testing
562 }
563 if len(have) > len(pos) {
564 have = have[:len(pos)]
565 }
566 if !same(have, pos) {
567 t.Errorf("%s:%d: %#q.FindSubmatchIndex(%#q) = %v, want %v", file, lineno, pattern, text, have, pos)
568 }
569 }
570 }
571 }
572
573 func parseFowlerResult(s string) (ok, compiled, matched bool, pos []int) {
574 // Field 4: the test outcome. This is either one of the posix error
575 // codes (with REG_ omitted) or the match array, a list of (m,n)
576 // entries with m and n being first and last+1 positions in the
577 // field 3 string, or NULL if REG_NOSUB is in effect and success
578 // is expected. BADPAT is acceptable in place of any regcomp(3)
579 // error code. The match[] array is initialized to (-2,-2) before
580 // each test. All array elements from 0 to nmatch-1 must be specified
581 // in the outcome. Unspecified endpoints (offset -1) are denoted by ?.
582 // Unset endpoints (offset -2) are denoted by X. {x}(o:n) denotes a
583 // matched (?{...}) expression, where x is the text enclosed by {...},
584 // o is the expression ordinal counting from 1, and n is the length of
585 // the unmatched portion of the subject string. If x starts with a
586 // number then that is the return value of re_execf(), otherwise 0 is
587 // returned.
588 switch {
589 case s == "":
590 // Match with no position information.
591 ok = true
592 compiled = true
593 matched = true
594 return
595 case s == "NOMATCH":
596 // Match failure.
597 ok = true
598 compiled = true
599 matched = false
600 return
601 case 'A' <= s[0] && s[0] <= 'Z':
602 // All the other error codes are compile errors.
603 ok = true
604 compiled = false
605 return
606 }
607 compiled = true
608
609 var x []int
610 for s != "" {
611 var end byte = ')'
612 if len(x)%2 == 0 {
613 if s[0] != '(' {
614 ok = false
615 return
616 }
617 s = s[1:]
618 end = ','
619 }
620 i := 0
621 for i < len(s) && s[i] != end {
622 i++
623 }
624 if i == 0 || i == len(s) {
625 ok = false
626 return
627 }
628 v := -1
629 var err error
630 if s[:i] != "?" {
631 v, err = strconv.Atoi(s[:i])
632 if err != nil {
633 ok = false
634 return
635 }
636 }
637 x = append(x, v)
638 s = s[i+1:]
639 }
640 if len(x)%2 != 0 {
641 ok = false
642 return
643 }
644 ok = true
645 matched = true
646 pos = x
647 return
648 }