Home | History | Annotate | Download | only in syntax
      1 // Copyright 2011 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 syntax
      6 
      7 import (
      8 	"bytes"
      9 	"fmt"
     10 	"testing"
     11 	"unicode"
     12 )
     13 
     14 type parseTest struct {
     15 	Regexp string
     16 	Dump   string
     17 }
     18 
     19 var parseTests = []parseTest{
     20 	// Base cases
     21 	{`a`, `lit{a}`},
     22 	{`a.`, `cat{lit{a}dot{}}`},
     23 	{`a.b`, `cat{lit{a}dot{}lit{b}}`},
     24 	{`ab`, `str{ab}`},
     25 	{`a.b.c`, `cat{lit{a}dot{}lit{b}dot{}lit{c}}`},
     26 	{`abc`, `str{abc}`},
     27 	{`a|^`, `alt{lit{a}bol{}}`},
     28 	{`a|b`, `cc{0x61-0x62}`},
     29 	{`(a)`, `cap{lit{a}}`},
     30 	{`(a)|b`, `alt{cap{lit{a}}lit{b}}`},
     31 	{`a*`, `star{lit{a}}`},
     32 	{`a+`, `plus{lit{a}}`},
     33 	{`a?`, `que{lit{a}}`},
     34 	{`a{2}`, `rep{2,2 lit{a}}`},
     35 	{`a{2,3}`, `rep{2,3 lit{a}}`},
     36 	{`a{2,}`, `rep{2,-1 lit{a}}`},
     37 	{`a*?`, `nstar{lit{a}}`},
     38 	{`a+?`, `nplus{lit{a}}`},
     39 	{`a??`, `nque{lit{a}}`},
     40 	{`a{2}?`, `nrep{2,2 lit{a}}`},
     41 	{`a{2,3}?`, `nrep{2,3 lit{a}}`},
     42 	{`a{2,}?`, `nrep{2,-1 lit{a}}`},
     43 	// Malformed { } are treated as literals.
     44 	{`x{1001`, `str{x{1001}`},
     45 	{`x{9876543210`, `str{x{9876543210}`},
     46 	{`x{9876543210,`, `str{x{9876543210,}`},
     47 	{`x{2,1`, `str{x{2,1}`},
     48 	{`x{1,9876543210`, `str{x{1,9876543210}`},
     49 	{``, `emp{}`},
     50 	{`|`, `emp{}`}, // alt{emp{}emp{}} but got factored
     51 	{`|x|`, `alt{emp{}lit{x}emp{}}`},
     52 	{`.`, `dot{}`},
     53 	{`^`, `bol{}`},
     54 	{`$`, `eol{}`},
     55 	{`\|`, `lit{|}`},
     56 	{`\(`, `lit{(}`},
     57 	{`\)`, `lit{)}`},
     58 	{`\*`, `lit{*}`},
     59 	{`\+`, `lit{+}`},
     60 	{`\?`, `lit{?}`},
     61 	{`{`, `lit{{}`},
     62 	{`}`, `lit{}}`},
     63 	{`\.`, `lit{.}`},
     64 	{`\^`, `lit{^}`},
     65 	{`\$`, `lit{$}`},
     66 	{`\\`, `lit{\}`},
     67 	{`[ace]`, `cc{0x61 0x63 0x65}`},
     68 	{`[abc]`, `cc{0x61-0x63}`},
     69 	{`[a-z]`, `cc{0x61-0x7a}`},
     70 	{`[a]`, `lit{a}`},
     71 	{`\-`, `lit{-}`},
     72 	{`-`, `lit{-}`},
     73 	{`\_`, `lit{_}`},
     74 	{`abc`, `str{abc}`},
     75 	{`abc|def`, `alt{str{abc}str{def}}`},
     76 	{`abc|def|ghi`, `alt{str{abc}str{def}str{ghi}}`},
     77 
     78 	// Posix and Perl extensions
     79 	{`[[:lower:]]`, `cc{0x61-0x7a}`},
     80 	{`[a-z]`, `cc{0x61-0x7a}`},
     81 	{`[^[:lower:]]`, `cc{0x0-0x60 0x7b-0x10ffff}`},
     82 	{`[[:^lower:]]`, `cc{0x0-0x60 0x7b-0x10ffff}`},
     83 	{`(?i)[[:lower:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`},
     84 	{`(?i)[a-z]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`},
     85 	{`(?i)[^[:lower:]]`, `cc{0x0-0x40 0x5b-0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`},
     86 	{`(?i)[[:^lower:]]`, `cc{0x0-0x40 0x5b-0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`},
     87 	{`\d`, `cc{0x30-0x39}`},
     88 	{`\D`, `cc{0x0-0x2f 0x3a-0x10ffff}`},
     89 	{`\s`, `cc{0x9-0xa 0xc-0xd 0x20}`},
     90 	{`\S`, `cc{0x0-0x8 0xb 0xe-0x1f 0x21-0x10ffff}`},
     91 	{`\w`, `cc{0x30-0x39 0x41-0x5a 0x5f 0x61-0x7a}`},
     92 	{`\W`, `cc{0x0-0x2f 0x3a-0x40 0x5b-0x5e 0x60 0x7b-0x10ffff}`},
     93 	{`(?i)\w`, `cc{0x30-0x39 0x41-0x5a 0x5f 0x61-0x7a 0x17f 0x212a}`},
     94 	{`(?i)\W`, `cc{0x0-0x2f 0x3a-0x40 0x5b-0x5e 0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`},
     95 	{`[^\\]`, `cc{0x0-0x5b 0x5d-0x10ffff}`},
     96 	//	{ `\C`, `byte{}` },  // probably never
     97 
     98 	// Unicode, negatives, and a double negative.
     99 	{`\p{Braille}`, `cc{0x2800-0x28ff}`},
    100 	{`\P{Braille}`, `cc{0x0-0x27ff 0x2900-0x10ffff}`},
    101 	{`\p{^Braille}`, `cc{0x0-0x27ff 0x2900-0x10ffff}`},
    102 	{`\P{^Braille}`, `cc{0x2800-0x28ff}`},
    103 	{`\pZ`, `cc{0x20 0xa0 0x1680 0x2000-0x200a 0x2028-0x2029 0x202f 0x205f 0x3000}`},
    104 	{`[\p{Braille}]`, `cc{0x2800-0x28ff}`},
    105 	{`[\P{Braille}]`, `cc{0x0-0x27ff 0x2900-0x10ffff}`},
    106 	{`[\p{^Braille}]`, `cc{0x0-0x27ff 0x2900-0x10ffff}`},
    107 	{`[\P{^Braille}]`, `cc{0x2800-0x28ff}`},
    108 	{`[\pZ]`, `cc{0x20 0xa0 0x1680 0x2000-0x200a 0x2028-0x2029 0x202f 0x205f 0x3000}`},
    109 	{`\p{Lu}`, mkCharClass(unicode.IsUpper)},
    110 	{`[\p{Lu}]`, mkCharClass(unicode.IsUpper)},
    111 	{`(?i)[\p{Lu}]`, mkCharClass(isUpperFold)},
    112 	{`\p{Any}`, `dot{}`},
    113 	{`\p{^Any}`, `cc{}`},
    114 
    115 	// Hex, octal.
    116 	{`[\012-\234]\141`, `cat{cc{0xa-0x9c}lit{a}}`},
    117 	{`[\x{41}-\x7a]\x61`, `cat{cc{0x41-0x7a}lit{a}}`},
    118 
    119 	// More interesting regular expressions.
    120 	{`a{,2}`, `str{a{,2}}`},
    121 	{`\.\^\$\\`, `str{.^$\}`},
    122 	{`[a-zABC]`, `cc{0x41-0x43 0x61-0x7a}`},
    123 	{`[^a]`, `cc{0x0-0x60 0x62-0x10ffff}`},
    124 	{`[-]`, `cc{0x3b1-0x3b5 0x263a}`}, // utf-8
    125 	{`a*{`, `cat{star{lit{a}}lit{{}}`},
    126 
    127 	// Test precedences
    128 	{`(?:ab)*`, `star{str{ab}}`},
    129 	{`(ab)*`, `star{cap{str{ab}}}`},
    130 	{`ab|cd`, `alt{str{ab}str{cd}}`},
    131 	{`a(b|c)d`, `cat{lit{a}cap{cc{0x62-0x63}}lit{d}}`},
    132 
    133 	// Test flattening.
    134 	{`(?:a)`, `lit{a}`},
    135 	{`(?:ab)(?:cd)`, `str{abcd}`},
    136 	{`(?:a+b+)(?:c+d+)`, `cat{plus{lit{a}}plus{lit{b}}plus{lit{c}}plus{lit{d}}}`},
    137 	{`(?:a+|b+)|(?:c+|d+)`, `alt{plus{lit{a}}plus{lit{b}}plus{lit{c}}plus{lit{d}}}`},
    138 	{`(?:a|b)|(?:c|d)`, `cc{0x61-0x64}`},
    139 	{`a|.`, `dot{}`},
    140 	{`.|a`, `dot{}`},
    141 	{`(?:[abc]|A|Z|hello|world)`, `alt{cc{0x41 0x5a 0x61-0x63}str{hello}str{world}}`},
    142 	{`(?:[abc]|A|Z)`, `cc{0x41 0x5a 0x61-0x63}`},
    143 
    144 	// Test Perl quoted literals
    145 	{`\Q+|*?{[\E`, `str{+|*?{[}`},
    146 	{`\Q+\E+`, `plus{lit{+}}`},
    147 	{`\Q\\E`, `lit{\}`},
    148 	{`\Q\\\E`, `str{\\}`},
    149 
    150 	// Test Perl \A and \z
    151 	{`(?m)^`, `bol{}`},
    152 	{`(?m)$`, `eol{}`},
    153 	{`(?-m)^`, `bot{}`},
    154 	{`(?-m)$`, `eot{}`},
    155 	{`(?m)\A`, `bot{}`},
    156 	{`(?m)\z`, `eot{\z}`},
    157 	{`(?-m)\A`, `bot{}`},
    158 	{`(?-m)\z`, `eot{\z}`},
    159 
    160 	// Test named captures
    161 	{`(?P<name>a)`, `cap{name:lit{a}}`},
    162 
    163 	// Case-folded literals
    164 	{`[Aa]`, `litfold{A}`},
    165 	{`[\x{100}\x{101}]`, `litfold{}`},
    166 	{`[]`, `litfold{}`},
    167 
    168 	// Strings
    169 	{`abcde`, `str{abcde}`},
    170 	{`[Aa][Bb]cd`, `cat{strfold{AB}str{cd}}`},
    171 
    172 	// Factoring.
    173 	{`abc|abd|aef|bcx|bcy`, `alt{cat{lit{a}alt{cat{lit{b}cc{0x63-0x64}}str{ef}}}cat{str{bc}cc{0x78-0x79}}}`},
    174 	{`ax+y|ax+z|ay+w`, `cat{lit{a}alt{cat{plus{lit{x}}cc{0x79-0x7a}}cat{plus{lit{y}}lit{w}}}}`},
    175 
    176 	// Bug fixes.
    177 	{`(?:.)`, `dot{}`},
    178 	{`(?:x|(?:xa))`, `cat{lit{x}alt{emp{}lit{a}}}`},
    179 	{`(?:.|(?:.a))`, `cat{dot{}alt{emp{}lit{a}}}`},
    180 	{`(?:A(?:A|a))`, `cat{lit{A}litfold{A}}`},
    181 	{`(?:A|a)`, `litfold{A}`},
    182 	{`A|(?:A|a)`, `litfold{A}`},
    183 	{`(?s).`, `dot{}`},
    184 	{`(?-s).`, `dnl{}`},
    185 	{`(?:(?:^).)`, `cat{bol{}dot{}}`},
    186 	{`(?-s)(?:(?:^).)`, `cat{bol{}dnl{}}`},
    187 
    188 	// RE2 prefix_tests
    189 	{`abc|abd`, `cat{str{ab}cc{0x63-0x64}}`},
    190 	{`a(?:b)c|abd`, `cat{str{ab}cc{0x63-0x64}}`},
    191 	{`abc|abd|aef|bcx|bcy`,
    192 		`alt{cat{lit{a}alt{cat{lit{b}cc{0x63-0x64}}str{ef}}}` +
    193 			`cat{str{bc}cc{0x78-0x79}}}`},
    194 	{`abc|x|abd`, `alt{str{abc}lit{x}str{abd}}`},
    195 	{`(?i)abc|ABD`, `cat{strfold{AB}cc{0x43-0x44 0x63-0x64}}`},
    196 	{`[ab]c|[ab]d`, `cat{cc{0x61-0x62}cc{0x63-0x64}}`},
    197 	{`(?:xx|yy)c|(?:xx|yy)d`,
    198 		`cat{alt{str{xx}str{yy}}cc{0x63-0x64}}`},
    199 	{`x{2}|x{2}[0-9]`,
    200 		`cat{rep{2,2 lit{x}}alt{emp{}cc{0x30-0x39}}}`},
    201 	{`x{2}y|x{2}[0-9]y`,
    202 		`cat{rep{2,2 lit{x}}alt{lit{y}cat{cc{0x30-0x39}lit{y}}}}`},
    203 
    204 	// Valid repetitions.
    205 	{`((((((((((x{2}){2}){2}){2}){2}){2}){2}){2}){2}))`, ``},
    206 	{`((((((((((x{1}){2}){2}){2}){2}){2}){2}){2}){2}){2})`, ``},
    207 }
    208 
    209 const testFlags = MatchNL | PerlX | UnicodeGroups
    210 
    211 func TestParseSimple(t *testing.T) {
    212 	testParseDump(t, parseTests, testFlags)
    213 }
    214 
    215 var foldcaseTests = []parseTest{
    216 	{`AbCdE`, `strfold{ABCDE}`},
    217 	{`[Aa]`, `litfold{A}`},
    218 	{`a`, `litfold{A}`},
    219 
    220 	// 0x17F is an old English long s (looks like an f) and folds to s.
    221 	// 0x212A is the Kelvin symbol and folds to k.
    222 	{`A[F-g]`, `cat{litfold{A}cc{0x41-0x7a 0x17f 0x212a}}`}, // [Aa][A-z...]
    223 	{`[[:upper:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`},
    224 	{`[[:lower:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`},
    225 }
    226 
    227 func TestParseFoldCase(t *testing.T) {
    228 	testParseDump(t, foldcaseTests, FoldCase)
    229 }
    230 
    231 var literalTests = []parseTest{
    232 	{"(|)^$.[*+?]{5,10},\\", "str{(|)^$.[*+?]{5,10},\\}"},
    233 }
    234 
    235 func TestParseLiteral(t *testing.T) {
    236 	testParseDump(t, literalTests, Literal)
    237 }
    238 
    239 var matchnlTests = []parseTest{
    240 	{`.`, `dot{}`},
    241 	{"\n", "lit{\n}"},
    242 	{`[^a]`, `cc{0x0-0x60 0x62-0x10ffff}`},
    243 	{`[a\n]`, `cc{0xa 0x61}`},
    244 }
    245 
    246 func TestParseMatchNL(t *testing.T) {
    247 	testParseDump(t, matchnlTests, MatchNL)
    248 }
    249 
    250 var nomatchnlTests = []parseTest{
    251 	{`.`, `dnl{}`},
    252 	{"\n", "lit{\n}"},
    253 	{`[^a]`, `cc{0x0-0x9 0xb-0x60 0x62-0x10ffff}`},
    254 	{`[a\n]`, `cc{0xa 0x61}`},
    255 }
    256 
    257 func TestParseNoMatchNL(t *testing.T) {
    258 	testParseDump(t, nomatchnlTests, 0)
    259 }
    260 
    261 // Test Parse -> Dump.
    262 func testParseDump(t *testing.T, tests []parseTest, flags Flags) {
    263 	for _, tt := range tests {
    264 		re, err := Parse(tt.Regexp, flags)
    265 		if err != nil {
    266 			t.Errorf("Parse(%#q): %v", tt.Regexp, err)
    267 			continue
    268 		}
    269 		if tt.Dump == "" {
    270 			// It parsed. That's all we care about.
    271 			continue
    272 		}
    273 		d := dump(re)
    274 		if d != tt.Dump {
    275 			t.Errorf("Parse(%#q).Dump() = %#q want %#q", tt.Regexp, d, tt.Dump)
    276 		}
    277 	}
    278 }
    279 
    280 // dump prints a string representation of the regexp showing
    281 // the structure explicitly.
    282 func dump(re *Regexp) string {
    283 	var b bytes.Buffer
    284 	dumpRegexp(&b, re)
    285 	return b.String()
    286 }
    287 
    288 var opNames = []string{
    289 	OpNoMatch:        "no",
    290 	OpEmptyMatch:     "emp",
    291 	OpLiteral:        "lit",
    292 	OpCharClass:      "cc",
    293 	OpAnyCharNotNL:   "dnl",
    294 	OpAnyChar:        "dot",
    295 	OpBeginLine:      "bol",
    296 	OpEndLine:        "eol",
    297 	OpBeginText:      "bot",
    298 	OpEndText:        "eot",
    299 	OpWordBoundary:   "wb",
    300 	OpNoWordBoundary: "nwb",
    301 	OpCapture:        "cap",
    302 	OpStar:           "star",
    303 	OpPlus:           "plus",
    304 	OpQuest:          "que",
    305 	OpRepeat:         "rep",
    306 	OpConcat:         "cat",
    307 	OpAlternate:      "alt",
    308 }
    309 
    310 // dumpRegexp writes an encoding of the syntax tree for the regexp re to b.
    311 // It is used during testing to distinguish between parses that might print
    312 // the same using re's String method.
    313 func dumpRegexp(b *bytes.Buffer, re *Regexp) {
    314 	if int(re.Op) >= len(opNames) || opNames[re.Op] == "" {
    315 		fmt.Fprintf(b, "op%d", re.Op)
    316 	} else {
    317 		switch re.Op {
    318 		default:
    319 			b.WriteString(opNames[re.Op])
    320 		case OpStar, OpPlus, OpQuest, OpRepeat:
    321 			if re.Flags&NonGreedy != 0 {
    322 				b.WriteByte('n')
    323 			}
    324 			b.WriteString(opNames[re.Op])
    325 		case OpLiteral:
    326 			if len(re.Rune) > 1 {
    327 				b.WriteString("str")
    328 			} else {
    329 				b.WriteString("lit")
    330 			}
    331 			if re.Flags&FoldCase != 0 {
    332 				for _, r := range re.Rune {
    333 					if unicode.SimpleFold(r) != r {
    334 						b.WriteString("fold")
    335 						break
    336 					}
    337 				}
    338 			}
    339 		}
    340 	}
    341 	b.WriteByte('{')
    342 	switch re.Op {
    343 	case OpEndText:
    344 		if re.Flags&WasDollar == 0 {
    345 			b.WriteString(`\z`)
    346 		}
    347 	case OpLiteral:
    348 		for _, r := range re.Rune {
    349 			b.WriteRune(r)
    350 		}
    351 	case OpConcat, OpAlternate:
    352 		for _, sub := range re.Sub {
    353 			dumpRegexp(b, sub)
    354 		}
    355 	case OpStar, OpPlus, OpQuest:
    356 		dumpRegexp(b, re.Sub[0])
    357 	case OpRepeat:
    358 		fmt.Fprintf(b, "%d,%d ", re.Min, re.Max)
    359 		dumpRegexp(b, re.Sub[0])
    360 	case OpCapture:
    361 		if re.Name != "" {
    362 			b.WriteString(re.Name)
    363 			b.WriteByte(':')
    364 		}
    365 		dumpRegexp(b, re.Sub[0])
    366 	case OpCharClass:
    367 		sep := ""
    368 		for i := 0; i < len(re.Rune); i += 2 {
    369 			b.WriteString(sep)
    370 			sep = " "
    371 			lo, hi := re.Rune[i], re.Rune[i+1]
    372 			if lo == hi {
    373 				fmt.Fprintf(b, "%#x", lo)
    374 			} else {
    375 				fmt.Fprintf(b, "%#x-%#x", lo, hi)
    376 			}
    377 		}
    378 	}
    379 	b.WriteByte('}')
    380 }
    381 
    382 func mkCharClass(f func(rune) bool) string {
    383 	re := &Regexp{Op: OpCharClass}
    384 	lo := rune(-1)
    385 	for i := rune(0); i <= unicode.MaxRune; i++ {
    386 		if f(i) {
    387 			if lo < 0 {
    388 				lo = i
    389 			}
    390 		} else {
    391 			if lo >= 0 {
    392 				re.Rune = append(re.Rune, lo, i-1)
    393 				lo = -1
    394 			}
    395 		}
    396 	}
    397 	if lo >= 0 {
    398 		re.Rune = append(re.Rune, lo, unicode.MaxRune)
    399 	}
    400 	return dump(re)
    401 }
    402 
    403 func isUpperFold(r rune) bool {
    404 	if unicode.IsUpper(r) {
    405 		return true
    406 	}
    407 	c := unicode.SimpleFold(r)
    408 	for c != r {
    409 		if unicode.IsUpper(c) {
    410 			return true
    411 		}
    412 		c = unicode.SimpleFold(c)
    413 	}
    414 	return false
    415 }
    416 
    417 func TestFoldConstants(t *testing.T) {
    418 	last := rune(-1)
    419 	for i := rune(0); i <= unicode.MaxRune; i++ {
    420 		if unicode.SimpleFold(i) == i {
    421 			continue
    422 		}
    423 		if last == -1 && minFold != i {
    424 			t.Errorf("minFold=%#U should be %#U", minFold, i)
    425 		}
    426 		last = i
    427 	}
    428 	if maxFold != last {
    429 		t.Errorf("maxFold=%#U should be %#U", maxFold, last)
    430 	}
    431 }
    432 
    433 func TestAppendRangeCollapse(t *testing.T) {
    434 	// AppendRange should collapse each of the new ranges
    435 	// into the earlier ones (it looks back two ranges), so that
    436 	// the slice never grows very large.
    437 	// Note that we are not calling cleanClass.
    438 	var r []rune
    439 	for i := rune('A'); i <= 'Z'; i++ {
    440 		r = appendRange(r, i, i)
    441 		r = appendRange(r, i+'a'-'A', i+'a'-'A')
    442 	}
    443 	if string(r) != "AZaz" {
    444 		t.Errorf("appendRange interlaced A-Z a-z = %s, want AZaz", string(r))
    445 	}
    446 }
    447 
    448 var invalidRegexps = []string{
    449 	`(`,
    450 	`)`,
    451 	`(a`,
    452 	`a)`,
    453 	`(a))`,
    454 	`(a|b|`,
    455 	`a|b|)`,
    456 	`(a|b|))`,
    457 	`(a|b`,
    458 	`a|b)`,
    459 	`(a|b))`,
    460 	`[a-z`,
    461 	`([a-z)`,
    462 	`[a-z)`,
    463 	`([a-z]))`,
    464 	`x{1001}`,
    465 	`x{9876543210}`,
    466 	`x{2,1}`,
    467 	`x{1,9876543210}`,
    468 	"\xff", // Invalid UTF-8
    469 	"[\xff]",
    470 	"[\\\xff]",
    471 	"\\\xff",
    472 	`(?P<name>a`,
    473 	`(?P<name>`,
    474 	`(?P<name`,
    475 	`(?P<x y>a)`,
    476 	`(?P<>a)`,
    477 	`[a-Z]`,
    478 	`(?i)[a-Z]`,
    479 	`a{100000}`,
    480 	`a{100000,}`,
    481 	"((((((((((x{2}){2}){2}){2}){2}){2}){2}){2}){2}){2})",
    482 }
    483 
    484 var onlyPerl = []string{
    485 	`[a-b-c]`,
    486 	`\Qabc\E`,
    487 	`\Q*+?{[\E`,
    488 	`\Q\\E`,
    489 	`\Q\\\E`,
    490 	`\Q\\\\E`,
    491 	`\Q\\\\\E`,
    492 	`(?:a)`,
    493 	`(?P<name>a)`,
    494 }
    495 
    496 var onlyPOSIX = []string{
    497 	"a++",
    498 	"a**",
    499 	"a?*",
    500 	"a+*",
    501 	"a{1}*",
    502 	".{1}{2}.{3}",
    503 }
    504 
    505 func TestParseInvalidRegexps(t *testing.T) {
    506 	for _, regexp := range invalidRegexps {
    507 		if re, err := Parse(regexp, Perl); err == nil {
    508 			t.Errorf("Parse(%#q, Perl) = %s, should have failed", regexp, dump(re))
    509 		}
    510 		if re, err := Parse(regexp, POSIX); err == nil {
    511 			t.Errorf("Parse(%#q, POSIX) = %s, should have failed", regexp, dump(re))
    512 		}
    513 	}
    514 	for _, regexp := range onlyPerl {
    515 		if _, err := Parse(regexp, Perl); err != nil {
    516 			t.Errorf("Parse(%#q, Perl): %v", regexp, err)
    517 		}
    518 		if re, err := Parse(regexp, POSIX); err == nil {
    519 			t.Errorf("Parse(%#q, POSIX) = %s, should have failed", regexp, dump(re))
    520 		}
    521 	}
    522 	for _, regexp := range onlyPOSIX {
    523 		if re, err := Parse(regexp, Perl); err == nil {
    524 			t.Errorf("Parse(%#q, Perl) = %s, should have failed", regexp, dump(re))
    525 		}
    526 		if _, err := Parse(regexp, POSIX); err != nil {
    527 			t.Errorf("Parse(%#q, POSIX): %v", regexp, err)
    528 		}
    529 	}
    530 }
    531 
    532 func TestToStringEquivalentParse(t *testing.T) {
    533 	for _, tt := range parseTests {
    534 		re, err := Parse(tt.Regexp, testFlags)
    535 		if err != nil {
    536 			t.Errorf("Parse(%#q): %v", tt.Regexp, err)
    537 			continue
    538 		}
    539 		if tt.Dump == "" {
    540 			// It parsed. That's all we care about.
    541 			continue
    542 		}
    543 		d := dump(re)
    544 		if d != tt.Dump {
    545 			t.Errorf("Parse(%#q).Dump() = %#q want %#q", tt.Regexp, d, tt.Dump)
    546 			continue
    547 		}
    548 
    549 		s := re.String()
    550 		if s != tt.Regexp {
    551 			// If ToString didn't return the original regexp,
    552 			// it must have found one with fewer parens.
    553 			// Unfortunately we can't check the length here, because
    554 			// ToString produces "\\{" for a literal brace,
    555 			// but "{" is a shorter equivalent in some contexts.
    556 			nre, err := Parse(s, testFlags)
    557 			if err != nil {
    558 				t.Errorf("Parse(%#q.String() = %#q): %v", tt.Regexp, s, err)
    559 				continue
    560 			}
    561 			nd := dump(nre)
    562 			if d != nd {
    563 				t.Errorf("Parse(%#q) -> %#q; %#q vs %#q", tt.Regexp, s, d, nd)
    564 			}
    565 
    566 			ns := nre.String()
    567 			if s != ns {
    568 				t.Errorf("Parse(%#q) -> %#q -> %#q", tt.Regexp, s, ns)
    569 			}
    570 		}
    571 	}
    572 }
    573