github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/regexp/exec_test.gno (about)

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